Compare commits

...

3 Commits

Author SHA1 Message Date
4fdfba0b2e 100% log 2024-02-09 13:06:47 +04:00
a710ce8ccb 100% 2024-02-09 12:21:21 +04:00
ff1ca92984 99% 2024-02-09 01:31:19 +04:00
14 changed files with 223 additions and 71 deletions

2
7laba.txt Normal file
View File

@ -0,0 +1,2 @@
TruckStorage
111|100:100:Lime:Blue:True;100:100:Lime;100:100:Lime;100:100:Brown;100:100:Yellow:Lime:True;100:100:Red:Black:False;100:100:ActiveCaptionText:ButtonHighlight:True;100:100:Blue:Black:False;100:100:Blue;100:100:Lime;100:100:OrangeRed;100:100:White:Red:True;100:100:Lime;100:100:White:Black:False;100:100:White:Red:True;100:100:Blue:Black:False;100:100:ActiveCaptionText;100:100:White:Lime:True;100:100:Red;100:100:Blue:Red:True;

2
7laba5.txt Normal file
View File

@ -0,0 +1,2 @@
TruckStorage
111|

View File

@ -3,7 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157 VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 10.0.40219.1 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 EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -11,4 +11,25 @@
<StartupObject></StartupObject> <StartupObject></StartupObject>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -11,7 +11,10 @@ using System.Xml;
using DumpTruck.DrawningObjects; using DumpTruck.DrawningObjects;
using DumpTruck.Generics; using DumpTruck.Generics;
using DumpTruck.MovementStrategy; using DumpTruck.MovementStrategy;
using Microsoft.Win32; using DumpTruck.Exceptions;
using Microsoft.Extensions.Logging;
using System.Windows;
using NLog;
namespace DumpTruck namespace DumpTruck
@ -23,10 +26,12 @@ namespace DumpTruck
/// </summary> /// </summary>
private readonly TrucksGenericStorage _storage; private readonly TrucksGenericStorage _storage;
public FormTruckCollection() private readonly Microsoft.Extensions.Logging.ILogger _logger;
public FormTruckCollection(ILogger<FormTruckCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
@ -55,15 +60,17 @@ namespace DumpTruck
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Не удалось удалить объект: не выбран набор");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty]; string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Не удалось удалить объект: набор пуст");
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (System.Windows.Forms.MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
@ -71,17 +78,26 @@ namespace DumpTruck
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos) try
{ {
MessageBox.Show("Объект удален"); if (obj - pos)
pictureBoxCollection.Image = obj.ShowTrucks(); {
System.Windows.Forms.MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Удален объект на позиции: {pos}");
}
else
{
System.Windows.Forms.MessageBox.Show("Не удалось удалить объект");
}
} }
catch (TruckNotFoundException ex)
else
{ {
MessageBox.Show("Не удалось удалить объект"); System.Windows.Forms.MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
} }
}
}
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
{ {
@ -102,13 +118,15 @@ namespace DumpTruck
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", System.Windows.Forms.MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void AddTruck(DrawningTruck truck) private void AddTruck(DrawningTruck truck)
{ {
truck._pictureWidth = pictureBoxCollection.Width; truck._pictureWidth = pictureBoxCollection.Width;
@ -120,22 +138,33 @@ namespace DumpTruck
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
return; return;
} }
if (obj + truck != -1) try
{ {
MessageBox.Show("Объект добавлен"); if (obj + truck != -1)
pictureBoxCollection.Image = obj.ShowTrucks(); {
System.Windows.Forms.MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Объект добавлен {truck}");
}
else
{
System.Windows.Forms.MessageBox.Show("Не удалось добавить объект");
}
} }
else catch (ApplicationException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); System.Windows.Forms.MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
} }
private void buttonAddTruck_Click(object sender, EventArgs e) private void buttonAddTruck_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Не удалось добавить объект: не выбран набор");
return; return;
} }
var formTruckConfig = new FormTruckConfig(); var formTruckConfig = new FormTruckConfig();
@ -154,12 +183,13 @@ namespace DumpTruck
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
MessageBoxIcon.Question) == DialogResult.Yes) if (System.Windows.Forms.MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(name);
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
/// <summary> /// <summary>
@ -171,14 +201,16 @@ namespace DumpTruck
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); System.Windows.Forms.MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение прошло успешно: {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", System.Windows.Forms.MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -192,16 +224,19 @@ namespace DumpTruck
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storage.LoadData(openFileDialog.FileName);
System.Windows.Forms.MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information); "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", System.Windows.Forms.MessageBox.Show($"Не загрузилось {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
} }
} }
} }

View File

@ -1,4 +1,7 @@
using DumpTruck; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace DumpTruck namespace DumpTruck
{ {
@ -11,9 +14,25 @@ namespace DumpTruck
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); 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 =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Numerics; using System.Numerics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using DumpTruck.Exceptions;
namespace DumpTruck.Generics namespace DumpTruck.Generics
{ {
@ -53,10 +54,10 @@ namespace DumpTruck.Generics
public int Insert(T truck, int position) public int Insert(T truck, int position)
{ {
// Проверка позиции // Проверка позиции
if (position < 0 || position >= _maxCount) if (position < 0 || position > Count)
{ throw new TruckNotFoundException(position);
return -1; if (Count >= _maxCount)
} throw new StorageOverflowException(_maxCount);
// Вставка по позиции // Вставка по позиции
_places.Insert(position, truck); _places.Insert(position, truck);
return position; return position;
@ -69,7 +70,7 @@ namespace DumpTruck.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if ((position < 0) || (position > Count)) return false; if ((position < 0) || (position > Count)) throw new TruckNotFoundException(position);
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
_places[position] = null; _places[position] = null;
return true; return true;

View File

@ -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) { }
}
}

View 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) { }
}
}

View File

@ -5,6 +5,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using DumpTruck.DrawningObjects; using DumpTruck.DrawningObjects;
using DumpTruck.Exceptions;
using DumpTruck.Generics; using DumpTruck.Generics;
using DumpTruck.MovementStrategy; using DumpTruck.MovementStrategy;
@ -91,7 +92,7 @@ namespace DumpTruck.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -109,33 +110,32 @@ namespace DumpTruck.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using StreamWriter sw = new(filename); using StreamWriter sw = new(filename);
sw.Write($"TruckStorage{Environment.NewLine}{data}"); sw.Write($"TruckStorage{Environment.NewLine}{data}");
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
string str = sr.ReadLine(); string str = sr.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new NullReferenceException("Нет данных для загрузки");
} }
if (!str.StartsWith("TruckStorage")) if (!str.StartsWith("TruckStorage"))
{ {
return false; throw new InvalidDataException("Неверный формат данных");
} }
_truckStorages.Clear(); _truckStorages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
@ -147,22 +147,20 @@ namespace DumpTruck.Generics
} }
TrucksGenericCollection<DrawningTruck, DrawningObjectTruck> collection = new(_pictureWidth, _pictureHeight); TrucksGenericCollection<DrawningTruck, DrawningObjectTruck> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); 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); DrawningTruck? truck = elem?.CreateDrawningTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null) if (truck != null)
{ {
if (collection + truck == -1) if (collection + truck == -1)
{ {
return false; throw new ApplicationException("Ошибка добавления в коллекцию");
} }
} }
} }
_truckStorages.Add(record[0], collection); _truckStorages.Add(record[0], collection);
} }
} }
return true;
} }
} }
} }

View 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": "ArmoredTransport"
}
}
}

View 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="log-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View 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
View 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>