PIbd-21. Teryokhin A.S. Lab work 07 #7

Closed
katana wants to merge 1 commits from Lab7Base into Lab6Base
9 changed files with 192 additions and 47 deletions

View File

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

View File

@ -7,6 +7,7 @@ using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.MovementStrategy;
using ProjectSeaplane.Generics;
using System.IO;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.Generics
{
@ -30,7 +31,7 @@ namespace ProjectSeaplane.Generics
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -49,7 +50,7 @@ namespace ProjectSeaplane.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename, false))
{
@ -57,7 +58,7 @@ namespace ProjectSeaplane.Generics
writer.Write(data.ToString());
}
return true;
return;
}
/// <summary>
@ -65,11 +66,11 @@ namespace ProjectSeaplane.Generics
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
using (StreamReader reader = new StreamReader(filename))
@ -77,11 +78,11 @@ namespace ProjectSeaplane.Generics
string cheker = reader.ReadLine();
if (cheker == null)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (!cheker.StartsWith("PlaneStorage"))
{
return false;
throw new Exception("Неверный формат данных");
}
_planeStorages.Clear();
string strs;
@ -90,11 +91,11 @@ namespace ProjectSeaplane.Generics
{
if (strs == null && firstinit)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
return false;
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0];
@ -105,15 +106,20 @@ namespace ProjectSeaplane.Generics
data?.CreateDrawningPlane(_separatorForObject, _pictureWidth, _pictureHeight);
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);
}
return true;
}
}

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectSeaplane
{
internal static class Program
@ -11,7 +15,29 @@ namespace ProjectSeaplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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