Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a6abe240f | ||
|
|
3473802309 | ||
|
|
2a2bac1b20 | ||
|
|
86398dc418 | ||
|
|
7884e5e29c |
@@ -41,5 +41,35 @@ namespace WarmlyShip
|
||||
|
||||
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;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,13 +275,16 @@ namespace WarmlyShip
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.Information($"Сохранение прошло успешно. Сохранено в {saveFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.Warning($"Не удалось сохранить файл {saveFileDialog.FileName}. Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,17 +295,19 @@ namespace WarmlyShip
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO продумать логику
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.Information($"Загрузка файла {openFileDialog.FileName} прошла успешно");
|
||||
ReloadMaps();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.Warning($"Не загрузился файл {openFileDialog.FileName}. Ошибка:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace WarmlyShip
|
||||
/// <summary>
|
||||
/// Интерфейс для работы с объектом, прорисовываемым на форме
|
||||
/// </summary>
|
||||
internal interface IDrawningObject
|
||||
internal interface IDrawningObject : IEquatable<IDrawningObject>
|
||||
{
|
||||
/// <summary>
|
||||
/// Шаг перемещения объекта
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -98,7 +98,7 @@ namespace WarmlyShip
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns></returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@@ -112,25 +112,24 @@ namespace WarmlyShip
|
||||
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка нформации по автомобилям на парковках из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
if (!sr.ReadLine().Contains("MapsCollection"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new Exception("Формат данных в файле не правильный");
|
||||
}
|
||||
|
||||
//очищаем записи
|
||||
@@ -152,7 +151,6 @@ namespace WarmlyShip
|
||||
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
19
WarmlyShip/WarmlyShip/StorageOverflowException.cs
Normal file
19
WarmlyShip/WarmlyShip/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 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) { }
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
19
WarmlyShip/WarmlyShip/WarmlyShipNotFoundException.cs
Normal file
19
WarmlyShip/WarmlyShip/WarmlyShipNotFoundException.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 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) { }
|
||||
}
|
||||
}
|
||||
15
WarmlyShip/WarmlyShip/nlog.config
Normal file
15
WarmlyShip/WarmlyShip/nlog.config
Normal 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>
|
||||
16
WarmlyShip/WarmlyShip/serilog.json
Normal file
16
WarmlyShip/WarmlyShip/serilog.json
Normal 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}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user