Musoev D.T. LabWork07 #7

Closed
Denis wants to merge 3 commits from LabWork07 into LabWork06
8 changed files with 184 additions and 25 deletions

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 AirplaneWithRadar
{
[Serializable]
internal class AirplaneNotFoundException : ApplicationException
{
public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public AirplaneNotFoundException() : base() { }
public AirplaneNotFoundException(string message) : base(message) { }
public AirplaneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected AirplaneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -8,6 +8,23 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Configuration.ConfigurationBuilders.Environment" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" 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="Microsoft.Extensions.Logging.Configuration" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.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>

View File

@ -87,6 +87,10 @@ namespace AirplaneWithRadar
_airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, labelBaseColor.BackColor, labelDopColor.BackColor,
checkBoxAddRadar.Checked, checkBoxAddLadder.Checked, checkBoxAddWindow.Checked);
break;
case null:
throw new AirplaneNotFoundException(0);
break;
}
DrawAirplane();

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -24,9 +25,11 @@ namespace AirplaneWithRadar
{"Карта туманного неба с грозой", new FoggySkyMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetAirplane()
private ILogger _logger;
public FormMapWithSetAirplane(ILogger<FormMapWithSetAirplane> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapDict)
@ -85,20 +88,34 @@ namespace AirplaneWithRadar
}
private void AddAirplane(DrawningAirplane airplane)
{
if (ListBoxMaps.SelectedIndex == -1)
try
{
return;
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Airplane}", airplane);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
catch (StorageOverflowException ex)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
catch (ArgumentException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, airplane);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Добавление объекта
@ -131,15 +148,30 @@ namespace AirplaneWithRadar
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty] - pos != null)
try
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
var deletedAirplane = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedAirplane != null)
{
MessageBox.Show("Объект удалён");
_logger.LogInformation("Из текущей карты удалён объект {@Ship}", deletedAirplane);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (AirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@ -204,11 +236,13 @@ namespace AirplaneWithRadar
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return;
}
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
@ -218,11 +252,13 @@ namespace AirplaneWithRadar
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
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);
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
@ -235,6 +271,7 @@ namespace AirplaneWithRadar
{
_mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
/// <summary>
@ -249,11 +286,13 @@ namespace AirplaneWithRadar
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
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);
}
}
}
@ -270,11 +309,13 @@ namespace AirplaneWithRadar
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirplaneWithRadar
{
internal static class Program
@ -11,7 +17,34 @@ namespace AirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetAirplane());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirplane>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormMapWithSetAirplane>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\serilog.json", optional: false, reloadOnChange: true)
Review

Путь до файла конфигурации не должен быть абсолютным

Путь до файла конфигурации не должен быть абсолютным
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -26,20 +26,26 @@
// Добавление объекта в набор на конкретную позицию
public int Insert(T airplane, int position)
{
if (position >= _maxCount || position < 0) return -1;
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > _maxCount) return -1;
_places.Insert(position, airplane);
return position;
}
// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
// проверка позиции
if (position >= _maxCount || position < 0) return null;
// удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
if (position >= Count || position < 0)
{
throw new AirplaneNotFoundException(position);
}
T airplane = _places[position];
_places.RemoveAt(position);
return temp;
}
return airplane;
}
// Получение объекта из набора по позиции
public T this[int position]
{

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 AirplaneWithRadar
{
[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 context) : base(info, context) { }
}
}

View 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": "ContainerShip"
}
}
}