ISEbd-21. Gruzdev A.P. Lab work 07. #8

Closed
y3nnn wants to merge 2 commits from lab07 into lab06
8 changed files with 195 additions and 40 deletions
Showing only changes of commit 9f3af0505b - Show all commits

View File

@ -11,6 +11,9 @@ using System.Numerics;
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 ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip namespace ProjectWarmlyShip
{ {
@ -23,12 +26,17 @@ namespace ProjectWarmlyShip
/// </summary> /// </summary>
private readonly ShipsGenericStorage _storage; private readonly ShipsGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection(ILogger<FormShipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -66,6 +74,7 @@ namespace ProjectWarmlyShip
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
@ -89,11 +98,13 @@ namespace ProjectWarmlyShip
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(name);
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
/// <summary> /// <summary>
@ -116,15 +127,24 @@ namespace ProjectWarmlyShip
FormShipConfig form = new FormShipConfig(); FormShipConfig form = new FormShipConfig();
Action<DrawningShip>? ShipDelegate = new((m) => Action<DrawningShip>? ShipDelegate = 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.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
}); });
form.AddEvent(ShipDelegate); form.AddEvent(ShipDelegate);
@ -139,6 +159,7 @@ namespace ProjectWarmlyShip
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление объекта из несуществующего набора");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -152,15 +173,31 @@ namespace ProjectWarmlyShip
{ {
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.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (ShipNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Некорректные данные");
_logger.LogWarning("Некорректные данные");
} }
} }
/// <summary> /// <summary>
@ -191,15 +228,18 @@ namespace ProjectWarmlyShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", 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}");
} }
} }
} }
@ -213,14 +253,17 @@ namespace ProjectWarmlyShip
// TODO продумать логику // TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
ReloadObjects(); 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

@ -1,3 +1,5 @@
using System;
namespace ProjectWarmlyShip namespace ProjectWarmlyShip
{ {
internal static class Program internal static class Program
@ -11,7 +13,31 @@ namespace ProjectWarmlyShip
// 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 FormShipCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().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.7" />
<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 ProjectWarmlyShip.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics; using System.Numerics;
@ -53,10 +54,10 @@ namespace ProjectWarmlyShip.Generics
public bool Insert(T ship, int position) public bool Insert(T ship, int position)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return false; throw new ShipNotFoundException(position);
if (Count >= _maxCount) if (Count >= _maxCount)
return false; throw new StorageOverflowException(Count);
_places.Insert(0, ship); _places.Insert(0, ship);
return true; return true;
@ -68,10 +69,9 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _places.Count)
return false; throw new ShipNotFoundException(position);
if (position >= Count)
return false;
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Exceptions
{
[Serializable]
internal class ShipNotFoundException : ApplicationException
{
public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public ShipNotFoundException() : base() { }
public ShipNotFoundException(string message) : base(message) { }
public ShipNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected ShipNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -6,6 +6,8 @@ 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 ProjectWarmlyShip.Exceptions;
using System.Numerics;
namespace ProjectWarmlyShip namespace ProjectWarmlyShip
{ {
@ -93,7 +95,7 @@ namespace ProjectWarmlyShip
/// </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))
{ {
@ -112,26 +114,24 @@ namespace ProjectWarmlyShip
} }
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))
{ {
writer.WriteLine("ShipStorage"); writer.WriteLine("ShipStorage");
writer.Write(data.ToString()); writer.Write(data.ToString());
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </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("Файл не найден");
Review

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

Требовалось заменить класс Exception на его более подходящих наследников
} }
using (StreamReader reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
@ -139,17 +139,26 @@ namespace ProjectWarmlyShip
string cheker = reader.ReadLine(); string cheker = reader.ReadLine();
if (cheker == null) if (cheker == null)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!cheker.StartsWith("ShipStorage")) if (!cheker.StartsWith("ShipStorage"))
{ {
return false; throw new Exception("Неверный формат данных");
} }
_shipStorages.Clear(); _shipStorages.Clear();
string strs; string strs;
bool firstinit = true; bool firstinit = true;
while ((strs = reader.ReadLine()) != null) while ((strs = reader.ReadLine()) != null)
{ {
if (strs == null && firstinit)
{
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0]; string name = strs.Split(_separatorForKeyValue)[0];
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight); ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
@ -158,15 +167,19 @@ namespace ProjectWarmlyShip
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight); data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null) if (ship != null)
{ {
if (!(collection + ship)) try { _ = collection + ship; }
catch (ShipNotFoundException e)
{ {
return false; throw e;
}
catch (StorageOverflowException e)
{
throw e;
} }
} }
} }
_shipStorages.Add(name, collection); _shipStorages.Add(name, collection);
} }
return true;
} }
} }
} }

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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": "WarmlyShip"
}
}
}