This commit is contained in:
Владимир Данилов 2023-12-25 01:51:05 +04:00
parent 78558cda35
commit 3795138c04
8 changed files with 182 additions and 32 deletions

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": "Project_DumpTruck"
}
}
}

View File

@ -9,8 +9,11 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project_DumpTruck.DrawningObjects;
using Project_DumpTruck.Exceptions;
using Project_DumpTruck.Generics;
using Project_DumpTruck.MovementStrategy;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace Project_DumpTruck
@ -21,12 +24,13 @@ namespace Project_DumpTruck
/// Набор объектов
/// </summary>
private readonly TrucksGenericStorage _storage;
private readonly ILogger _logger;
public FormTruckCollection()
public FormTruckCollection(ILogger<FormTruckCollection> logger)
{
InitializeComponent();
_storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
@ -69,14 +73,17 @@ namespace Project_DumpTruck
return;
}
if (obj + truck != -1)
try
{
_ = obj + truck;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Обьект добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
}
else
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Обьект не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
}
}
@ -105,16 +112,25 @@ namespace Project_DumpTruck
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Обьект удален из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Обьект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch(TruckNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Обьект не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
}
private void buttonRefreshCollection_Click(object sender, EventArgs e)
@ -138,10 +154,12 @@ namespace Project_DumpTruck
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Добавление набора неуспешно Не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
@ -164,14 +182,15 @@ namespace Project_DumpTruck
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Удаление набора неуспешно");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
}
@ -184,15 +203,17 @@ namespace Project_DumpTruck
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не удалось");
}
}
}
@ -206,14 +227,17 @@ namespace Project_DumpTruck
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не удалось загрузить данные", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не удалось загрузить данные: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не удалось");
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
namespace Project_DumpTruck
{
internal static class Program
@ -8,10 +14,30 @@ namespace Project_DumpTruck
[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 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);
});
}
}
}

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="AppSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -1,4 +1,5 @@
using System;
using Project_DumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
@ -55,9 +56,12 @@ namespace Project_DumpTruck.Generics
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return -1;
throw new StorageOverflowException("Невалидная операция");
}
// Вставка по позиции
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(position, truck);
return position;
}
@ -69,8 +73,12 @@ namespace Project_DumpTruck.Generics
public bool Remove(int position)
{
// TODO проверка позиции
if ((position < 0) || (position > Count)) return false;
if ((position < 0) || (position > Count)) throw new TruckNotFoundException("Невалидная операция");
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (_places[position] == null)
{
throw new TruckNotFoundException(position);
}
_places[position] = null;
return true;
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Project_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

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Project_DumpTruck.Exceptions
{
[Serializable]
internal class TruckNotFoundException:ApplicationException
{
public TruckNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public TruckNotFoundException() : base() { }
public TruckNotFoundException(string message) : base(message) { }
public TruckNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected TruckNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.DrawningObjects;
using Project_DumpTruck.Exceptions;
using Project_DumpTruck.MovementStrategy;
namespace Project_DumpTruck.Generics
@ -106,7 +107,7 @@ namespace Project_DumpTruck.Generics
}
if (data.Length == 0)
{
return false;
throw new ArgumentException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TruckStorage{Environment.NewLine}{data}");
@ -121,19 +122,18 @@ namespace Project_DumpTruck.Generics
{
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 ArgumentException("Нет данных для загрузки");
}
if (!str.StartsWith("TruckStorage"))
{
//если нет такой записи, то это не те данные
return false;
throw new InvalidDataException("Неверный формат данных");
}
_truckStorages.Clear();
while ((str = sr.ReadLine()) != null)
@ -152,7 +152,18 @@ namespace Project_DumpTruck.Generics
{
if (collection + truck == -1)
{
return false;
try
{
_ = collection + truck;
}
catch (TruckNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
}