diff --git a/DumpTruck/DumpTruck.sln b/DumpTruck/DumpTruck.sln
index ed21e37..3c110a2 100644
--- a/DumpTruck/DumpTruck.sln
+++ b/DumpTruck/DumpTruck.sln
@@ -3,7 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DumpTruck", "DumpTruck\DumpTruck.csproj", "{DCAA55AD-0C09-4CF9-B6B6-4CC43082AC55}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DumpTruck", "DumpTruck\DumpTruck.csproj", "{DCAA55AD-0C09-4CF9-B6B6-4CC43082AC55}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Элементы решения", "Элементы решения", "{846638BC-8C15-4072-9D60-8404116C8EEE}"
+ ProjectSection(SolutionItems) = preProject
+ appsettings.json = appsettings.json
+ nlog.config = nlog.config
+ EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/DumpTruck/DumpTruck/DumpTruck.csproj b/DumpTruck/DumpTruck/DumpTruck.csproj
index efe6e12..5b2b895 100644
--- a/DumpTruck/DumpTruck/DumpTruck.csproj
+++ b/DumpTruck/DumpTruck/DumpTruck.csproj
@@ -11,4 +11,9 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/DumpTruck/DumpTruck/FormTruckCollection.cs b/DumpTruck/DumpTruck/FormTruckCollection.cs
index 487a7e7..87ac3ba 100644
--- a/DumpTruck/DumpTruck/FormTruckCollection.cs
+++ b/DumpTruck/DumpTruck/FormTruckCollection.cs
@@ -12,6 +12,11 @@ using DumpTruck.DrawningObjects;
using DumpTruck.Generics;
using DumpTruck.MovementStrategy;
using Microsoft.Win32;
+using DumpTruck.Exceptions;
+using Microsoft.Extensions.Logging;
+using System.Xml.Linq;
+using System.Windows;
+using NLog;
namespace DumpTruck
@@ -23,10 +28,12 @@ namespace DumpTruck
///
private readonly TrucksGenericStorage _storage;
- public FormTruckCollection()
+ private readonly Microsoft.Extensions.Logging.ILogger _logger;
+ public FormTruckCollection(ILogger logger)
{
InitializeComponent();
_storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
+ _logger = logger;
}
private void ReloadObjects()
@@ -55,12 +62,14 @@ namespace DumpTruck
if (listBoxStorages.SelectedIndex == -1)
{
+ _logger.LogWarning($"Не удалось удалить объект: не выбран набор");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
+ _logger.LogWarning($"Не удалось удалить объект: набор пуст");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
@@ -71,17 +80,26 @@ namespace DumpTruck
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
- if (obj - pos)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBoxCollection.Image = obj.ShowTrucks();
+ if (obj - pos)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBoxCollection.Image = obj.ShowTrucks();
+ _logger.LogInformation($"Удален объект на позиции: {pos}");
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
-
- else
+ catch (TruckNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
}
- }
+
+ }
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
@@ -108,7 +126,9 @@ namespace DumpTruck
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+ _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
+
private void AddTruck(DrawningTruck truck)
{
truck._pictureWidth = pictureBoxCollection.Width;
@@ -120,22 +140,33 @@ namespace DumpTruck
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
+ _logger.LogWarning($"Не удалось добавить объект: набор пуст");
return;
}
- if (obj + truck != -1)
+ try
{
- MessageBox.Show("Объект добавлен");
- pictureBoxCollection.Image = obj.ShowTrucks();
+ if (obj + truck != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBoxCollection.Image = obj.ShowTrucks();
+ _logger.LogInformation($"Объект добавлен {truck}");
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ }
}
- else
+ catch (ApplicationException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
private void buttonAddTruck_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
+ _logger.LogWarning($"Не удалось добавить объект: не выбран набор");
return;
}
var formTruckConfig = new FormTruckConfig();
@@ -154,12 +185,13 @@ namespace DumpTruck
{
return;
}
- if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
- MessageBoxIcon.Question) == DialogResult.Yes)
+ 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}");
}
}
///
@@ -171,14 +203,16 @@ namespace DumpTruck
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
- {
- MessageBox.Show("Сохранение прошло успешно",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ try
+ {
+ _storage.SaveData(saveFileDialog.FileName);
+ MessageBox.Show("Сохранение прошло успешно",
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation($"Сохранение прошло успешно: {saveFileDialog.FileName}");
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат",
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@@ -192,16 +226,19 @@ namespace DumpTruck
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
+ _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
+ _logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат",
+ MessageBox.Show($"Не загрузилось {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
}
diff --git a/DumpTruck/DumpTruck/Program.cs b/DumpTruck/DumpTruck/Program.cs
index 6b3ec3d..6401b75 100644
--- a/DumpTruck/DumpTruck/Program.cs
+++ b/DumpTruck/DumpTruck/Program.cs
@@ -1,4 +1,8 @@
-using DumpTruck;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using System.IO;
namespace DumpTruck
{
@@ -13,7 +17,28 @@ namespace DumpTruck
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormTruckCollection());
+ 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/DumpTruck/DumpTruck/SetGeneric.cs b/DumpTruck/DumpTruck/SetGeneric.cs
index 6acc2b3..b21dba9 100644
--- a/DumpTruck/DumpTruck/SetGeneric.cs
+++ b/DumpTruck/DumpTruck/SetGeneric.cs
@@ -4,6 +4,7 @@ using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
+using DumpTruck.Exceptions;
namespace DumpTruck.Generics
{
@@ -53,10 +54,10 @@ namespace DumpTruck.Generics
public int Insert(T truck, int position)
{
// Проверка позиции
- if (position < 0 || position >= _maxCount)
- {
- return -1;
- }
+ if (position < 0 || position > Count)
+ throw new TruckNotFoundException(position);
+ if (Count >= _maxCount)
+ throw new StorageOverflowException(_maxCount);
// Вставка по позиции
_places.Insert(position, truck);
return position;
@@ -69,7 +70,7 @@ namespace DumpTruck.Generics
public bool Remove(int position)
{
// TODO проверка позиции
- if ((position < 0) || (position > Count)) return false;
+ if ((position < 0) || (position > Count)) throw new TruckNotFoundException(position);
// TODO удаление объекта из массива, присвоив элементу массива значение null
_places[position] = null;
return true;
diff --git a/DumpTruck/DumpTruck/StorageOverException.cs b/DumpTruck/DumpTruck/StorageOverException.cs
deleted file mode 100644
index 5cc4829..0000000
--- a/DumpTruck/DumpTruck/StorageOverException.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.Serialization;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DumpTruck.Exceptions
-{
- [Serializable]
- internal class StorageOverException : ApplicationException
- {
- public StorageOverException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
- public StorageOverException() : base() { }
- public StorageOverException(string message) : base(message) { }
- public StorageOverException(string message, Exception exception)
- : base(message, exception) { }
- protected StorageOverException(SerializationInfo info,
- StreamingContext contex) : base(info, contex) { }
- }
-}
diff --git a/DumpTruck/DumpTruck/StorageOverflowException.cs b/DumpTruck/DumpTruck/StorageOverflowException.cs
new file mode 100644
index 0000000..dd9bc69
--- /dev/null
+++ b/DumpTruck/DumpTruck/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 DumpTruck.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/DumpTruck/DumpTruck/TruckGenericStorage.cs b/DumpTruck/DumpTruck/TruckGenericStorage.cs
index 372b911..f8ba81f 100644
--- a/DumpTruck/DumpTruck/TruckGenericStorage.cs
+++ b/DumpTruck/DumpTruck/TruckGenericStorage.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.DrawningObjects;
+using DumpTruck.Exceptions;
using DumpTruck.Generics;
using DumpTruck.MovementStrategy;
@@ -91,7 +92,7 @@ namespace DumpTruck.Generics
///
/// Путь и имя файла
/// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -109,33 +110,32 @@ namespace DumpTruck.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TruckStorage{Environment.NewLine}{data}");
- return true;
}
///
/// Загрузка информации по автомобилям в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
- return false;
+ throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("TruckStorage"))
{
- return false;
+ throw new InvalidDataException("Неверный формат данных");
}
_truckStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -147,22 +147,20 @@ namespace DumpTruck.Generics
}
TrucksGenericCollection collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
- foreach (string elem in set)
+ foreach (string elem in set.Reverse())
{
DrawningTruck? truck = elem?.CreateDrawningTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null)
{
if (collection + truck == -1)
{
- return false;
+ throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}
_truckStorages.Add(record[0], collection);
}
}
- return true;
-
}
}
}
\ No newline at end of file
diff --git a/DumpTruck/appsettings.json b/DumpTruck/appsettings.json
new file mode 100644
index 0000000..bce76f7
--- /dev/null
+++ b/DumpTruck/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": "DumpTruck"
+ }
+ }
+}
\ No newline at end of file
diff --git a/DumpTruck/nlog.config b/DumpTruck/nlog.config
new file mode 100644
index 0000000..6b24832
--- /dev/null
+++ b/DumpTruck/nlog.config
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file