PIbd-22. Shabunov O.A. Lab work 07 #7

Closed
olshab wants to merge 8 commits from Lab7 into Lab6
9 changed files with 205 additions and 46 deletions

View File

@ -27,4 +27,18 @@
<Folder Include="MovementStrategy\" />
</ItemGroup>
<ItemGroup>
<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.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,28 @@
using System.Runtime.Serialization;
namespace AirBomber.Exceptions
{
[Serializable]
internal class EntityNotFoundException : ApplicationException
{
public EntityNotFoundException(int i)
: base($"Не найден объект по позиции {i}")
{ }
public EntityNotFoundException()
: base()
{ }
public EntityNotFoundException(string Message)
: base(Message)
{ }
public EntityNotFoundException(string Message, Exception Exception)
: base(Message, Exception)
{ }
public EntityNotFoundException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@ -0,0 +1,28 @@
using System.Runtime.Serialization;
namespace AirBomber.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)
{ }
public StorageOverflowException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@ -1,5 +1,7 @@
using AirBomber.Generics;
using AirBomber.Exceptions;
using AirBomber.Generics;
using AirBomber.Rendering;
using Microsoft.Extensions.Logging;
namespace AirBomber
{
@ -7,11 +9,14 @@ namespace AirBomber
{
private readonly EntitiesGenericStorage _storage;
public FormEntityCollection()
private readonly ILogger _logger;
public FormEntityCollection(ILogger<FormEntityCollection> Logger)
{
InitializeComponent();
_storage = new EntitiesGenericStorage(CollectionPictureBox.Width, CollectionPictureBox.Height);
_logger = Logger;
}
private void ReloadObjects()
@ -46,15 +51,26 @@ namespace AirBomber
if (obj is null)
return;
if (obj + (Renderer) != -1)
try
{
MessageBox.Show("Объект добавлен");
CollectionPictureBox.Image = obj.ShowEntities();
}
if (obj + (Renderer) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Объект добавлен");
else
CollectionPictureBox.Image = obj.ShowEntities();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
@ -71,15 +87,26 @@ namespace AirBomber
return;
int Pos = Convert.ToInt32(NumberMaskedTextBox.Text);
if (obj - Pos == true)
try
{
MessageBox.Show("Объект удален");
CollectionPictureBox.Image = obj.ShowEntities();
if (obj - Pos == true)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Объект удален");
CollectionPictureBox.Image = obj.ShowEntities();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
}
}
else
catch (EntityNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
}
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
public void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -99,11 +126,15 @@ namespace AirBomber
if (string.IsNullOrEmpty(SetNameTextBox.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не все данные заполнены");
return;
}
_storage.AddSet(SetNameTextBox.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {SetNameTextBox.Text}");
}
private void ButtonRemoveSet_Click(object sender, EventArgs e)
@ -111,15 +142,19 @@ namespace AirBomber
if (StorageListBox.SelectedIndex == -1)
return;
string SetName = StorageListBox.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show(
$"Удалить объект{StorageListBox.SelectedItem}?",
$"Удалить объект{SetName}?",
"Удаление",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
) == DialogResult.Yes)
{
_storage.RemoveSet(StorageListBox.SelectedItem.ToString() ?? string.Empty);
_storage.RemoveSet(SetName);
ReloadObjects();
_logger.LogInformation($"Удален набор: {SetName}");
}
}
@ -132,10 +167,18 @@ namespace AirBomber
{
if (SaveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(SaveFileDialog.FileName))
try
{
_storage.SaveData(SaveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Сохранение прошло успешно");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не сохранилось: {ex.Message}");
}
}
}
@ -143,10 +186,18 @@ namespace AirBomber
{
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(OpenFileDialog.FileName))
try
{
_storage.LoadData(OpenFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Загрузка прошла успешно");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
ReloadObjects();

View File

@ -1,4 +1,5 @@
using AirBomber.MovementStrategy;
using AirBomber.Exceptions;
using AirBomber.MovementStrategy;
using AirBomber.Rendering;
namespace AirBomber.Generics
@ -36,12 +37,7 @@ namespace AirBomber.Generics
public static bool operator -(EntitiesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
return collect._collection.Remove(pos);
return false;
return collect._collection.Remove(pos);
}
public U? GetU(int pos)

View File

@ -1,4 +1,5 @@
using AirBomber.MovementStrategy;
using AirBomber.Exceptions;
using AirBomber.MovementStrategy;
using AirBomber.Rendering;
using System.Text;
@ -55,10 +56,10 @@ namespace AirBomber.Generics
}
}
public bool SaveData(string FileName)
public void SaveData(string FileName)
{
if (_entityStorages.Count == 0)
return false;
throw new InvalidOperationException("Невалидная операция: нет данных для сохранения");
using (StreamWriter writer = new StreamWriter(FileName, false))
{
@ -74,19 +75,17 @@ namespace AirBomber.Generics
writer.WriteLine($"{Record.Key}{_keyValueDelimiter}{Records}");
}
}
return true;
}
public bool LoadData(string FileName)
public void LoadData(string FileName)
{
if (!File.Exists(FileName))
return false;
throw new FileNotFoundException("Файл не найден");
using (StreamReader reader = new StreamReader(FileName))
{
if (reader.ReadLine() != "BomberStorage")
return false;
throw new FormatException("Неверный формат данных");
_entityStorages.Clear();
@ -108,15 +107,13 @@ namespace AirBomber.Generics
if (Renderer != null)
{
if ((Collection + Renderer) == -1)
return false;
throw new StorageOverflowException("Ошибка добавления в коллекцию");
}
}
_entityStorages.Add(Record[0], Collection);
}
}
return true;
}
}
}

View File

@ -1,4 +1,6 @@
namespace AirBomber.Generics
using AirBomber.Exceptions;
namespace AirBomber.Generics
{
internal class SetGeneric<T>
where T : class
@ -27,13 +29,13 @@
return i;
}
return -1;
throw new StorageOverflowException(_maxCount);
}
public int Insert(T Entity, int Position)
{
if (Position >= _maxCount)
return -1;
throw new StorageOverflowException(_maxCount);
if (_objects[Position] is null)
{
@ -41,13 +43,16 @@
return Position;
}
return -1;
throw new StorageOverflowException(_maxCount);
}
public bool Remove(int Position)
{
if (Position >= _maxCount)
return false;
throw new EntityNotFoundException(Position);
if (_objects[Position] is null)
throw new EntityNotFoundException(Position);
_objects[Position] = default(T);
return true;

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirBomber
{
internal static class Program
@ -6,7 +10,30 @@ namespace AirBomber
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new FormEntityCollection());
Log.Logger = new LoggerConfiguration()
Review

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
.MinimumLevel.Debug()
.WriteTo.File("airbomberlog-.log", rollingInterval: RollingInterval.Day)
.CreateLogger();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider ServiceProvider = services.BuildServiceProvider())
{
Application.Run(ServiceProvider.GetRequiredService<FormEntityCollection>());
}
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormEntityCollection>().AddLogging(
option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog();
}
);
}
}
}

13
AirBomber/nlog.config Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
Review

Не используется

Не используется
<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="airbomberlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>