Compare commits

..

4 Commits

15 changed files with 180 additions and 95 deletions

View File

@ -9,8 +9,13 @@
</PropertyGroup>
<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="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>

View File

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

View File

@ -5,6 +5,8 @@ using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.Exceptoins;
using System.Numerics;
namespace AirplaneWithRadar.Generics
{
@ -72,8 +74,7 @@ namespace AirplaneWithRadar.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_airplaneStorages.ContainsKey(name))
return;
if (_airplaneStorages.ContainsKey(name))
_airplaneStorages.Remove(name);
}
/// <summary>
@ -115,14 +116,13 @@ namespace AirplaneWithRadar.Generics
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"AirplaneStorage{Environment.NewLine}{data}");
}
}
/// <summary>
/// Загрузка информации по самолетам в хранилище из файла
@ -133,53 +133,47 @@ namespace AirplaneWithRadar.Generics
{
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))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("AirplaneStorage"))
if (!str.StartsWith("AirplaneStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
throw new FormatException("Неверный формат данных");
}
_airplaneStorages.Clear();
foreach (string data in strs)
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (strs == null)
{
throw new NullReferenceException("Нет данных для загрузки");
}
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);
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);
DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null)
{
if (!(collection + airplane))
{
throw new Exception("Ошибка добавления в коллекцию");
throw new InvalidOperationException("Ошибка добавления в коллекцию");
}
}
}
@ -188,3 +182,4 @@ namespace AirplaneWithRadar.Generics
}
}
}
}

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>
public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
if (width <= _airplaneWidth || height <= _airplaneHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
@ -78,14 +78,14 @@ namespace AirplaneWithRadar.DrawningObjects
protected DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height, int airplaneWidth, int airplaneHeight)
{
if (width <= _airplaneWidth || height <= _airplaneHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return;
}
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>

View File

@ -50,7 +50,6 @@ namespace AirplaneWithRadar.DrawningObjects
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
}
base.DrawTransport(g);
// Штырь
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 + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
}
base.DrawTransport(g);
}
public void SetAddColor(Color color)
{

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.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;
namespace AirplaneWithRadar
@ -25,11 +31,18 @@ namespace AirplaneWithRadar
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAirplaneCollection>()
.AddLogging(option =>
services.AddSingleton<FormAirplaneCollection>().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.AddNLog("nlog.config");
option.AddSerilog(logger);
});
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Exceptoins;
namespace AirplaneWithRadar.Generics
{
@ -56,7 +57,14 @@ namespace AirplaneWithRadar.Generics
/// <returns></returns>
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);
return true;
}
@ -67,7 +75,14 @@ namespace AirplaneWithRadar.Generics
/// <returns></returns>
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);
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>