Prytkina A.V. LabWork07 #8

Closed
anastasia_prytkina wants to merge 4 commits from LabWork07 into LabWork06
12 changed files with 199 additions and 64 deletions

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
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 contex) : base(info, contex) { }
}
}

View File

@ -8,6 +8,29 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<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="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace AirplaneWithRadar
{
/// <summary>
/// Расширение для класса DrawningCar
/// Расширение для класса DrawingAirplane
/// </summary>
internal static class ExtentionAirplane
{

View File

@ -16,7 +16,7 @@ namespace AirplaneWithRadar
public partial class FormAirplaneConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// Переменная-выбранный самолет
/// </summary>
DrawingAirplane _airplane = null;
/// <summary>
@ -164,7 +164,7 @@ namespace AirplaneWithRadar
}
}
/// <summary>
/// Добавление машины
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

View File

@ -1,4 +1,5 @@
using static System.Windows.Forms.DataFormats;
using Microsoft.Extensions.Logging;
using static System.Windows.Forms.DataFormats;
namespace AirplaneWithRadar
{
@ -19,11 +20,16 @@ namespace AirplaneWithRadar
private readonly MapsCollection _mapsCollection;
private Action<DrawingAirplane> AddAction;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetAirplanes()
public FormMapWithSetAirplanes(ILogger<FormMapWithSetAirplanes> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@ -61,15 +67,18 @@ namespace AirplaneWithRadar
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}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
@ -79,6 +88,8 @@ namespace AirplaneWithRadar
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);
}
/// <summary>
/// Удаление карты
@ -94,6 +105,7 @@ namespace AirplaneWithRadar
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();
}
}
@ -112,19 +124,36 @@ namespace AirplaneWithRadar
}
private void AddAirplaneOnMap(DrawingAirplane drawingAirplane)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
return;
}
DrawingObjectAirplane airplane = new(drawingAirplane);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airplane != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен новый объект");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
DrawingObjectAirplane airplane = new(drawingAirplane);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airplane != -1)
catch (StorageOverflowException ex)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning("Неизвестная ошибка: {0}", ex.Message);
}
}
/// <summary>
@ -147,14 +176,31 @@ namespace AirplaneWithRadar
return;
}
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();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Удалён объект на позиции {0}", pos);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
}
}
else
catch (AirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning("Неизвестная ошибка: {0}", ex.Message);
}
}
/// <summary>
@ -223,13 +269,16 @@ namespace AirplaneWithRadar
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
}
else
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);
}
}
}
@ -242,14 +291,18 @@ namespace AirplaneWithRadar
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось загрузить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не удалось загрузить: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось загрузить из файла {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}

View File

@ -169,17 +169,6 @@ namespace AirplaneWithRadar
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawHangar(Graphics g, int x, int y, int width, int height)
{
Pen pen = new(Color.Black, 3);
g.DrawLine(pen, x, y, x + width, y);
g.DrawLine(pen, x, y, x, y + height + 20);
g.DrawLine(pen, x, y + height + 20, x + width, y + height + 20);
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.White, 5);

View File

@ -89,21 +89,11 @@ namespace AirplaneWithRadar
}
}
/// <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))
{
@ -117,25 +107,24 @@ namespace AirplaneWithRadar
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 Exception("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string strFromFile = "";
if ((strFromFile = sr.ReadLine()) == null || !strFromFile.Contains("MapsCollection"))
{
return false;
throw new Exception("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((strFromFile = sr.ReadLine()) != null)
@ -158,7 +147,6 @@ namespace AirplaneWithRadar
_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 AirplaneWithRadar
{
internal static class Program
@ -9,7 +14,31 @@ namespace AirplaneWithRadar
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetAirplanes());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirplanes>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetAirplanes>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -61,6 +61,7 @@ namespace AirplaneWithRadar
// TODO вставка по позиции
if (position < 0 || position >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
return -1;
}
_places.Insert(position, airplane);
@ -74,13 +75,22 @@ namespace AirplaneWithRadar
public T Remove(int position)
{
// TODO проверка позиции
if (position < 0 || position >= Count)
if (position < Count && position >= 0)
{
if (_places.ElementAt(position) != null)
{
T result = _places.ElementAt(position);
_places.RemoveAt(position);
return result;
}
return null;
}
T airplane = _places[position];
_places.RemoveAt(position);
return airplane;
throw new AirplaneNotFoundException(position);
return null;
}
/// <summary>
/// Получение объекта из набора по позиции

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
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 contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "airplaneWithRadar_log-.log",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
}

View File

@ -1,8 +0,0 @@
using System;
public class Class1
{
public Class1()
{
}
}