diff --git a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj
index 13ee123..fe30e6a 100644
--- a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj
+++ b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj
@@ -8,6 +8,23 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
True
diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
index f0ac0b1..2ae9e30 100644
--- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
+++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs
@@ -1,14 +1,8 @@
using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.Generics;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
+using ProjectElectricLocomotive;
+using ProjectElectricLocomotive.Exceptions;
namespace ElectricLocomotive
{
@@ -16,10 +10,15 @@ namespace ElectricLocomotive
{
private readonly LocomotiveGenericStorage _storage;
- public FormLocomotiveCollection()
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ public FormLocomotiveCollection(ILogger logger)
{
InitializeComponent();
_storage = new LocomotiveGenericStorage(CollectionPictureBox.Width, CollectionPictureBox.Height);
+ _logger = logger;
}
///
@@ -49,10 +48,13 @@ namespace ElectricLocomotive
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+
+ _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
@@ -66,12 +68,15 @@ namespace ElectricLocomotive
{
return;
}
+ string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
- _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty);
+ _storage.DelSet(name);
ReloadObjects();
+ _logger.LogInformation($"Набор '{name}' удален");
}
+ _logger.LogWarning("Отмена удаления набора");
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
@@ -92,17 +97,27 @@ namespace ElectricLocomotive
{
return;
}
-
+ try
+ {
+ if (obj + loco > -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ CollectionPictureBox.Image = obj.ShowLocomotives();
+ _logger.LogInformation($"Добавлен объект {obj}");
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ _logger.LogInformation("Не удалось добавить объект");
+ }
+ }
+ catch (StorageOverflowException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogInformation("Не удалось добавить объект");
+ }
//проверяем, удалось ли нам загрузить объект
- if (obj + loco > -1)
- {
- MessageBox.Show("Объект добавлен");
- CollectionPictureBox.Image = obj.ShowLocomotives();
- }
- else
- {
- MessageBox.Show("Не удалось добавить объект");
- }
+
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
@@ -116,17 +131,28 @@ namespace ElectricLocomotive
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
+ _logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(Input.Text);
- if (obj - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- CollectionPictureBox.Image = obj.ShowLocomotives();
+ if ( obj - pos != null )
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Удален объект с позиции{pos}");
+ CollectionPictureBox.Image = obj.ShowLocomotives();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning($"Не найден объект по позиции: {pos}");
+ }
}
- else
+ catch (LocoNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"Не найден объект по позиции: {pos}");
}
}
@@ -150,15 +176,15 @@ namespace ElectricLocomotive
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
+ try
{
- MessageBox.Show("Сохранение прошло успешно!",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _storage.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Ошибка сохранения!", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
@@ -169,17 +195,19 @@ namespace ElectricLocomotive
///
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
+ // TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка завершена!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _storage.LoadData(openFileDialog.FileName);
+ _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Ошибка загрузки!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
-
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs
index 33c1044..87d18ad 100644
--- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs
+++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs
@@ -30,7 +30,6 @@ namespace ElectricLocomotive
panelColorBlue.MouseDown += PanelColor_MouseDown;
buttonCancelObject.Click += (s, e) => Close();
-
}
public void AddEvent(Action ev)
{
diff --git a/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs b/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs
new file mode 100644
index 0000000..b2a0ec9
--- /dev/null
+++ b/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs
@@ -0,0 +1,21 @@
+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 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) { }
+
+ }
+}
diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
index 8838fb6..6045226 100644
--- a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
+++ b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs
@@ -97,7 +97,7 @@ namespace ElectricLocomotive.Generics
///
/// Путь и имя файла
/// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -115,53 +115,47 @@ namespace ElectricLocomotive.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new Exception("Нет данных для записи, ошибка");
}
using StreamWriter fs = new StreamWriter(filename);
{
fs.WriteLine($"LocomotiveStorage{Environment.NewLine}");
fs.WriteLine(data);
}
- return true;
+ return;
}
///
/// Загрузка информации по автомобилям в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
{
-
string str = fs.ReadLine();
-
if (str == null || str.Length == 0)
{
- return false;
+ throw new IOException("Нет данных для загрузки");
}
-
if (!str.StartsWith("LocomotiveStorage"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Неверный формат данных");
}
-
_locomotivesStorage.Clear();
string strs = "";
-
-
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
- return false;
+ throw new FileNotFoundException("Нет данных для загрузки");
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@@ -176,15 +170,15 @@ namespace ElectricLocomotive.Generics
DrawningLocomotive? loco = elem?.CreateDrawningLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
if (loco != null)
{
- if ((collection + loco) == -1)
+ if ((collection + loco) == -1) // for my realization it's -1, for eegov's realization it's boolean
{
- return false;
+ throw new Exception("Ошибка добавления ");
}
}
}
_locomotivesStorage.Add(record[0], collection);
}
- return true;
+ return;
}
}
}
diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
index 5b95146..41373ce 100644
--- a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
+++ b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs
@@ -27,13 +27,13 @@ namespace ElectricLocomotive.Generics
_pictureHeight = picHeight;
_collection = new SetGeneric(width * height);
}
- public static int operator +(LocomotivesGenericCollection collect, T? loco)
+ public static int operator +(LocomotivesGenericCollection collect, T? locomotive)
{
- if (loco == null)
+ if (locomotive == null)
{
return -1;
}
- return collect._collection.Insert(loco);
+ return collect._collection.Insert(locomotive);
}
diff --git a/ElectricLocomotive/ElectricLocomotive/Program.cs b/ElectricLocomotive/ElectricLocomotive/Program.cs
index ead2f34..6d62a0d 100644
--- a/ElectricLocomotive/ElectricLocomotive/Program.cs
+++ b/ElectricLocomotive/ElectricLocomotive/Program.cs
@@ -1,19 +1,41 @@
-using ProjectElectricLocomotive;
+using Serilog;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Configuration;
namespace ElectricLocomotive
{
internal static class Program
{
- ///
- /// The main entry point for the application.
- ///
[STAThread]
static void Main()
{
// 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 =>
+ {
+ string[] path = Directory.GetCurrentDirectory().Split('\\');
+ string pathNeed = "";
+ for (int i = 0; i < path.Length - 3; i++)
+ {
+ pathNeed += path[i] + "\\";
+ }
+ var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSettings.json", optional: false, reloadOnChange: true).Build();
+ var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(logger);
+ });
}
}
+
}
\ No newline at end of file
diff --git a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs
index 8c310ef..a308aca 100644
--- a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs
+++ b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs
@@ -1,4 +1,5 @@
-using System;
+using ProjectElectricLocomotive.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -24,7 +25,13 @@ namespace ProjectElectricLocomotive.Generics
public int Insert(T loco, int position)
{
- if (position < 0 || position >= _maxCount) return -1;
+
+
+ if (position < 0 || position >= _maxCount)
+ {
+ return -1;
+ }
+
_places.Insert(position, loco);
return position;
}
@@ -34,6 +41,8 @@ namespace ProjectElectricLocomotive.Generics
return null;
T? tmp = _places[position];
+ if (tmp == null)
+ throw new LocoNotFoundException(position);
_places[position] = null;
return tmp;
}
diff --git a/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs b/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs
new file mode 100644
index 0000000..98ccf57
--- /dev/null
+++ b/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectElectricLocomotive
+{
+ [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/ElectricLocomotive/appSettings.json b/ElectricLocomotive/ElectricLocomotive/appSettings.json
new file mode 100644
index 0000000..49318ec
--- /dev/null
+++ b/ElectricLocomotive/ElectricLocomotive/appSettings.json
@@ -0,0 +1,20 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "Logs/log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
+ "Properties": {
+ "Application": "Locomotives"
+ }
+ }
+}
\ No newline at end of file
diff --git a/ElectricLocomotive/ElectricLocomotive/nlog.config b/ElectricLocomotive/ElectricLocomotive/nlog.config
new file mode 100644
index 0000000..cca6f0f
--- /dev/null
+++ b/ElectricLocomotive/ElectricLocomotive/nlog.config
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+