лаба 7, в процессе

This commit is contained in:
a.puchkina 2023-12-05 20:59:54 +04:00
parent 62d6124a79
commit ef234a35ba
9 changed files with 124 additions and 60 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

@ -5,6 +5,7 @@ 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;
namespace AirplaneWithRadar.Generics namespace AirplaneWithRadar.Generics
{ {
@ -114,14 +115,13 @@ namespace AirplaneWithRadar.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new Exception("Невалиданя операция, нет данных для сохранения"); throw new ArgumentException("Невалиданя операция, нет данных для сохранения");
} }
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>
/// Загрузка информации по самолетам в хранилище из файла /// Загрузка информации по самолетам в хранилище из файла
@ -132,29 +132,28 @@ namespace AirplaneWithRadar.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader reader = new StreamReader(filename))
{ {
byte[] b = new byte[fs.Length]; string str;
UTF8Encoding temp = new(true); while ((str = reader.ReadLine()) != null)
while (fs.Read(b, 0, b.Length) > 0)
{ {
bufferTextFromFile += temp.GetString(b); bufferTextFromFile += str + '\r' + '\n';
} }
} }
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
throw new Exception("Нет данных для загрузки"); throw new ArgumentException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("AirplaneStorage")) if (!strs[0].StartsWith("AirplaneStorage"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных"); throw new InvalidDataException("Неверный формат данных");
} }
_airplaneStorages.Clear(); _airplaneStorages.Clear();
foreach (string data in strs) foreach (string data in strs)
@ -177,8 +176,18 @@ namespace AirplaneWithRadar.Generics
{ {
if (!(collection + airplane)) if (!(collection + airplane))
{ {
throw new Exception("Ошибка добавления в коллекцию"); try
{
_ = collection + airplane;
}
catch (AirplaneNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
} }
} }
} }

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;
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) 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)
{ {
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{ {
return; return;
} }
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor); EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
} }
/// <summary> /// <summary>

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,14 +75,15 @@ 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>
@ -173,21 +175,31 @@ namespace AirplaneWithRadar
var formAirplaneConfig = new FormAirplaneConfig(); var formAirplaneConfig = new FormAirplaneConfig();
formAirplaneConfig.Show(); formAirplaneConfig.Show();
Action<DrawningAirplane>? airplaneDelegate = new((m) => formAirplaneConfig.AddEvent(AddAirplane);
}
private void AddAirplane(DrawningAirplane airplane)
{ {
bool isAddSuccessful = (obj + m); if (listBoxStorages.SelectedIndex == -1)
if (isAddSuccessful)
{ {
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
_ = obj + airplane;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowAirplanes(); pictureBoxCollection.Image = obj.ShowAirplanes();
_logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
});
formAirplaneConfig.AddEvent(airplaneDelegate);
} }
/// <summary> /// <summary>
@ -212,9 +224,9 @@ namespace AirplaneWithRadar
{ {
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("Объект удален");
@ -229,6 +241,7 @@ namespace AirplaneWithRadar
catch (AirplaneNotFoundException ex) catch (AirplaneNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"AirplaneNotFound: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
} }

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

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