Compare commits

..

4 Commits

15 changed files with 180 additions and 95 deletions

View File

@ -9,8 +9,13 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" /> <PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -28,7 +28,7 @@ namespace AirplaneWithRadar
/// <summary> /// <summary>
/// Выбранный самолет /// Выбранный самолет
/// </summary> /// </summary>
public DrawningAirplane? SelectedAirplane { get; private set; } public DrawningAirplane? SelectedAirplane { get; set; }
/// <summary> /// <summary>
/// Инициализация формы /// Инициализация формы

View File

@ -133,7 +133,7 @@ namespace AirplaneWithRadar.Generics
int i = 0; int i = 0;
foreach (var airplane in _collection.GetAirplanes()) foreach (var airplane in _collection.GetAirplanes())
{ {
if (airplane!= null) if (airplane != null)
{ {
airplane.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); airplane.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (airplane is DrawningAirplaneWithRadar) if (airplane is DrawningAirplaneWithRadar)

View File

@ -5,6 +5,8 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.Exceptoins;
using System.Numerics;
namespace AirplaneWithRadar.Generics namespace AirplaneWithRadar.Generics
{ {
@ -72,9 +74,8 @@ namespace AirplaneWithRadar.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_airplaneStorages.ContainsKey(name)) if (_airplaneStorages.ContainsKey(name))
return; _airplaneStorages.Remove(name);
_airplaneStorages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -115,14 +116,13 @@ namespace AirplaneWithRadar.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new Exception("Невалиданя операция, нет данных для сохранения"); throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using FileStream fs = new(filename, FileMode.Create); using (StreamWriter writer = new StreamWriter(filename))
byte[] info = new {
UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}"); writer.Write($"AirplaneStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length); }
return;
} }
/// <summary> /// <summary>
/// Загрузка информации по самолетам в хранилище из файла /// Загрузка информации по самолетам в хранилище из файла
@ -133,57 +133,52 @@ namespace AirplaneWithRadar.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не найден"); throw new FileNotFoundException($"Файл {filename} не найден");
} }
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
} using (StreamReader fs = File.OpenText(filename))
if (!strs[0].StartsWith("AirplaneStorage"))
{ {
//если нет такой записи, то это не те данные string str = fs.ReadLine();
throw new Exception("Неверный формат данных"); if (str == null || str.Length == 0)
}
_airplaneStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{ {
continue; throw new NullReferenceException("Нет данных для загрузки");
} }
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> if (!str.StartsWith("AirplaneStorage"))
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{ {
DrawningAirplane? airplane = //если нет такой записи, то это не те данные
elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); throw new FormatException("Неверный формат данных");
if (airplane != null) }
_airplaneStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{ {
if (!(collection + airplane)) throw new NullReferenceException("Нет данных для загрузки");
{ }
throw new Exception("Ошибка добавления в коллекцию");
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null)
{
if (!(collection + airplane))
{
throw new InvalidOperationException("Ошибка добавления в коллекцию");
}
} }
} }
_airplaneStorages.Add(record[0], collection);
} }
_airplaneStorages.Add(record[0], collection);
} }
} }
} }

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirplaneWithRadar"
}
}
}

View File

@ -57,12 +57,12 @@ namespace AirplaneWithRadar.DrawningObjects
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns> /// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height) public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height)
{ {
_pictureWidth = width; if (width <= _airplaneWidth || height <= _airplaneHeight)
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{ {
return; return;
} }
_pictureWidth = width;
_pictureHeight = height;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor); EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
} }
/// <summary> /// <summary>
@ -78,14 +78,14 @@ namespace AirplaneWithRadar.DrawningObjects
protected DrawningAirplane(int speed, double weight, Color bodyColor, int protected DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height, int airplaneWidth, int airplaneHeight) width, int height, int airplaneWidth, int airplaneHeight)
{ {
if (width <= _airplaneWidth || height <= _airplaneHeight)
{
return;
}
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
_airplaneWidth = airplaneWidth; _airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight; _airplaneHeight = airplaneHeight;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return;
}
EntityAirplane = new EntityAirplane(speed, weight, bodyColor); EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
} }
/// <summary> /// <summary>

