ПИбд-23 Салин Олег Алексеевич Лабораторная работа №7 #17

Closed
Oleja123 wants to merge 5 commits from Lab7 into Lab6
5 changed files with 78 additions and 17 deletions
Showing only changes of commit 157ab08659 - Show all commits

View File

@ -1,4 +1,5 @@
using Monorail.DrawningObjects; using Microsoft.Extensions.Logging;
using Monorail.DrawningObjects;
using Monorail.Exceptions; using Monorail.Exceptions;
using Monorail.Generics; using Monorail.Generics;
using Monorail.MovementStrategy; using Monorail.MovementStrategy;
@ -12,18 +13,21 @@ 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 System.Xml.Linq;
namespace Monorail namespace Monorail
{ {
public partial class FormMonorailCollection : Form public partial class FormMonorailCollection : Form
{ {
private readonly MonorailGenericStorage _storage; private readonly MonorailGenericStorage _storage;
private readonly ILogger _logger;
public FormMonorailCollection() public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new MonorailGenericStorage(pictureBoxCollection.Width, _storage = new MonorailGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height); pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
@ -68,6 +72,7 @@ namespace Monorail
{ {
bool q = obj + m; bool q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowMonorails(); pictureBoxCollection.Image = obj.ShowMonorails();
} }
@ -96,17 +101,23 @@ namespace Monorail
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text);
try try
{ {
int pos = Convert.ToInt32(maskedTextBox.Text);
var q = obj - pos; var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowMonorails(); pictureBoxCollection.Image = obj.ShowMonorails();
} }
catch (MonorailNotFoundException ex) catch (MonorailNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
catch(FormatException ex)
{
MessageBox.Show("Введите число");
}
} }
private void updateCollectionButton_Click(object sender, EventArgs e) private void updateCollectionButton_Click(object sender, EventArgs e)
@ -137,12 +148,14 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowMonorail
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty;
_storage.DelSet(name);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
@ -157,6 +170,7 @@ MessageBoxIcon.Question) == DialogResult.Yes)
} }
_storage.AddSet(storageAddNameBox.Text); _storage.AddSet(storageAddNameBox.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {storageAddNameBox.Text}");
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
@ -168,6 +182,7 @@ MessageBoxIcon.Question) == DialogResult.Yes)
_storage.SaveData(saveFileDialog.FileName); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -187,7 +202,8 @@ MessageBoxIcon.Question) == DialogResult.Yes)
_storage.LoadData(openFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach(var collection in _storage.Keys) _logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }

View File

@ -6,6 +6,11 @@
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -21,4 +26,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -70,7 +70,7 @@ StringSplitOptions.RemoveEmptyEntries);
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не найден"); throw new IOException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -79,11 +79,11 @@ StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
throw new Exception("Нет данных для загрузки"); throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("MonorailStorage")) if (!strs[0].StartsWith("MonorailStorage"))
{ {
throw new Exception("Неверный формат данных"); throw new IOException("Неверный формат данных");
} }
_monorailStorages.Clear(); _monorailStorages.Clear();
do do
@ -107,7 +107,7 @@ StringSplitOptions.RemoveEmptyEntries);
{ {
if (!(collection + monorail)) if (!(collection + monorail))
{ {
throw new Exception("Ошибка добавления в коллекцию"); return false;
} }
} }
} }

View File

@ -1,23 +1,43 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace Monorail namespace Monorail
{ {
static class Program internal static class Program
{ {
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles(); ApplicationConfiguration.Initialize();
Application.SetCompatibleTextRenderingDefault(false); var services = new ServiceCollection();
Application.Run(new FormMonorailCollection()); ConfigureServices(services);
Review

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

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMonorailCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMonorailCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<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="${basedir}/monoraillog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
<logger name="*" minlevel="Warning" maxlevel ="Warning" writeTo="tofile" />
</rules>
</nlog>
</configuration>