Nikolaeva Y.A. Lab work 07 #7
@ -8,6 +8,23 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<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" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.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.Console" Version="4.1.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@ -24,10 +25,14 @@ namespace Airbus
|
||||
//объект от коллекции карт
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
|
||||
//логер
|
||||
private readonly ILogger _logger;
|
||||
|
||||
//конструктор
|
||||
public FormMapWithSetPlanes()
|
||||
public FormMapWithSetPlanes(ILogger<FormMapWithSetPlanes> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
|
||||
comboBoxSelectorMap.Items.Clear();
|
||||
foreach (var element in _mapsDict)
|
||||
@ -63,6 +68,7 @@ namespace Airbus
|
||||
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||
|
||||
return;
|
||||
}
|
||||
@ -70,12 +76,15 @@ namespace Airbus
|
||||
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
|
||||
{
|
||||
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Отсутствует карта с названием {0}", textBoxNewMapName.Text);
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text,
|
||||
_mapsDict[comboBoxSelectorMap.Text]);
|
||||
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
|
||||
ReloadMaps();
|
||||
}
|
||||
|
||||
@ -83,6 +92,7 @@ namespace Airbus
|
||||
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);
|
||||
}
|
||||
|
||||
// Удаление карты
|
||||
@ -95,7 +105,7 @@ namespace Airbus
|
||||
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();
|
||||
}
|
||||
}
|
||||
@ -103,18 +113,33 @@ namespace Airbus
|
||||
//отрисовка добавленного объекта в хранилище
|
||||
private void AddPlane(DrawningAirbus plane)
|
||||
{
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation("Добавлен объект {@Airbus}", plane);
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -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}. Объект: {@Airbus}", ex.Message, plane);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
}
|
||||
@ -130,7 +155,7 @@ namespace Airbus
|
||||
//удаление объекта
|
||||
private void ButtonRemovePlane_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
|
||||
if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -143,14 +168,30 @@ namespace Airbus
|
||||
|
||||
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 deletedPlane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
|
||||
if (deletedPlane != null)
|
||||
{
|
||||
MessageBox.Show("Объект удалён");
|
||||
_logger.LogInformation("Из текущей карты удалён объект {@Airbus}", deletedPlane);
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (PlaneNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -211,15 +252,19 @@ namespace Airbus
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.SaveData(saveFileDialog.FileName))
|
||||
{
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
|
||||
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -229,16 +274,20 @@ namespace Airbus
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
ReloadMaps();
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
|
||||
|
||||
MessageBox.Show("Загрузка данных прошла успешно", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadMaps();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка загрузки данных", "Результат",
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -28,10 +28,8 @@ namespace Airbus
|
||||
|
||||
//конструктор
|
||||
public MapWithSetPlanesGeneric(int picWidth, int picHeight, U map)
|
||||
{
|
||||
int width = picWidth / _placeSizeWidth;
|
||||
int height = picHeight / _placeSizeHeight;
|
||||
_setPlanes = new SetPlanesGeneric<T>(width * height);
|
||||
{
|
||||
_setPlanes = new SetPlanesGeneric<T>(18);
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_map = map;
|
||||
|
@ -53,8 +53,8 @@ namespace Airbus
|
||||
}
|
||||
}
|
||||
|
||||
// сохранение информации по автомобилям в хранилище в файл
|
||||
public bool SaveData(string filename)
|
||||
// сохранение информации по самолётам в ангарах в файл
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -71,16 +71,14 @@ namespace Airbus
|
||||
$"{Environment.NewLine}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// загрузка информации по автомобилям на парковках из файла
|
||||
public bool LoadData(string filename)
|
||||
// загрузка информации по самолётам в ангарах из файла
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new(filename))
|
||||
@ -90,7 +88,7 @@ namespace Airbus
|
||||
//если не содержит такую запись или пустой файл
|
||||
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
|
||||
{
|
||||
return false;
|
||||
throw new FileFormatException("Формат данных в файле неправильный");
|
||||
}
|
||||
|
||||
_mapStorage.Clear();
|
||||
@ -117,8 +115,6 @@ namespace Airbus
|
||||
_mapStorage[element[0]].LoadData(element[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//доступ к аэродрому
|
||||
|
25
Airbus/Airbus/PlaneNotFoundException.cs
Normal file
25
Airbus/Airbus/PlaneNotFoundException.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Airbus
|
||||
{
|
||||
[Serializable]
|
||||
|
||||
//класс собственных исключений
|
||||
internal class PlaneNotFoundException: ApplicationException
|
||||
{
|
||||
public PlaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
|
||||
public PlaneNotFoundException() : base() { }
|
||||
|
||||
public PlaneNotFoundException(string message) : base(message) { }
|
||||
|
||||
public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -1,3 +1,10 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Extensions.Logging;
|
||||
using System;
|
||||
|
||||
namespace Airbus
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +18,28 @@ namespace Airbus
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetPlanes());
|
||||
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetPlanes>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetPlanes>();
|
||||
|
||||
var serilogLogger = new LoggerConfiguration()
|
||||
|
||||
.WriteTo.RollingFile("Logs\\log.txt")
|
||||
.CreateLogger();
|
||||
|
||||
services.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger: serilogLogger, dispose: true);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -29,6 +29,11 @@ namespace Airbus
|
||||
//добавление объекта в набор
|
||||
public int Insert(T plane)
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
|
||||
if (Count + 1 <= _maxCount) return Insert(plane, 0);
|
||||
else return -1;
|
||||
}
|
||||
@ -36,10 +41,14 @@ namespace Airbus
|
||||
//добавление объекта в набор на конкретную позицию
|
||||
public int Insert(T plane, int position)
|
||||
{
|
||||
if (position >= _maxCount && position < 0)
|
||||
if (position > _maxCount && position < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (_places.Contains(plane))
|
||||
{
|
||||
throw new ArgumentException($"Объект {plane} уже есть в наборе");
|
||||
}
|
||||
|
||||
_places.Insert(position, plane);
|
||||
return position;
|
||||
@ -48,22 +57,16 @@ namespace Airbus
|
||||
//удаление объекта из набора с конкретной позиции
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < _maxCount && position >= 0)
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
|
||||
if (_places.ElementAt(position) != null)
|
||||
{
|
||||
T result = _places.ElementAt(position);
|
||||
|
||||
_places.RemoveAt(position);
|
||||
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
throw new PlaneNotFoundException(position);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
T result = _places[position];
|
||||
_places.RemoveAt(position);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
//получение объекта из набора по позиции
|
||||
public T this[int position]
|
||||
|
25
Airbus/Airbus/StorageOverflowException.cs
Normal file
25
Airbus/Airbus/StorageOverflowException.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Airbus
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта