Compare commits

..

No commits in common. "4fdfba0b2e4febac5e24c63aa39dacdd38eeec68" and "2c1605cadc22fb8d4cb9f0b9fd44839dcc9c4385" have entirely different histories.

14 changed files with 72 additions and 224 deletions

View File

@ -1,2 +0,0 @@
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;

View File

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

View File

@ -3,13 +3,7 @@ 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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DumpTruck", "DumpTruck\DumpTruck.csproj", "{DCAA55AD-0C09-4CF9-B6B6-4CC43082AC55}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "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,25 +11,4 @@
<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,10 +11,7 @@ using System.Xml;
using DumpTruck.DrawningObjects; using DumpTruck.DrawningObjects;
using DumpTruck.Generics; using DumpTruck.Generics;
using DumpTruck.MovementStrategy; using DumpTruck.MovementStrategy;
using DumpTruck.Exceptions; using Microsoft.Win32;
using Microsoft.Extensions.Logging;
using System.Windows;
using NLog;
namespace DumpTruck namespace DumpTruck
@ -26,12 +23,10 @@ namespace DumpTruck
/// </summary> /// </summary>
private readonly TrucksGenericStorage _storage; private readonly TrucksGenericStorage _storage;
private readonly Microsoft.Extensions.Logging.ILogger _logger; public FormTruckCollection()
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()
@ -60,17 +55,15 @@ 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 (System.Windows.Forms.MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
@ -78,26 +71,17 @@ namespace DumpTruck
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try if (obj - pos)
{ {
if (obj - pos) MessageBox.Show("Объект удален");
{ 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
{ {
System.Windows.Forms.MessageBox.Show(ex.Message); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
} }
}
}
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
{ {
@ -118,15 +102,13 @@ namespace DumpTruck
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
System.Windows.Forms.MessageBox.Show("Не все данные заполнены", "Ошибка", 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;
@ -138,33 +120,22 @@ 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;
} }
try if (obj + truck != -1)
{ {
if (obj + truck != -1) MessageBox.Show("Объект добавлен");
{ pictureBoxCollection.Image = obj.ShowTrucks();
System.Windows.Forms.MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Объект добавлен {truck}");
}
else
{
System.Windows.Forms.MessageBox.Show("Не удалось добавить объект");
}
} }
catch (ApplicationException ex) else
{ {
System.Windows.Forms.MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект");
_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();
@ -183,13 +154,12 @@ namespace DumpTruck
{ {
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
if (System.Windows.Forms.MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxIcon.Question) == DialogResult.Yes)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(name); _storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
/// <summary> /// <summary>
@ -201,16 +171,14 @@ namespace DumpTruck
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storage.SaveData(saveFileDialog.FileName))
{
_storage.SaveData(saveFileDialog.FileName);
System.Windows.Forms.MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение прошло успешно: {saveFileDialog.FileName}");
}
catch (Exception ex)
{ {
System.Windows.Forms.MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -224,19 +192,16 @@ namespace DumpTruck
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_storage.LoadData(openFileDialog.FileName))
{ {
_storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно",
System.Windows.Forms.MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information); "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
} }
catch (Exception ex) else
{ {
System.Windows.Forms.MessageBox.Show($"Не загрузилось {ex.Message}", "Результат", MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
} }
} }
} }

View File

@ -1,7 +1,4 @@
using Microsoft.Extensions.Configuration; using DumpTruck;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace DumpTruck namespace DumpTruck
{ {
@ -14,25 +11,9 @@ 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();
var services = new ServiceCollection(); Application.Run(new FormTruckCollection());
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,7 +4,6 @@ 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
{ {
@ -54,10 +53,10 @@ namespace DumpTruck.Generics
public int Insert(T truck, int position) public int Insert(T truck, int position)
{ {
// Проверка позиции // Проверка позиции
if (position < 0 || position > Count) if (position < 0 || position >= _maxCount)
throw new TruckNotFoundException(position); {
if (Count >= _maxCount) return -1;
throw new StorageOverflowException(_maxCount); }
// Вставка по позиции // Вставка по позиции
_places.Insert(position, truck); _places.Insert(position, truck);
return position; return position;
@ -70,7 +69,7 @@ namespace DumpTruck.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if ((position < 0) || (position > Count)) throw new TruckNotFoundException(position); if ((position < 0) || (position > Count)) return false;
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
_places[position] = null; _places[position] = null;
return true; return true;

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

@ -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 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,7 +5,6 @@ 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;
@ -92,7 +91,7 @@ namespace DumpTruck.Generics
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename) public bool SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -110,32 +109,33 @@ namespace DumpTruck.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения"); return false;
} }
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 void LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не найден"); return false;
} }
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)
{ {
throw new NullReferenceException("Нет данных для загрузки"); return false;
} }
if (!str.StartsWith("TruckStorage")) if (!str.StartsWith("TruckStorage"))
{ {
throw new InvalidDataException("Неверный формат данных"); return false;
} }
_truckStorages.Clear(); _truckStorages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
@ -147,20 +147,22 @@ 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.Reverse()) foreach (string elem in set)
{ {
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)
{ {
throw new ApplicationException("Ошибка добавления в коллекцию"); return false;
} }
} }
} }
_truckStorages.Add(record[0], collection); _truckStorages.Add(record[0], collection);
} }
} }
return true;
} }
} }
} }

View File

@ -1,20 +0,0 @@
{
"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

@ -1,14 +0,0 @@
<?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

@ -1,20 +0,0 @@
{
"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"
}
}
}

View File

@ -1,14 +0,0 @@
<?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>