diff --git a/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .cs b/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .cs
new file mode 100644
index 0000000..6b84022
--- /dev/null
+++ b/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .cs
@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectElectricLocomotive.Exceptions
+{
+ [Serializable]
+ internal class LocomotiveNotFoundException : ApplicationException
+ {
+ public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+ public LocomotiveNotFoundException() : base() { }
+ public LocomotiveNotFoundException (string message) : base(message) { }
+ public LocomotiveNotFoundException(string message, Exception innerException) : base(message, innerException) { }
+ protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/ElectricLocomotive/Exceptions/StorageOverflowException.cs b/ElectricLocomotive/Exceptions/StorageOverflowException.cs
new file mode 100644
index 0000000..73c104f
--- /dev/null
+++ b/ElectricLocomotive/Exceptions/StorageOverflowException.cs
@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectElectricLocomotive.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) { }
+ }
+}
diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs
index ddc84fb..adfc6fa 100644
--- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs
+++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs
@@ -133,7 +133,7 @@ namespace ProjectElectricLocomotive.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new Exception("Невалиданя операция, нет данных длясохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
@@ -151,7 +151,7 @@ namespace ProjectElectricLocomotive.Generics
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException($"Файл {filename} не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@@ -167,12 +167,12 @@ namespace ProjectElectricLocomotive.Generics
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
- return false;
+ throw new FileLoadException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("LocomotiveStorage"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new ArgumentException("Неверный формат данных");
}
_locomotiveStorage.Clear();
foreach (string data in strs)
@@ -197,7 +197,7 @@ namespace ProjectElectricLocomotive.Generics
{
if ((collection + locomotive) == 0)
{
- return false;
+ throw new InvalidOperationException("Ошибкадобавления в коллекцию");
}
}
}
diff --git a/ElectricLocomotive/Generics/SetGeneric.cs b/ElectricLocomotive/Generics/SetGeneric.cs
index 6ca43f5..6cb07b4 100644
--- a/ElectricLocomotive/Generics/SetGeneric.cs
+++ b/ElectricLocomotive/Generics/SetGeneric.cs
@@ -1,4 +1,5 @@
-using System;
+using ProjectElectricLocomotive.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -43,7 +44,7 @@ namespace ProjectElectricLocomotive.Generics
public bool Insert(T locomotive)
{
if (_places.Count >= _maxCount) {
- return false;
+ throw new StorageOverflowException(_maxCount);
}
_places.Insert(0, locomotive);
return true;
@@ -74,7 +75,10 @@ namespace ProjectElectricLocomotive.Generics
{
return false;
}
-
+ if (_places[position] == null)
+ {
+ throw new LocomotiveNotFoundException(position);
+ }
_places.RemoveAt(position);
return true;
diff --git a/ElectricLocomotive/LogicFormLocomotiveCollection.cs b/ElectricLocomotive/LogicFormLocomotiveCollection.cs
index 1acefcd..8285d0f 100644
--- a/ElectricLocomotive/LogicFormLocomotiveCollection.cs
+++ b/ElectricLocomotive/LogicFormLocomotiveCollection.cs
@@ -1,12 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
using ProjectElectricLocomotive.DrawningObjects;
+using ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive.Generics;
-using ProjectElectricLocomotive.MovementStrategy;
+using System.Xml.Linq;
namespace ProjectElectricLocomotive
{
@@ -21,15 +17,20 @@ namespace ProjectElectricLocomotive
///
private readonly LocomotivesGenericStorage _storage;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormLocomotiveCollection()
+ public FormLocomotiveCollection(ILogger logger)
{
InitializeComponent();
_storage = new LocomotivesGenericStorage(
pictureBoxCollection.Width,
pictureBoxCollection.Height
);
+ _logger = logger;
}
///
@@ -67,6 +68,7 @@ namespace ProjectElectricLocomotive
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+ _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
///
@@ -90,12 +92,14 @@ namespace ProjectElectricLocomotive
{
return;
}
- if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?",
+ string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
+ if (MessageBox.Show($"Удалить объект {name}?",
"Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
- _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
+ _storage.DelSet(name);
ReloadObjects();
+ _logger.LogInformation($"Удален набор: {name}");
}
}
@@ -122,15 +126,22 @@ namespace ProjectElectricLocomotive
return;
}
SelectedLocomotive.SetPictureSize(pictureBoxCollection.Size);
- if (obj + SelectedLocomotive > 0)
+ try
{
- MessageBox.Show("Объект добавлен");
+ if (obj + SelectedLocomotive > 0)
+ {
+ MessageBox.Show("Объект добавлен");
- pictureBoxCollection.Image = obj.ShowLocomotives();
+ pictureBoxCollection.Image = obj.ShowLocomotives();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ }
}
- else
+ catch (StorageOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show(ex.Message);
}
}
@@ -165,14 +176,21 @@ namespace ProjectElectricLocomotive
{
pos = 0;
}
- if (obj - pos != -1)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBoxCollection.Image = obj.ShowLocomotives();
+ if (obj - pos != -1)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBoxCollection.Image = obj.ShowLocomotives();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (LocomotiveNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
}
}
///
@@ -205,15 +223,16 @@ namespace ProjectElectricLocomotive
saveFileDialog.Title = "Сохранение";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
+ try
{
+ _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
- else
- {
- MessageBox.Show("Не сохранилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ catch (Exception ex)
+ {
+ MessageBox.Show($"Не сохранилось: {ex.Message}",
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -225,16 +244,17 @@ namespace ProjectElectricLocomotive
openFileDialog.Title = "Загрузка";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
+ _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
ReloadObjects();
}
- else
+ catch(Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не загрузилось: {ex.Message}",
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
diff --git a/ElectricLocomotive/Program.cs b/ElectricLocomotive/Program.cs
index 5def1ba..daae88b 100644
--- a/ElectricLocomotive/Program.cs
+++ b/ElectricLocomotive/Program.cs
@@ -1,3 +1,7 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+
namespace ProjectElectricLocomotive
{
internal static class Program
@@ -11,7 +15,20 @@ namespace ProjectElectricLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormLocomotiveCollection());
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ using (ServiceProvider serviceProvider = services.BuildServiceProvider())
+ {
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ }
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton().AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddNLog("nlog.config");
+ });
}
}
}
\ No newline at end of file
diff --git a/ElectricLocomotive/ProjectElectricLocomotive.csproj b/ElectricLocomotive/ProjectElectricLocomotive.csproj
index 13ee123..eb2b961 100644
--- a/ElectricLocomotive/ProjectElectricLocomotive.csproj
+++ b/ElectricLocomotive/ProjectElectricLocomotive.csproj
@@ -8,6 +8,11 @@
enable
+
+
+
+
+
True
diff --git a/ElectricLocomotive/nlog.config b/ElectricLocomotive/nlog.config
new file mode 100644
index 0000000..54e4ba6
--- /dev/null
+++ b/ElectricLocomotive/nlog.config
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file