Emelyanov A.S. LabWork07 #12

Closed
Emelyanov535 wants to merge 5 commits from LabWork07 into LabWork06
9 changed files with 176 additions and 65 deletions

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings>
</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="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.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

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -28,9 +29,11 @@ namespace Airbus
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetPlanes()
private readonly ILogger _logger;
public FormMapWithSetPlanes(ILogger<FormMapWithSetPlanes> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@ -68,16 +71,19 @@ namespace Airbus
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@ -87,6 +93,7 @@ namespace Airbus
private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
/// Удаление карты
@ -101,6 +108,7 @@ namespace Airbus
}
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);
ReloadMaps();
}
@ -114,25 +122,35 @@ namespace Airbus
{
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlane);
// TODO
formPlaneConfig.Show();
}
private void AddPlane(DrawningPlane plane)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Plane}", plane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
else 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();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
@ -154,14 +172,28 @@ namespace Airbus
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
try{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (PlaneNotFoundException 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>
@ -230,15 +262,16 @@ namespace Airbus
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_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);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -248,14 +281,17 @@ namespace Airbus
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -169,8 +169,6 @@ namespace Airbus
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
(_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
@ -214,7 +212,5 @@ namespace Airbus
_setPlanes.Insert(DrawningObjectPlane.Create(rec) as T);
}
}
}
}

View File

@ -78,21 +78,11 @@ namespace Airbus
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -106,25 +96,24 @@ namespace Airbus
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 FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
return false;
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@ -144,7 +133,6 @@ namespace Airbus
_mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

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 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) { }
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Airbus
{
internal static class Program
@ -11,7 +16,29 @@ 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>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -34,10 +34,7 @@ namespace Airbus
/// <returns></returns>
public int Insert(T plane)
{
// TODO вставка в начало набора
// TODO проверка на _maxCount
if (_places.Count + 1 >= _maxCount)
return -1;
if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(0, plane);
return 0;
}
@ -51,12 +48,7 @@ namespace Airbus
{
// TODO проверка позиции
// TODO вставка по позиции
if (position >= _maxCount || position < 0)
{
return -1;
}
if (_places.Count + 1 >= _maxCount)
return -1;
if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, plane);
return position;
}
@ -69,13 +61,13 @@ namespace Airbus
{
// TODO проверка позиции
// TODO удаление объекта из массива, присовив элементу массива значение null
if (position >= _maxCount || position < 0)
{
return null;
}
T DeletePlane = _places[position];
_places.RemoveAt(position);
return DeletePlane;
if (position >= _maxCount || position >= _places.Count) throw new PlaneNotFoundException(position);
T res = _places[position];
_places.Remove(res);
if (res == null) throw new PlaneNotFoundException(position);
return res;
}
/// <summary>
/// Получение объекта из набора по позиции

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 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) { }
}
}

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"
}
}
}