99%
This commit is contained in:
parent
2c1605cadc
commit
ff1ca92984
@ -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
|
||||
|
@ -11,4 +11,9 @@
|
||||
<StartupObject></StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -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
|
||||
/// </summary>
|
||||
private readonly TrucksGenericStorage _storage;
|
||||
|
||||
public FormTruckCollection()
|
||||
private readonly Microsoft.Extensions.Logging.ILogger _logger;
|
||||
public FormTruckCollection(ILogger<FormTruckCollection> 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("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (TruckNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -171,14 +203,16 @@ namespace DumpTruck
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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<FormTruckCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormTruckCollection>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
@ -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) { }
|
||||
}
|
||||
}
|
21
DumpTruck/DumpTruck/StorageOverflowException.cs
Normal file
21
DumpTruck/DumpTruck/StorageOverflowException.cs
Normal file
@ -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) { }
|
||||
}
|
||||
}
|
@ -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
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
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;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
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<DrawningTruck, DrawningObjectTruck> 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;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
20
DumpTruck/appsettings.json
Normal file
20
DumpTruck/appsettings.json
Normal file
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
14
DumpTruck/nlog.config
Normal file
14
DumpTruck/nlog.config
Normal file
@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true" internalLogLevel="Info">
|
||||
<targets>
|
||||
<target xsi:type="File" name="tofile" fileName="carlog-
|
||||
${shortdate}.log" />
|
||||
</targets>
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
Loading…
Reference in New Issue
Block a user