PIbd-22. Stroev V.M. Lab Work 07 #9

Closed
StroevVladimir wants to merge 4 commits from Lab07 into Lab06
8 changed files with 165 additions and 63 deletions

View File

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

View File

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

@ -8,8 +8,12 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Monorail.DrawningObjects; using Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics; using Monorail.Generics;
using Monorail.MovementStrategy; using Monorail.MovementStrategy;
using Monorail.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace Monorail namespace Monorail
{ {
@ -17,12 +21,16 @@ namespace Monorail
public partial class FormMonorailCollection : Form public partial class FormMonorailCollection : Form
{ {
private readonly MonorailsGenericStorage _storage; private readonly MonorailsGenericStorage _storage;
readonly int countPlace = 21;
public FormMonorailCollection() private readonly ILogger _logger;
readonly int countPlace = 22;
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new MonorailsGenericStorage _storage = new MonorailsGenericStorage
(pictureBoxCollection.Width, pictureBoxCollection.Height); (pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
{ {
@ -49,11 +57,13 @@ namespace Monorail
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e) EventArgs e)
@ -67,12 +77,16 @@ EventArgs e)
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?",
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект{name}?",
"Удаление", MessageBoxButtons.YesNo, "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
private void ButtonAddMonorail_Click(object sender, EventArgs e) private void ButtonAddMonorail_Click(object sender, EventArgs e)
@ -103,18 +117,23 @@ EventArgs e)
{ {
return; return;
} }
try
int addedIndex = obj + monorail;
if (addedIndex != -1 && addedIndex < countPlace)
{ {
MessageBox.Show("Объект добавлен"); int addedIndex = obj + monorail;
pictureBoxCollection.Image = obj.ShowMonorails(); if (addedIndex != -1 && addedIndex < countPlace)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Добавлен монорельс");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
} }
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
private void ButtonRemoveMonorail_Click(object sender, EventArgs e) private void ButtonRemoveMonorail_Click(object sender, EventArgs e)
{ {
@ -135,24 +154,27 @@ EventArgs e)
{ {
return; return;
} }
int pos; int pos = 0;
if (maskedTextBoxNumber.Text == "") try
{
MessageBox.Show("Введите позицию элемента выше");
return;
}
else
{ {
pos = Convert.ToInt32(maskedTextBoxNumber.Text); pos = Convert.ToInt32(maskedTextBoxNumber.Text);
} }
if (obj - pos != null) catch (Exception)
{ {
MessageBox.Show("Введите позицию монорельса", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try {
var curObj = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowMonorails(); pictureBoxCollection.Image = obj.ShowMonorails();
} _logger.LogInformation($"Объект удален по позиции: {pos}");
else }catch(MonorailNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось удалить объект по позиции {pos}");
} }
} }
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -172,15 +194,18 @@ EventArgs e)
{ {
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("Сохранение файла");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}",
MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не сохранилось: {ex.Message}");
} }
} }
} }
@ -188,17 +213,20 @@ EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation("Загрузка файла");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось. {ex.Message}",
MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
} }
ReloadObjects();
} }
} }
} }

View File

@ -37,10 +37,7 @@ namespace Monorail.Generics
public static T? operator -(MonorailsGenericCollection<T, U> collect, int pos) public static T? operator -(MonorailsGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null) collect._collection.Remove(pos);
{
collect._collection.Remove(pos);
}
return obj; return obj;
} }
public U? GetU(int pos) public U? GetU(int pos)

View File

@ -52,7 +52,7 @@ namespace Monorail.Generics
return _monorailsStorages[ind]; return _monorailsStorages[ind];
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -72,28 +72,28 @@ namespace Monorail.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
using StreamWriter sw = new(filename); using StreamWriter sw = new(filename);
sw.Write($"MonorailStorage{Environment.NewLine}{data}"); sw.Write($"MonorailStorage{Environment.NewLine}{data}");
return true; return;
} }
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 sr = File.OpenText(filename)) using (StreamReader sr = File.OpenText(filename))
{ {
string str = sr.ReadLine(); string str = sr.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!str.StartsWith("MonorailStorage")) if (!str.StartsWith("MonorailStorage"))
{ {
return false; throw new Exception("Неверный формат данных");
} }
_monorailsStorages.Clear(); _monorailsStorages.Clear();
@ -101,11 +101,6 @@ namespace Monorail.Generics
while ((strs = sr.ReadLine()) != null) while ((strs = sr.ReadLine()) != null)
{ {
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
@ -122,15 +117,14 @@ namespace Monorail.Generics
{ {
if ((collection + monorail) == -1) if ((collection + monorail) == -1)
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
_monorailsStorages.Add(record[0], collection); _monorailsStorages.Add(record[0], collection);
} }
return true;
} }
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using Monorail.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -23,15 +24,12 @@ namespace Monorail.Generics
} }
public int Insert(T monorail, int position) public int Insert(T monorail, int position)
{ {
if (Count == _maxCount) if (Count == _maxCount || position >= _maxCount)
return -1; throw new StorageOverflowException(Count);
if (position < 0 || monorail == null) if (position < 0 || monorail == null)
return -1; throw new StorageOverflowException("Ошибка. Объект не найден или введённый " +
"номер позиции = отрицательное число");
if (position >= _maxCount)
return -1;
if (Count == 0) if (Count == 0)
{ {
@ -48,7 +46,7 @@ namespace Monorail.Generics
// TODO проверка позиции // TODO проверка позиции
if (position >= Count) if (position >= Count)
{ {
return false; throw new MonorailNotFoundException(position);
} }
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (_places[position] != null) if (_places[position] != null)
@ -58,7 +56,7 @@ namespace Monorail.Generics
} }
else else
{ {
return false; throw new MonorailNotFoundException(position);
} }
} }
public T? this[int position] public T? this[int position]

View File

@ -8,4 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Xml" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using System.Configuration;
using Serilog.Settings.AppSettings;
using Serilog.Settings.Xml;
using Serilog.Sinks.File;
namespace Monorail namespace Monorail
{ {
internal static class Program internal static class Program
@ -11,7 +20,30 @@ namespace Monorail
// 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 FormMonorailCollection());
string logFolderPath = Path.Combine(AppContext.BaseDirectory, "Logs");
string logFilePath = Path.Combine(logFolderPath, "monoraillog-{Date}.log");
Log.Logger = new LoggerConfiguration()
Review

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

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
.MinimumLevel.Debug()
.WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
.CreateLogger();
var services = new ServiceCollection();
ConfigureServices(services);
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.AddSerilog(Log.Logger);
});
} }
} }
} }