diff --git a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs
index 870cd4f..933cd2a 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/FormMapWithSetLocomotives.cs
@@ -1,4 +1,5 @@
-using System;
+using Microsoft.Extensions.Logging;
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -27,11 +28,16 @@ namespace WarmlyLocomotive
///
private readonly MapsCollection _mapsCollection;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormMapWithSetLocomotives()
+ public FormMapWithSetLocomotives(ILogger logger)
{
InitializeComponent();
+ _logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -77,14 +83,29 @@ namespace WarmlyLocomotive
return;
}
DrawningObjectLocomotive locomotive = new(drawningLocomotive);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1)
+ try
{
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1)
+ {
+ _logger.LogInformation($"Добавление объекта {locomotive}");
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogInformation("Не удалось добавить объект");
+ MessageBox.Show("Не удалось добавить объект");
+ }
}
- else
+ catch (StorageOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
+ MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
///
@@ -107,14 +128,30 @@ namespace WarmlyLocomotive
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ var deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
+ if (deletedLocomotive != null)
+ {
+ _logger.LogInformation($"Объект {deletedLocomotive} удалён");
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogInformation($"Не удалось удалить объект по позиции {pos}");
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (LocomotiveNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning($"Ошибка удаления: {ex.Message}");
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
///
@@ -183,21 +220,25 @@ namespace WarmlyLocomotive
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
+ _logger.LogInformation("Не все данные заполнены при попытке создании карты");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
+ _logger.LogInformation($"Нет карты с названием {comboBoxSelectorMap.Text}");
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{
+ _logger.LogInformation("Присутствуют символы, недопустимые для имени карты");
MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
+ _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
///
/// Выбор карты
@@ -207,6 +248,7 @@ namespace WarmlyLocomotive
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ _logger.LogInformation($"Текущая карта сменена на {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
///
/// Удаление карты
@@ -224,6 +266,7 @@ namespace WarmlyLocomotive
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
+ _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
}
///
@@ -235,13 +278,16 @@ namespace WarmlyLocomotive
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _mapsCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation($"Успешное сохранение по пути {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось сохранить данные. Ошибка - {ex.Message}");
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -254,14 +300,17 @@ namespace WarmlyLocomotive
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
+ _logger.LogInformation($"Успешная загрузка по пути {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось загрузить данные. Ошибка - {ex.Message}");
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs b/WarmlyLocomotive/WarmlyLocomotive/LocomotiveNotFoundException.cs
new file mode 100644
index 0000000..20e2daa
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/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 WarmlyLocomotive
+{
+ [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 exception) : base(message, exception) { }
+ protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs
index 54991f0..7ca3dbb 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/MapsCollection.cs
@@ -94,7 +94,7 @@ namespace WarmlyLocomotive
///
/// Путь и имя файла
///
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -108,18 +108,17 @@ namespace WarmlyLocomotive
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
- return true;
}
///
/// Загрузка информации по локомотивам в депо из файла
///
///
///
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -127,7 +126,7 @@ namespace WarmlyLocomotive
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -150,7 +149,6 @@ namespace WarmlyLocomotive
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
- return true;
}
}
}
diff --git a/WarmlyLocomotive/WarmlyLocomotive/Program.cs b/WarmlyLocomotive/WarmlyLocomotive/Program.cs
index 5334215..5b23774 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/Program.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+using Serilog;
namespace WarmlyLocomotive
{
internal static class Program
@@ -11,7 +16,25 @@ namespace WarmlyLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormMapWithSetLocomotives());
+ 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 =>
+ {
+ var serilogLogger = new LoggerConfiguration()
+ .WriteTo.File("LogOfProgram.txt")
+ .CreateLogger();
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(serilogLogger, true);
+ });
}
}
}
\ No newline at end of file
diff --git a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs
index 28765de..b579117 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs
+++ b/WarmlyLocomotive/WarmlyLocomotive/SetLocomotivesGeneric.cs
@@ -46,7 +46,7 @@ namespace WarmlyLocomotive
{
if (position < 0 || position > Count || _maxCount == Count)
{
- return -1;
+ throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, locomotive);
return position;
@@ -60,7 +60,7 @@ namespace WarmlyLocomotive
{
if (position < 0 || position >= Count)
{
- return null;
+ throw new LocomotiveNotFoundException(position);
}
T memoryObj = _places[position];
_places.RemoveAt(position);
diff --git a/WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs b/WarmlyLocomotive/WarmlyLocomotive/StorageOverflowException.cs
new file mode 100644
index 0000000..444fefd
--- /dev/null
+++ b/WarmlyLocomotive/WarmlyLocomotive/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 WarmlyLocomotive
+{
+ [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/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj
index 13ee123..af6aa60 100644
--- a/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj
+++ b/WarmlyLocomotive/WarmlyLocomotive/WarmlyLocomotive.csproj
@@ -8,6 +8,15 @@
enable
+
+
+
+
+
+
+
+
+
True