3 Commits

Author SHA1 Message Date
MaxKarme
9df56cdb4d logging 2022-11-30 08:16:52 +03:00
MaxKarme
7e4fd641e7 fix bugs 2022-11-25 16:04:36 +03:00
MaxKarme
d43966d9eb Генерация ошибок 2022-11-25 15:57:11 +03:00
8 changed files with 169 additions and 59 deletions

View File

@@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<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="Serilog.Extensions.Hosting" Version="5.0.1" />
<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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +36,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="loggerConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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

View File

@@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -24,9 +25,14 @@ namespace AirFighter
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetCars()
private readonly ILogger _logger;
public FormMapWithSetCars(ILogger<FormMapWithSetCars> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, _mapsCollection = new MapsCollection(pictureBox.Width,
pictureBox.Height); pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
@@ -70,6 +76,7 @@ namespace AirFighter
{ {
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
_logger.LogInformation("При попытке создания карты не все данные заполнены");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
@@ -77,15 +84,18 @@ namespace AirFighter
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation($"Нет карты с названием {comboBoxSelectorMap.Text}");
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]); _mapsDict[comboBoxSelectorMap.Text]);
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
ReloadMaps(); ReloadMaps();
} }
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
_logger?.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString()}");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
@@ -101,6 +111,7 @@ namespace AirFighter
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ??
string.Empty); string.Empty);
_logger.LogInformation($"Удаление карты {listBoxMaps.SelectedItem}");
ReloadMaps(); ReloadMaps();
} }
} }
@@ -112,15 +123,23 @@ namespace AirFighter
return; return;
} }
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectAirFighter(aircraft) != -1) try
{ {
MessageBox.Show("Объект добавлен"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectAirFighter(aircraft) != -1)
pictureBox.Image = {
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); MessageBox.Show("Объект добавлен");
} pictureBox.Image =
else _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("На карту добавлен новый объект");
}
} catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show($"Ошибка переполнения: {ex.Message}");
_logger.LogWarning($"Ошибка переполнения: {ex.Message}");
} catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
} }
} }
@@ -151,16 +170,27 @@ namespace AirFighter
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{ {
MessageBox.Show("Объект удален"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
pictureBox.Image = {
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); MessageBox.Show("Объект удален");
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удален объект на позиции {pos}");
}
} catch (AircraftNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка при удалении объекта на позиции {pos}: {ex.Message}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка при удалении объекта на позиции {pos}: {ex.Message}");
} }
} }
@@ -176,6 +206,7 @@ namespace AirFighter
return; return;
} }
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Показ хранилища");
} }
/// <summary> /// <summary>
@@ -190,6 +221,7 @@ namespace AirFighter
return; return;
} }
pictureBox.Image =_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap(); pictureBox.Image =_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
_logger.LogInformation("Просмотр карты");
} }
/// <summary> /// <summary>
/// Перемещение /// Перемещение
@@ -221,43 +253,39 @@ namespace AirFighter
break; break;
} }
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
try
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) _mapsCollection.SaveData(saveFileDialog.FileName);
{ MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Сохранение прошло успешно", "Результат", _logger.LogInformation($"Успешное сохранение в файл {saveFileDialog.FileName}");
MessageBoxButtons.OK, MessageBoxIcon.Information); } catch(Exception ex)
} {
else MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ _logger.LogWarning($"Ошибка при сохранении в файл {saveFileDialog.FileName}: {ex.Message}");
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
// TODO продумать логику if (openFileDialog.ShowDialog() != DialogResult.OK) return;
if (openFileDialog.ShowDialog() == DialogResult.OK) try
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) _mapsCollection.LoadData(openFileDialog.FileName);
{ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Загрузка прошла успешно", "Результат", _logger.LogInformation($"Успешная загрузка из файла {openFileDialog.FileName}");
MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps();
ReloadMaps(); } catch(Exception ex)
} {
else MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ _logger.LogWarning($"Ошибка при загрузке из файла {openFileDialog.FileName}: {ex.Message}");
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }

View File

@@ -44,7 +44,7 @@ namespace AirFighter
_mapStorages.Remove(name); _mapStorages.Remove(name);
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@@ -59,14 +59,13 @@ namespace AirFighter
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader fs = new(filename)) using (StreamReader fs = new(filename))
{ {
@@ -74,7 +73,7 @@ namespace AirFighter
if (!current.Contains("MapsCollection")) if (!current.Contains("MapsCollection"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
return false; throw new FileFormatException("Не правильный формат данных");
} }
_mapStorages.Clear(); _mapStorages.Clear();
@@ -96,8 +95,6 @@ namespace AirFighter
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _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 AirFighter namespace AirFighter
{ {
internal static class Program internal static class Program
@@ -8,10 +13,30 @@ namespace AirFighter
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetCars()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetCars>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetCars>()
.AddLogging(option =>
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("loggerConfig.json")
.Build();
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(config).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog();
});
} }
} }
} }

View File

@@ -30,18 +30,13 @@ namespace AirFighter
public int Insert(T car) public int Insert(T car)
{ {
// TODO вставка в начало набора // TODO вставка в начало набора
if (_places.Count == _maxCount) return -1; if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(0, car); _places.Insert(0, car);
return 0; return 0;
} }
public int Insert(T car, int position) public int Insert(T car, int position)
{ {
// TODO проверка позиции if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
if (_places.Count == _maxCount) return -1;
_places.Insert(position, car); _places.Insert(position, car);
return position; return position;
} }
@@ -52,10 +47,12 @@ namespace AirFighter
/// <returns></returns> /// <returns></returns>
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции if(position >= _maxCount || position >= _places.Count) throw new AircraftNotFoundException(position);
// TODO удаление объекта из массива, присовив элементу массива значение null
T res = _places[position]; T res = _places[position];
_places.Remove(res); _places.Remove(res);
if (res == null) throw new AircraftNotFoundException(position);
return res; return res;
} }
/// <summary> /// <summary>

View File

@@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace AirFighter
{
[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,17 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "{Level:u4}: {Message:lj} [{Timestamp:HH:mm:ss.fff}]{NewLine}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
}