This commit is contained in:
kirin 2023-11-28 13:43:14 +04:00
parent cb38f8505d
commit 145c0765f8
8 changed files with 125 additions and 35 deletions

View File

@ -20,4 +20,24 @@
</Compile> </Compile>
</ItemGroup> </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.2-dev-02097" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00968" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ElectricLocomotive.Exceptions;
public class LocoNotFoundException : ApplicationException
{
public LocoNotFoundException(int i) : base($"Не найден объект попозиции {i}") { }
public LocoNotFoundException() : base() { }
public LocoNotFoundException(string message) : base(message) { }
public LocoNotFoundException(string message, Exception exception) :
base(message, exception) { }
protected LocoNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ElectricLocomotive.Exceptions;
[Serializable]
public 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

@ -1,4 +1,6 @@
using System.Windows.Forms; using System.Windows.Forms;
using ElectricLocomotive.Exceptions;
using Serilog;
namespace ElectricLocomotive; namespace ElectricLocomotive;
@ -35,14 +37,18 @@ public partial class FormLocomotivCollection : Form {
FormLocoConfig form = new(); FormLocoConfig form = new();
form.Show(); form.Show();
Action<DrawingLocomotiv>? monorailDelegate = new((m) => { Action<DrawingLocomotiv>? monorailDelegate = new((m) => {
bool q = (obj + m); try
if (q) { {
bool q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {storageListBox.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(collectionPictureBox.Width, collectionPictureBox.Height); m.ChangePictureBoxSize(collectionPictureBox.Width, collectionPictureBox.Height);
collectionPictureBox.Image = obj.ShowLocos(); collectionPictureBox.Image = obj.ShowLocos();
} }
else { catch (StorageOverflowException ex)
MessageBox.Show("Не удалось добавить объект"); {
Log.Warning($"Коллекция {storageListBox.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(monorailDelegate); form.AddEvent(monorailDelegate);
@ -60,13 +66,24 @@ public partial class FormLocomotivCollection : Form {
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
return; return;
} }
int pos = Convert.ToInt32(locoIndexInput.Text);
if (obj - pos != null) { try
{
int pos = Convert.ToInt32(locoIndexInput.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
collectionPictureBox.Image = obj.ShowLocos(); collectionPictureBox.Image = obj.ShowLocos();
} }
else { catch(LocoNotFoundException ex)
MessageBox.Show("Не удалось удалить объект"); {
Log.Warning($"Не получилось удалить объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch(FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
@ -92,9 +109,10 @@ public partial class FormLocomotivCollection : Form {
} }
if (MessageBox.Show($"Удалить объект{storageListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект{storageListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) { MessageBoxIcon.Question) == DialogResult.Yes) {
_storage.DelSet(storageListBox.SelectedItem.ToString() string name = storageListBox.SelectedItem.ToString() ?? string.Empty;
?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Log.Information($"Удален набор: {name}");
} }
} }
@ -107,33 +125,46 @@ public partial class FormLocomotivCollection : Form {
} }
_storage.AddSet(storageIndexInput.Text); _storage.AddSet(storageIndexInput.Text);
ReloadObjects(); ReloadObjects();
Log.Information($"Добавлен набор: {storageIndexInput.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("Не сохранилось", "Результат", {
MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { private void LoadToolStripMenuItem_Click(object sender, EventArgs e) {
if (loadFileDialog.ShowDialog() == DialogResult.OK) { if (loadFileDialog.ShowDialog() == DialogResult.OK) {
if (_storage.LoadData(loadFileDialog.FileName)) { try
{
_storage.LoadData(loadFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys) { Log.Information($"Файл {loadFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
storageListBox.Items.Add(collection); storageListBox.Items.Add(collection);
} }
ReloadObjects();
} }
else { catch (Exception ex)
MessageBox.Show("Не загрузилось", "Результат", {
MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -28,10 +28,7 @@ public class LocosGenericCollection <T, U> where T : DrawingLocomotiv where U :
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;
} }
public U? GetU(int pos) public U? GetU(int pos)

View File

@ -65,7 +65,7 @@ public class LocosGenericStorage
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных длясохранения");
} }
string toWrite = $"LocoStorage{Environment.NewLine}{data}"; string toWrite = $"LocoStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, var strs = toWrite.Split(new char[] { '\n', '\r' },
@ -84,7 +84,7 @@ public class LocosGenericStorage
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -93,11 +93,11 @@ public class LocosGenericStorage
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("LocoStorage")) if (!strs[0].StartsWith("LocoStorage"))
{ {
return false; throw new Exception("Неверный формат данных");
} }
_electricLocoStorages.Clear(); _electricLocoStorages.Clear();
do do
@ -121,7 +121,7 @@ public class LocosGenericStorage
{ {
if (!(collection + monorail)) if (!(collection + monorail))
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }

View File

@ -1,4 +1,6 @@
namespace ElectricLocomotive; using ElectricLocomotive.Exceptions;
namespace ElectricLocomotive;
public class SetGeneric <T> where T : class public class SetGeneric <T> where T : class
{ {
@ -15,14 +17,17 @@ public class SetGeneric <T> where T : class
public bool Insert(T electricLocomotiv) public bool Insert(T electricLocomotiv)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
return false; throw new StorageOverflowException(_maxCount);
Insert(electricLocomotiv, 0); Insert(electricLocomotiv, 0);
return true; return true;
} }
public bool Insert(T electricLocomotiv, int position) public bool Insert(T electricLocomotiv, 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, electricLocomotiv); _places.Insert(position, electricLocomotiv);
return true; return true;
@ -31,7 +36,7 @@ public class SetGeneric <T> where T : class
public bool Remove(int position) public bool Remove(int position)
{ {
if (!(position >= 0 && position < Count)) if (!(position >= 0 && position < Count))
return false; throw new LocoNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -1,3 +1,5 @@
using Serilog;
namespace ElectricLocomotive namespace ElectricLocomotive
{ {
internal static class Program internal static class Program
@ -8,9 +10,13 @@ namespace ElectricLocomotive
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, Log.Logger = new LoggerConfiguration()
// see https://aka.ms/applicationconfiguration. .WriteTo.File("log.txt")
ApplicationConfiguration.Initialize(); .MinimumLevel.Debug()
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormLocomotivCollection()); Application.Run(new FormLocomotivCollection());
} }
} }