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

Closed
Oleja123 wants to merge 5 commits from Lab7 into Lab6
10 changed files with 125 additions and 34 deletions

View File

@ -15,6 +15,8 @@ namespace Monorail.DrawningObjects
public int GetPosX => _startPosX; public int GetPosX => _startPosX;
char separator = '|';
public int GetPosY => _startPosY; public int GetPosY => _startPosY;
public int GetWidth => _monoRailWidth; public int GetWidth => _monoRailWidth;

View File

@ -1,6 +1,8 @@
using Monorail.Entities; using Microsoft.VisualBasic.Logging;
using Monorail.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;

View File

@ -1,4 +1,6 @@
using Monorail.DrawningObjects; using Microsoft.Extensions.Logging;
using Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics; using Monorail.Generics;
using Monorail.MovementStrategy; using Monorail.MovementStrategy;
using System; using System;
@ -11,6 +13,8 @@ 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;
using Serilog;
namespace Monorail namespace Monorail
{ {
@ -63,16 +67,18 @@ namespace Monorail
form.Show(); form.Show();
Action<DrawningMonorail>? monorailDelegate = new((m) => Action<DrawningMonorail>? monorailDelegate = new((m) =>
{ {
bool q = (obj + m); try
if (q)
{ {
bool q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {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();
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(monorailDelegate); form.AddEvent(monorailDelegate);
@ -95,15 +101,24 @@ namespace Monorail
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); try
if (obj - pos != null)
{ {
int pos = Convert.ToInt32(maskedTextBox.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowMonorails(); pictureBoxCollection.Image = obj.ShowMonorails();
} }
else catch (MonorailNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch(FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
@ -138,9 +153,11 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowMonorail
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();
Log.Information($"Удален набор: {name}");
} }
} }
@ -155,21 +172,26 @@ MessageBoxIcon.Question) == DialogResult.Yes)
} }
_storage.AddSet(storageAddNameBox.Text); _storage.AddSet(storageAddNameBox.Text);
ReloadObjects(); ReloadObjects();
Log.Information($"Добавлен набор: {storageAddNameBox.Text}");
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, 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);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", Log.Warning("Не удалось сохранить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -179,19 +201,23 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{ {
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);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }
ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", Log.Warning("Не удалось загрузить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -6,6 +6,13 @@
<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" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.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

@ -45,7 +45,6 @@ namespace Monorail.Generics
pos) 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;
} }

View File

@ -50,7 +50,7 @@ MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail>> record in _
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
string toWrite = $"MonorailStorage{Environment.NewLine}{data}"; string toWrite = $"MonorailStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, var strs = toWrite.Split(new char[] { '\n', '\r' },
@ -70,7 +70,7 @@ StringSplitOptions.RemoveEmptyEntries);
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; 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)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("MonorailStorage")) if (!strs[0].StartsWith("MonorailStorage"))
{ {
return false; throw new IOException("Неверный формат данных");
} }
_monorailStorages.Clear(); _monorailStorages.Clear();
do do

View File

@ -0,0 +1,20 @@
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 context) : base(info, context) { }
}
}

View File

@ -1,12 +1,20 @@
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;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
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.
@ -14,6 +22,10 @@ namespace Monorail
[STAThread] [STAThread]
static void Main() static void Main()
{ {
Log.Logger = new LoggerConfiguration()
Review

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

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
.WriteTo.File("log.txt")
.MinimumLevel.Debug()
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);

View File

@ -1,8 +1,10 @@
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;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms;
namespace Monorail.Generics namespace Monorail.Generics
{ {
@ -23,7 +25,7 @@ namespace Monorail.Generics
public bool Insert(T monorail) public bool Insert(T monorail)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
return false; throw new StorageOverflowException(_maxCount);
Insert(monorail, 0); Insert(monorail, 0);
return true; return true;
@ -31,7 +33,9 @@ namespace Monorail.Generics
public bool Insert(T monorail, int position) public bool Insert(T monorail, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false; return false;
_places.Insert(position, monorail); _places.Insert(position, monorail);
return true; return true;
@ -39,7 +43,7 @@ namespace Monorail.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
if (!(position >= 0 && position < Count)) if (!(position >= 0 && position < Count))
return false; throw new MonorailNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -0,0 +1,19 @@
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 context) : base(info, context) { }
}
}