Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
681b60f6a6 | ||
|
|
7d27bcd94f | ||
|
|
6ddf4f9380 | ||
|
|
f41bd15744 | ||
|
|
aaf1b043b7 | ||
|
|
57dab5fc82 | ||
|
|
8659337eb5 | ||
|
|
271840c48e | ||
|
|
fd8617cbf0 | ||
|
|
c7c8241605 | ||
|
|
697a62d101 | ||
|
|
3d397d9854 | ||
|
|
38732f72cf | ||
|
|
3a6d87df27 | ||
|
|
62a9296290 | ||
|
|
f8ac712f8a | ||
|
|
8062309a2c | ||
|
|
f478227337 | ||
|
|
db90912206 | ||
|
|
eb32a4c319 | ||
|
|
aa2d4c26e1 | ||
|
|
845a719d29 |
19
Boats/Boats/BoatNotFoundException.cs
Normal file
19
Boats/Boats/BoatNotFoundException.cs
Normal 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 Boats
|
||||
{
|
||||
[Serializable]
|
||||
internal class BoatNotFoundException : ApplicationException
|
||||
{
|
||||
public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public BoatNotFoundException() : base() { }
|
||||
public BoatNotFoundException(string message) : base(message) { }
|
||||
public BoatNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,29 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</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.1.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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -23,4 +46,6 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties jsconfig1_1json__JsonSchema="{" /></VisualStudio></ProjectExtensions>
|
||||
|
||||
</Project>
|
||||
@@ -30,5 +30,7 @@ namespace Boats
|
||||
{
|
||||
_boat.DrawTransport(g);
|
||||
}
|
||||
public string GetInfo() => _boat?.GetDataForSave();
|
||||
public static IDrawingObject Create(string data) => new DrawingObjectBoat(data.CreateDrawingBoat());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,5 +37,9 @@ namespace Boats
|
||||
Bobbers = bobbers;
|
||||
Sail = sail;
|
||||
}
|
||||
public void SetDopColor(Color color)
|
||||
{
|
||||
DopColor = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
63
Boats/Boats/ExtentionBoat.cs
Normal file
63
Boats/Boats/ExtentionBoat.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Boats
|
||||
{
|
||||
/// <summary>
|
||||
/// Расширение для класса DrawingBoat
|
||||
/// </summary>
|
||||
internal static class ExtentionBoat
|
||||
{
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly char _separatorForObject = ':';
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
public static DrawingBoat CreateDrawingBoat(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
if (strs.Length == 3)
|
||||
{
|
||||
return new DrawingBoat(
|
||||
Convert.ToInt32(strs[0]),
|
||||
Convert.ToInt32(strs[1]),
|
||||
Color.FromName(strs[2])
|
||||
);
|
||||
}
|
||||
if (strs.Length == 6)
|
||||
{
|
||||
return new DrawingCatamaran(
|
||||
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="drawingBoat"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetDataForSave(this DrawingBoat drawingBoat)
|
||||
{
|
||||
var boat = drawingBoat.Boat;
|
||||
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
|
||||
if (boat is not EntityCatamaran catamaran)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
return $"{str}{_separatorForObject}{catamaran.DopColor.Name}{_separatorForObject}{catamaran.Bobbers}{_separatorForObject}{catamaran.Sail}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,10 +147,9 @@ namespace Boats
|
||||
/// <param name="e"></param>
|
||||
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
labelBaseColor.BackColor = (Color)e.Data.GetData(typeof(Color).ToString());
|
||||
if (_boat == null)
|
||||
return;
|
||||
_boat.Boat.BodyColor = labelBaseColor.BackColor;
|
||||
_boat.Boat.BodyColor = (Color)e.Data.GetData(typeof(Color).ToString());
|
||||
DrawBoat();
|
||||
}
|
||||
/// <summary>
|
||||
@@ -176,10 +175,9 @@ namespace Boats
|
||||
/// <param name="e"></param>
|
||||
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
labelDopColor.BackColor = (Color)e.Data.GetData(typeof(Color).ToString());
|
||||
if (_boat == null || _boat is not DrawingCatamaran)
|
||||
return;
|
||||
(_boat.Boat as EntityCatamaran).DopColor = labelDopColor.BackColor;
|
||||
(_boat.Boat as EntityCatamaran).SetDopColor((Color)e.Data.GetData(typeof(Color).ToString()));
|
||||
DrawBoat();
|
||||
}
|
||||
/// <summary>
|
||||
|
||||
71
Boats/Boats/FormMapWithSetBoats.Designer.cs
generated
71
Boats/Boats/FormMapWithSetBoats.Designer.cs
generated
@@ -45,9 +45,16 @@
|
||||
this.listBoxMaps = new System.Windows.Forms.ListBox();
|
||||
this.ButtonAddMap = new System.Windows.Forms.Button();
|
||||
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
|
||||
this.menuStrip = new System.Windows.Forms.MenuStrip();
|
||||
this.FileToolStripMenuItem = 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.groupBoxInstruments.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
|
||||
this.groupBoxMaps.SuspendLayout();
|
||||
this.menuStrip.SuspendLayout();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// groupBoxInstruments
|
||||
@@ -62,9 +69,9 @@
|
||||
this.groupBoxInstruments.Controls.Add(this.ButtonRemoveBoat);
|
||||
this.groupBoxInstruments.Controls.Add(this.ButtonAddBoat);
|
||||
this.groupBoxInstruments.Dock = System.Windows.Forms.DockStyle.Right;
|
||||
this.groupBoxInstruments.Location = new System.Drawing.Point(901, 0);
|
||||
this.groupBoxInstruments.Location = new System.Drawing.Point(901, 28);
|
||||
this.groupBoxInstruments.Name = "groupBoxInstruments";
|
||||
this.groupBoxInstruments.Size = new System.Drawing.Size(250, 768);
|
||||
this.groupBoxInstruments.Size = new System.Drawing.Size(250, 783);
|
||||
this.groupBoxInstruments.TabIndex = 0;
|
||||
this.groupBoxInstruments.TabStop = false;
|
||||
this.groupBoxInstruments.Text = "Инструменты";
|
||||
@@ -182,9 +189,9 @@
|
||||
// pictureBox
|
||||
//
|
||||
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, 28);
|
||||
this.pictureBox.Name = "pictureBox";
|
||||
this.pictureBox.Size = new System.Drawing.Size(901, 768);
|
||||
this.pictureBox.Size = new System.Drawing.Size(901, 783);
|
||||
this.pictureBox.TabIndex = 1;
|
||||
this.pictureBox.TabStop = false;
|
||||
//
|
||||
@@ -240,14 +247,59 @@
|
||||
this.textBoxNewMapName.Size = new System.Drawing.Size(220, 27);
|
||||
this.textBoxNewMapName.TabIndex = 0;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
|
||||
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
|
||||
this.FileToolStripMenuItem});
|
||||
this.menuStrip.Location = new System.Drawing.Point(0, 0);
|
||||
this.menuStrip.Name = "menuStrip";
|
||||
this.menuStrip.Size = new System.Drawing.Size(1151, 28);
|
||||
this.menuStrip.TabIndex = 12;
|
||||
this.menuStrip.Text = "menuStrip1";
|
||||
//
|
||||
// FileToolStripMenuItem
|
||||
//
|
||||
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
|
||||
this.SaveToolStripMenuItem,
|
||||
this.LoadToolStripMenuItem});
|
||||
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
|
||||
this.FileToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
|
||||
this.FileToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// SaveToolStripMenuItem
|
||||
//
|
||||
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
|
||||
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 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(224, 26);
|
||||
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";
|
||||
//
|
||||
// FormMapWithSetBoats
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(1151, 768);
|
||||
this.ClientSize = new System.Drawing.Size(1151, 811);
|
||||
this.Controls.Add(this.groupBoxMaps);
|
||||
this.Controls.Add(this.pictureBox);
|
||||
this.Controls.Add(this.groupBoxInstruments);
|
||||
this.Controls.Add(this.menuStrip);
|
||||
this.MainMenuStrip = this.menuStrip;
|
||||
this.Name = "FormMapWithSetBoats";
|
||||
this.Text = "Карта с набором элементов";
|
||||
this.groupBoxInstruments.ResumeLayout(false);
|
||||
@@ -255,7 +307,10 @@
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
|
||||
this.groupBoxMaps.ResumeLayout(false);
|
||||
this.groupBoxMaps.PerformLayout();
|
||||
this.menuStrip.ResumeLayout(false);
|
||||
this.menuStrip.PerformLayout();
|
||||
this.ResumeLayout(false);
|
||||
this.PerformLayout();
|
||||
|
||||
}
|
||||
|
||||
@@ -278,5 +333,11 @@
|
||||
private ListBox listBoxMaps;
|
||||
private Button ButtonAddMap;
|
||||
private TextBox textBoxNewMapName;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem FileToolStripMenuItem;
|
||||
private ToolStripMenuItem SaveToolStripMenuItem;
|
||||
private ToolStripMenuItem LoadToolStripMenuItem;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@@ -25,6 +26,7 @@ namespace Boats
|
||||
/// Объект от коллекции карт
|
||||
/// </summary>
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Объект от класса карты с набором объектов
|
||||
/// </summary>
|
||||
@@ -32,9 +34,10 @@ namespace Boats
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormMapWithSetBoats()
|
||||
public FormMapWithSetBoats(ILogger<FormMapWithSetBoats> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
|
||||
ComboBoxSelectorMap.Items.Clear();
|
||||
foreach (var elem in _mapsDict)
|
||||
@@ -124,15 +127,29 @@ namespace Boats
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
pos -= 1;
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
var deletedBoat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
if (deletedBoat != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Удален объект {deletedBoat.GetType().Name}");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}: объект равен null");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (BoatNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -212,6 +229,7 @@ namespace Boats
|
||||
}
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление карты
|
||||
@@ -228,6 +246,7 @@ namespace Boats
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? ""}");
|
||||
ReloadMaps();
|
||||
}
|
||||
}
|
||||
@@ -239,6 +258,7 @@ namespace Boats
|
||||
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem?.ToString() ?? ""}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Listener для добавления новой лодки из формы
|
||||
@@ -246,19 +266,76 @@ namespace Boats
|
||||
/// <param name="drawingBoat"></param>
|
||||
private void AddBoatListener(DrawingBoat drawingBoat)
|
||||
{
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawingObjectBoat boat = new(drawingBoat);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавлен объект {drawingBoat.GetType().Name}");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
DrawingObjectBoat boat = new(drawingBoat);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
|
||||
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
else
|
||||
}
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранить"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation($"Сохранение прошло успешно. Файл: {saveFileDialog.FileName}");
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось сохранить файл '{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);
|
||||
ReloadMaps();
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Открытие файла '{openFileDialog.FileName}' прошло успешно");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось открыть файл {openFileDialog.FileName}. Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>152, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>319, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -38,5 +38,10 @@ namespace Boats
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
(float Left, float Top, float Right, float Bottom) GetCurrentPosition();
|
||||
/// <summary>
|
||||
/// Получение информации по объекту
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
string GetInfo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,5 +239,30 @@ namespace Boats
|
||||
i++;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение данных в виде строки
|
||||
/// </summary>
|
||||
/// <param name="sep"></param>
|
||||
/// <returns></returns>
|
||||
public string GetData(char separatorType, char separatorData)
|
||||
{
|
||||
string data = $"{_map.GetType().Name}{separatorType}";
|
||||
foreach (var boat in _setBoats.GetBoats())
|
||||
{
|
||||
data += $"{boat.GetInfo()}{separatorData}";
|
||||
}
|
||||
return data;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка списка из массива строк
|
||||
/// </summary>
|
||||
/// <param name="records"></param>
|
||||
public void LoadData(string[] records)
|
||||
{
|
||||
foreach (var rec in records)
|
||||
{
|
||||
_setBoats.Insert(DrawingObjectBoat.Create(rec) as T);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static System.Net.Mime.MediaTypeNames;
|
||||
|
||||
namespace Boats
|
||||
{
|
||||
@@ -14,7 +15,7 @@ namespace Boats
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с картами
|
||||
/// </summary>
|
||||
readonly Dictionary<string, MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>> _mapStorages;
|
||||
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий карт
|
||||
/// </summary>
|
||||
@@ -28,13 +29,21 @@ namespace Boats
|
||||
/// </summary>
|
||||
private readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по элементу словаря в файл
|
||||
/// </summary>
|
||||
private readonly char separatorDict = '|';
|
||||
/// <summary>
|
||||
/// Разделитель для записи коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly char separatorData = ';';
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="pictureWidth"></param>
|
||||
/// <param name="pictureHeight"></param>
|
||||
public MapsCollection(int pictureWidth, int pictureHeight)
|
||||
{
|
||||
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>>();
|
||||
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>>();
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
@@ -46,7 +55,7 @@ namespace Boats
|
||||
public void AddMap(string name, AbstractMap map)
|
||||
{
|
||||
// Добавление карты
|
||||
MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
|
||||
MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> newMap = new(_pictureWidth, _pictureHeight, map);
|
||||
_mapStorages.Add(name, newMap);
|
||||
}
|
||||
/// <summary>
|
||||
@@ -67,7 +76,7 @@ namespace Boats
|
||||
/// </summary>
|
||||
/// <param name="ind"></param>
|
||||
/// <returns></returns>
|
||||
public MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap> this[string index]
|
||||
public MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> this[string index]
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -79,5 +88,73 @@ namespace Boats
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по лодкам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns></returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
using (StreamWriter sw = File.CreateText(filename))
|
||||
{
|
||||
sw.WriteLine($"MapsCollection");
|
||||
foreach (var storage in _mapStorages)
|
||||
{
|
||||
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка нформации по лодкам в гавани из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = File.OpenText(filename))
|
||||
{
|
||||
string? currentLine = sr.ReadLine();
|
||||
if (currentLine == null || !currentLine.Contains("MapsCollection"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
throw new FileFormatException("Формат данных в файле не правильный");
|
||||
}
|
||||
//очищаем записи
|
||||
_mapStorages.Clear();
|
||||
currentLine = sr.ReadLine();
|
||||
while (currentLine != null)
|
||||
{
|
||||
var elem = currentLine.Split(separatorDict);
|
||||
AbstractMap map = null;
|
||||
switch (elem[1])
|
||||
{
|
||||
case "SimpleMap":
|
||||
map = new SimpleMap();
|
||||
break;
|
||||
case "OceanMap":
|
||||
map = new OceanMap();
|
||||
break;
|
||||
case "LineMap":
|
||||
map = new LineMap();
|
||||
break;
|
||||
}
|
||||
_mapStorages.Add(
|
||||
elem[0],
|
||||
new MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map)
|
||||
);
|
||||
_mapStorages[elem[0]].LoadData(
|
||||
elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
|
||||
currentLine = sr.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Extensions.Logging;
|
||||
|
||||
namespace Boats
|
||||
{
|
||||
internal static class Program
|
||||
@@ -11,7 +17,30 @@ namespace Boats
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetBoats());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBoats>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetBoats>()
|
||||
.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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,9 @@ namespace Boats
|
||||
public int Insert(T boat)
|
||||
{
|
||||
// Проверка на _maxCount
|
||||
// Если достигли максимального значения - выбрасываем исключение
|
||||
if (Count == _maxCount)
|
||||
return -1;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
// Вставка в начало набора
|
||||
return Insert(boat, 0);
|
||||
}
|
||||
@@ -69,10 +70,12 @@ namespace Boats
|
||||
public T Remove(int position)
|
||||
{
|
||||
// Проверка позиции
|
||||
if (Count == 0 || position < 0 || position >= _maxCount)
|
||||
return null;
|
||||
// Если позиция неверная (пустой быть не может, потому что у нас список),
|
||||
// то выбрасываем исключение
|
||||
if (position < 0 || position >= Count)
|
||||
throw new BoatNotFoundException(position);
|
||||
T boat = _places[position];
|
||||
_places[position] = null;
|
||||
_places.RemoveAt(position);
|
||||
return boat;
|
||||
}
|
||||
public T this[int position]
|
||||
|
||||
19
Boats/Boats/StorageOverflowException.cs
Normal file
19
Boats/Boats/StorageOverflowException.cs
Normal 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 Boats
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
}
|
||||
20
Boats/Boats/appSettings.json
Normal file
20
Boats/Boats/appSettings.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Boats"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user