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.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip
{
@ -23,12 +26,17 @@ namespace ProjectWarmlyShip
/// </summary>
private readonly ShipsGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
@ -66,6 +74,7 @@ namespace ProjectWarmlyShip
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
@ -89,11 +98,13 @@ namespace ProjectWarmlyShip
{
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()
?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
@ -116,15 +127,24 @@ namespace ProjectWarmlyShip
FormShipConfig form = new FormShipConfig();
Action<DrawningShip>? ShipDelegate = 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.ShowShips();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
});
form.AddEvent(ShipDelegate);
@ -139,6 +159,7 @@ namespace ProjectWarmlyShip
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -152,15 +173,31 @@ namespace ProjectWarmlyShip
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Некорректные данные");
_logger.LogWarning("Некорректные данные");
}
}
/// <summary>
@ -191,15 +228,18 @@ namespace ProjectWarmlyShip
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_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}");
}
}
}
@ -213,14 +253,17 @@ namespace ProjectWarmlyShip
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
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
{
internal static class Program
@ -11,7 +13,31 @@ namespace ProjectWarmlyShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -1,4 +1,5 @@
using System;
using ProjectWarmlyShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
@ -53,10 +54,10 @@ namespace ProjectWarmlyShip.Generics
public bool Insert(T ship, int position)
{
if (position < 0 || position >= _maxCount)
return false;
throw new ShipNotFoundException(position);
if (Count >= _maxCount)
return false;
throw new StorageOverflowException(Count);
_places.Insert(0, ship);
return true;
@ -68,10 +69,9 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false;
if (position < 0 || position > _places.Count)
throw new ShipNotFoundException(position);
_places.RemoveAt(position);
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.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.Exceptions;
using System.Numerics;
namespace ProjectWarmlyShip
{
@ -93,7 +95,7 @@ namespace ProjectWarmlyShip
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -112,26 +114,24 @@ namespace ProjectWarmlyShip
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename, false))
{
writer.WriteLine("ShipStorage");
writer.Write(data.ToString());
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </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))
@ -139,17 +139,26 @@ namespace ProjectWarmlyShip
string cheker = reader.ReadLine();
if (cheker == null)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (!cheker.StartsWith("ShipStorage"))
{
return false;
throw new Exception("Неверный формат данных");
}
_shipStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
{
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0];
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
@ -158,15 +167,19 @@ namespace ProjectWarmlyShip
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
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);
}
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"
}
}
}