вроде как доделанная лаба

This commit is contained in:
ArtemEmelyanov 2022-11-26 21:00:21 +04:00
parent 70543c40c7
commit 39f7f8c79b
6 changed files with 47 additions and 47 deletions

View File

@ -8,21 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" 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" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" 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="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -71,11 +71,13 @@ namespace Airbus
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return; return;
} }
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsCollection.AddMap(textBoxNewMapName.Text,
@ -91,6 +93,7 @@ namespace Airbus
private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e) private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
} }
/// <summary> /// <summary>
/// Удаление карты /// Удаление карты
@ -105,6 +108,7 @@ namespace Airbus
} }
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
} }
@ -118,11 +122,12 @@ namespace Airbus
{ {
var formPlaneConfig = new FormPlaneConfig(); var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlane); formPlaneConfig.AddEvent(AddPlane);
// TODO
formPlaneConfig.Show(); formPlaneConfig.Show();
} }
private void AddPlane(DrawningPlane plane) private void AddPlane(DrawningPlane plane)
{
try
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
@ -131,13 +136,22 @@ namespace Airbus
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1) else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Plane}", plane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
} }
} }
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Удаление объекта /// Удаление объекта
/// </summary> /// </summary>
@ -162,19 +176,23 @@ namespace Airbus
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Plane}", _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (PlaneNotFoundException ex) catch (PlaneNotFoundException ex)
{ {
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}"); MessageBox.Show($"Ошибка удаления: {ex.Message}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
} }
} }
@ -247,10 +265,12 @@ namespace Airbus
try try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName); _mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -264,11 +284,13 @@ namespace Airbus
try try
{ {
_mapsCollection.LoadData(openFileDialog.FileName); _mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps(); ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -106,14 +106,14 @@ namespace Airbus
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
string str = ""; string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{ {
throw new Exception("Формат данных в файле не правильный"); throw new FileFormatException("Формат данных в файле не правильный");
} }
_mapStorages.Clear(); _mapStorages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)

View File

@ -1,6 +1,6 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using Serilog;
namespace Airbus namespace Airbus
{ {
@ -24,10 +24,13 @@ namespace Airbus
} }
private static void ConfigureServices(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
{ {
services.AddSingleton<FormMapWithSetPlanes>().AddLogging(option => var serilogLogger = new LoggerConfiguration().WriteTo.File("seriallog.txt").CreateLogger();
services.AddSingleton<FormMapWithSetPlanes>()
.AddLogging(option =>
{ {
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config"); option.AddSerilog(logger: serilogLogger, dispose: true);
}); });
} }
} }

View File

@ -34,12 +34,7 @@ namespace Airbus
/// <returns></returns> /// <returns></returns>
public int Insert(T plane) public int Insert(T plane)
{ {
// TODO вставка в начало набора return Insert(plane, 0); ;
// TODO проверка на _maxCount
if (_places.Count + 1 >= _maxCount)
return -1;
_places.Insert(0, plane);
return 0;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию

View File

@ -1,13 +0,0 @@
<?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>