7 лабораторная работа

This commit is contained in:
katana 2023-12-02 14:47:29 +04:00
parent 7282a6221b
commit 745fe9e98f
9 changed files with 192 additions and 47 deletions

View File

@ -10,6 +10,9 @@ 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 Microsoft.Extensions.Logging;
using System.Xml.Linq;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane namespace ProjectSeaplane
{ {
@ -19,13 +22,17 @@ namespace ProjectSeaplane
/// Набор объектов /// Набор объектов
/// </summary> /// </summary>
private readonly PlanesGenericStorage _storage; private readonly PlanesGenericStorage _storage;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormPlaneCollection() public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -60,10 +67,12 @@ namespace ProjectSeaplane
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
@ -85,15 +94,18 @@ namespace ProjectSeaplane
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление невыбранного набора");
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?",
"Удаление", MessageBoxButtons.YesNo, "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
@ -118,16 +130,26 @@ namespace ProjectSeaplane
Action<DrawningPlane>? planeDelegate = new((m) => Action<DrawningPlane>? planeDelegate = new((m) =>
{ {
bool q = (obj + m); var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (q) if (obj == null)
{ {
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowPlanes(); pictureBoxCollection.Image = obj.ShowPlanes();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
}); });
form.AddEvent(planeDelegate); form.AddEvent(planeDelegate);
form.Show(); form.Show();
@ -141,6 +163,7 @@ namespace ProjectSeaplane
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление объекта из несуществующего набора");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
@ -154,15 +177,33 @@ namespace ProjectSeaplane
{ {
return; return;
} }
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowPlanes(); pictureBoxCollection.Image = obj.ShowPlanes();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (PlaneNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Некорректные данные");
_logger.LogWarning("Некорректные данные");
} }
} }
/// <summary> /// <summary>
@ -196,16 +237,18 @@ namespace ProjectSeaplane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }
/// <summary> /// <summary>
@ -217,17 +260,19 @@ namespace ProjectSeaplane
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
ReloadObjects(); ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectSeaplane.Exceptions
{
[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

@ -48,7 +48,7 @@ namespace ProjectSeaplane.Generics
int height = picHeight / _placeSizeHeight; int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(15);
} }
/// <summary> /// <summary>
/// Перегрузка оператора сложения /// Перегрузка оператора сложения

View File

@ -7,6 +7,7 @@ using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.MovementStrategy; using ProjectSeaplane.MovementStrategy;
using ProjectSeaplane.Generics; using ProjectSeaplane.Generics;
using System.IO; using System.IO;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.Generics namespace ProjectSeaplane.Generics
{ {
@ -30,7 +31,7 @@ namespace ProjectSeaplane.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -49,7 +50,7 @@ namespace ProjectSeaplane.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename, false)) using (StreamWriter writer = new StreamWriter(filename, false))
{ {
@ -57,7 +58,7 @@ namespace ProjectSeaplane.Generics
writer.Write(data.ToString()); writer.Write(data.ToString());
} }
return true; return;
} }
/// <summary> /// <summary>
@ -65,11 +66,11 @@ namespace ProjectSeaplane.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
using (StreamReader reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
@ -77,11 +78,11 @@ namespace ProjectSeaplane.Generics
string cheker = reader.ReadLine(); string cheker = reader.ReadLine();
if (cheker == null) if (cheker == null)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!cheker.StartsWith("PlaneStorage")) if (!cheker.StartsWith("PlaneStorage"))
{ {
return false; throw new Exception("Неверный формат данных");
} }
_planeStorages.Clear(); _planeStorages.Clear();
string strs; string strs;
@ -90,11 +91,11 @@ namespace ProjectSeaplane.Generics
{ {
if (strs == null && firstinit) if (strs == null && firstinit)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (strs == null) if (strs == null)
{ {
return false; break;
} }
firstinit = false; firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0]; string name = strs.Split(_separatorForKeyValue)[0];
@ -105,15 +106,20 @@ namespace ProjectSeaplane.Generics
data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight); data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null) if (plane != null)
{ {
if (!(collection + plane)) try { _ = collection + plane; }
catch (PlaneNotFoundException e)
{ {
return false; throw e;
} }
catch (StorageOverflowException e)
{
throw e;
}
} }
} }
_planeStorages.Add(name, collection); _planeStorages.Add(name, collection);
} }
return true;
} }
} }

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectSeaplane namespace ProjectSeaplane
{ {
internal static class Program internal static class Program
@ -11,7 +15,29 @@ namespace ProjectSeaplane
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormPlaneCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormPlaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormPlaneCollection>().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.AddSerilog(logger);
});
} }
} }
} }

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,4 +1,5 @@
using System; using ProjectSeaplane.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -52,13 +53,14 @@ namespace ProjectSeaplane.Generics
public bool Insert(T plane, int position) public bool Insert(T plane, int position)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return false; throw new PlaneNotFoundException(position);
if (Count >= _maxCount) if (Count > _maxCount)
return false; {
throw new StorageOverflowException(Count);
}
_places.Insert(0, plane); _places.Insert(0, plane);
return true; return true;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@ -67,10 +69,8 @@ namespace ProjectSeaplane.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount || position >= Count)
return false; throw new PlaneNotFoundException(position);
if (position >= Count)
return false;
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectSeaplane.Exceptions
{
[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": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Seaplane"
}
}
}