View File

@ -50,7 +50,6 @@ namespace AirplaneWithRadar.DrawningObjects
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5); g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5); g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
} }
base.DrawTransport(g);
// Штырь // Штырь
if (airplaneWithRadar.Pin) if (airplaneWithRadar.Pin)
{ {
@ -63,6 +62,7 @@ namespace AirplaneWithRadar.DrawningObjects
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) }); g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) });
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) }); g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
} }
base.DrawTransport(g);
} }
public void SetAddColor(Color color) public void SetAddColor(Color color)
{ {

View File

@ -185,14 +185,14 @@
// сохранениеToolStripMenuItem // сохранениеToolStripMenuItem
// //
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(180, 22); сохранениеToolStripMenuItem.Size = new Size(141, 22);
сохранениеToolStripMenuItem.Text = "Сохранение"; сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// загрузкаToolStripMenuItem // загрузкаToolStripMenuItem
// //
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem"; загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(180, 22); загрузкаToolStripMenuItem.Size = new Size(141, 22);
загрузкаToolStripMenuItem.Text = "Загрузка"; загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -210,6 +210,11 @@
// openFileDialog // openFileDialog
// //
openFileDialog.FileName = "openFileDialog1"; openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
// //
// FormAirplaneCollection // FormAirplaneCollection
// //

View File

@ -1,18 +1,17 @@
/*using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;*/ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
//using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Generics; using AirplaneWithRadar.Generics;
using AirplaneWithRadar.Exceptoins; using AirplaneWithRadar.Exceptoins;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
//using NLog.Extensions.Logging;
namespace AirplaneWithRadar namespace AirplaneWithRadar
{ {
@ -52,11 +51,13 @@ namespace AirplaneWithRadar
_storage.SaveData(saveFileDialog.FileName); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Не сохранилось: {ex.Message}", MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не прошло");
} }
} }
} }
@ -74,13 +75,16 @@ namespace AirplaneWithRadar
_storage.LoadData(openFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загружено из файла {openFileDialog.FileName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла");
} }
} }
ReloadObjects();
} }
/// <summary> /// <summary>
@ -141,10 +145,11 @@ namespace AirplaneWithRadar
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Коллекция не выбрана");
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(name); _storage.DelSet(name);
@ -161,6 +166,7 @@ namespace AirplaneWithRadar
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Коллекция не выбрана");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -180,15 +186,17 @@ namespace AirplaneWithRadar
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowAirplanes(); pictureBoxCollection.Image = obj.ShowAirplanes();
_logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Набор переполнен! Не удалось добавить объект");
_logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
}); });
formAirplaneConfig.AddEvent(airplaneDelegate); formAirplaneConfig.AddEvent(airplaneDelegate);
} }
/// <summary> /// <summary>
/// Удаление объекта из набора /// Удаление объекта из набора
/// </summary> /// </summary>
@ -209,24 +217,33 @@ namespace AirplaneWithRadar
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
_logger.LogWarning("Отмена удаления объекта");
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try try
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}");
pictureBoxCollection.Image = obj.ShowAirplanes(); pictureBoxCollection.Image = obj.ShowAirplanes();
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
catch (AirplaneNotFoundException ex) catch (AirplaneNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }

View File

@ -120,6 +120,9 @@
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value> <value>132, 17</value>
</metadata> </metadata>

View File

@ -300,7 +300,7 @@
labelAdditionalColor.TabIndex = 13; labelAdditionalColor.TabIndex = 13;
labelAdditionalColor.Text = "Доп. цвет"; labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelColor_DragDrop; labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter; labelAdditionalColor.DragEnter += labelColor_DragEnter;
// //
// labelBodyColor // labelBodyColor
@ -313,7 +313,7 @@
labelBodyColor.TabIndex = 12; labelBodyColor.TabIndex = 12;
labelBodyColor.Text = "Цвет"; labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter; labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelColor_DragDrop; labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelColor_DragEnter; labelBodyColor.DragEnter += labelColor_DragEnter;
// //
// pictureBoxObject // pictureBoxObject

