Генерация ошибок. Логирование. Serilog. Изменения в MapsCollection.

This commit is contained in:
Никита Чернышов 2022-12-22 21:20:43 +04:00
parent 0a636cd3f2
commit 60da240f7a
8 changed files with 190 additions and 37 deletions

View File

@ -8,6 +8,27 @@
<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.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<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

@ -9,6 +9,8 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using Microsoft.Extensions.Logging;
using Serilog.Core;
namespace AircraftCarrier
{
@ -27,12 +29,17 @@ namespace AircraftCarrier
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarship()
public FormMapWithSetWarship(ILogger<FormMapWithSetWarship> logger)
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
_logger = logger;
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
@ -71,15 +78,18 @@ namespace AircraftCarrier
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Какое-то поле пустое", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Карта отсутсвует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
@ -89,6 +99,7 @@ namespace AircraftCarrier
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлен переход на карту {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
/// Удаление карты
@ -104,6 +115,7 @@ namespace AircraftCarrier
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@ -124,23 +136,30 @@ namespace AircraftCarrier
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddWarshipOnForm(DrawingWarship drawningWarship)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectWarship warship = new(drawningWarship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship >= 0)
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectWarship(drawningWarship) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Warship}", drawningWarship);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@ -159,16 +178,32 @@ namespace AircraftCarrier
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
var deletedWarship = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedWarship != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@Warship}", deletedWarship);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (WarshipNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </summary>
@ -235,13 +270,16 @@ namespace AircraftCarrier
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
@ -254,14 +292,17 @@ namespace AircraftCarrier
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}

View File

@ -78,7 +78,7 @@ namespace AircraftCarrier
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -92,25 +92,24 @@ namespace AircraftCarrier
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))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
return false;
throw new Exception("Формат данных в файле неправильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@ -129,7 +128,6 @@ namespace AircraftCarrier
_mapStorages.Add(elem[0], new MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}

View File

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

View File

@ -41,6 +41,10 @@ namespace AircraftCarrier
{
return Insert(ship, 0);
}
private bool isCorrectPosition(int position)
{
return 0 <= position && position < _maxCount;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
@ -49,8 +53,14 @@ namespace AircraftCarrier
/// <returns></returns>
public int Insert(T ship, int position)
{
if (position >= _maxCount || position < 0) return -1; _places.Insert(position, ship);
return 1;
if (Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!isCorrectPosition(position))
{
return -1;
}
_places.Insert(position, ship);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@ -59,10 +69,11 @@ namespace AircraftCarrier
/// <returns></returns>
public T Remove(int position)
{
if (position >= _maxCount || position < 0)
if (!isCorrectPosition(position))
return null;
var result = _places[position];
var result = this[position];
if (result == null)
throw new WarshipNotFoundException(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 AircraftCarrier
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

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

View File

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