View File

@ -9,6 +9,8 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Entities; using AirplaneWithRadar.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AirplaneWithRadar namespace AirplaneWithRadar
{ {
@ -99,18 +101,21 @@ namespace AirplaneWithRadar
/// <param name="e"></param> /// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e) private void PanelObject_DragDrop(object sender, DragEventArgs e)
{ {
ILogger<FormAirplaneCollection> logger = new NullLogger<FormAirplaneCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString()) switch (e.Data?.GetData(DataFormats.Text).ToString())
{ {
case "labelSimpleObject": case "labelSimpleObject":
labelAdditionalColor.AllowDrop = false;
_airplane = new DrawningAirplane((int)numericUpDownSpeed.Value, _airplane = new DrawningAirplane((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
pictureBoxObject.Height);
break; break;
case "labelModifiedObject": case "labelModifiedObject":
labelAdditionalColor.AllowDrop = true;
_airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, _airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.DimGray, checkBoxRadar.Checked, (int)numericUpDownWeight.Value, Color.White, Color.DimGray, checkBoxRadar.Checked,
checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
pictureBoxObject.Height);
break; break;
} }
DrawAirplane(); DrawAirplane();
@ -136,19 +141,39 @@ namespace AirplaneWithRadar
{ {
if (_airplane == null) if (_airplane == null)
return; return;
var color = e.Data.GetData(typeof(Color));
switch (((Label)sender).Name) switch (((Label)sender).Name)
{ {
case "labelBodyColor": case "labelBodyColor":
_airplane.SetBodyColor((Color)e.Data.GetData(typeof(Color))); _airplane.EntityAirplane.BodyColor = (Color)color;
break; break;
case "labelAdditionalColor": case "labelAdditionalColor":
if (!(_airplane is DrawningAirplaneWithRadar)) if (!(_airplane is DrawningAirplaneWithRadar))
return; return;
(_airplane as DrawningAirplaneWithRadar).SetAddColor((Color)e.Data.GetData(typeof(Color))); (_airplane as DrawningAirplaneWithRadar).EntityAirplane.BodyColor = (Color)color;
break; break;
} }
DrawAirplane(); DrawAirplane();
} }
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_airplane != null && color != null)
{
_airplane.EntityAirplane.BodyColor = (Color)color;
DrawAirplane();
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_airplane != null && color != null && _airplane.EntityAirplane is EntityAirplaneWithRadar entityAirplaneWithRadar)
{
entityAirplaneWithRadar.AdditionalColor = (Color)color;
DrawAirplane();
}
}
private void labelColor_DragEnter(object sender, DragEventArgs e) private void labelColor_DragEnter(object sender, DragEventArgs e)
{ {

View File

@ -1,6 +1,12 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using System; using System;
namespace AirplaneWithRadar namespace AirplaneWithRadar
@ -25,11 +31,18 @@ namespace AirplaneWithRadar
} }
private static void ConfigureServices(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
{ {
services.AddSingleton<FormAirplaneCollection>() services.AddSingleton<FormAirplaneCollection>().AddLogging(option =>
.AddLogging(option =>
{ {
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config"); option.AddSerilog(logger);
}); });
} }
} }

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using AirplaneWithRadar.Exceptoins;
namespace AirplaneWithRadar.Generics namespace AirplaneWithRadar.Generics
{ {
@ -56,7 +57,14 @@ namespace AirplaneWithRadar.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T airplane, int position) public bool Insert(T airplane, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return false; if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new StorageOverflowException("Невозможно добавить");
}
_places.Insert(position, airplane); _places.Insert(position, airplane);
return true; return true;
} }
@ -67,7 +75,14 @@ namespace AirplaneWithRadar.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) return false; if (position >= Count || position < 0 || position > _maxCount)
{
throw new AirplaneNotFoundException("Невалидная операция");
}
if (_places[position] == null)
{
throw new AirplaneNotFoundException(position);
}
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

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>