Сделана окончательно i guess...

This commit is contained in:
Никита Волков 2023-12-25 03:42:31 +04:00
parent d6ef87c351
commit 6cf49037d6
9 changed files with 181 additions and 46 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": "Bulldozers"
}
}
}

View File

@ -8,7 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" 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.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
<AutoGen>True</AutoGen> <AutoGen>True</AutoGen>
@ -23,4 +36,6 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
</Project> </Project>

View File

@ -0,0 +1,16 @@

using System.Runtime.Serialization;
namespace Bulldozer.Exceptions
{
internal class BulldozerNotFoundException : ApplicationException
{
public BulldozerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BulldozerNotFoundException() : base() { }
public BulldozerNotFoundException(string message) : base(message) { }
public BulldozerNotFoundException(string message, Exception exception) : base(message, exception)
{ }
protected BulldozerNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

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

@ -1,8 +1,11 @@
using Bulldozer.DrawingObjects; using Bulldozer.DrawingObjects;
using Bulldozer.Generics; using Bulldozer.Generics;
using Bulldozer.MovementStrategy; using Bulldozer.MovementStrategy;
using System.Numerics;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using Bulldozer.Exceptions;
using Microsoft.Extensions.Logging;
namespace Bulldozer namespace Bulldozer
{ {
@ -12,13 +15,12 @@ namespace Bulldozer
/// Набор объектов /// Набор объектов
/// </summary> /// </summary>
private readonly BulldozersGenericStorage _storage; private readonly BulldozersGenericStorage _storage;
private readonly ILogger _logger;
public FormBulldozerCollection(ILogger<FormBulldozerCollection> logger)
public FormBulldozerCollection()
{ {
InitializeComponent(); InitializeComponent();
_storage = new BulldozersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BulldozersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
@ -52,10 +54,12 @@ namespace Bulldozer
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
@ -83,6 +87,7 @@ namespace Bulldozer
{ {
_storage.DelSet(listBoxBulldozerStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(listBoxBulldozerStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {Name}");
} }
} }
@ -116,14 +121,15 @@ namespace Bulldozer
{ {
return; return;
} }
if (obj + bulldozer > -1) try
{ {
_ = obj + bulldozer;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBulldozers(); pictureBoxCollection.Image = obj.ShowBulldozers();
} } catch(Exception ex) {
else MessageBox.Show(ex.Message);
{ _logger.LogWarning($"Объект не добавлен в набор {listBoxBulldozerStorages.SelectedItem.ToString()}");
MessageBox.Show("Не удалось добавить объект");
} }
} }
@ -148,15 +154,28 @@ namespace Bulldozer
{ {
return; return;
} }
int pos = Convert.ToInt32(textBoxDeletingBulldozer.Text); try
if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); int pos = Convert.ToInt32(textBoxDeletingBulldozer.Text);
pictureBoxCollection.Image = obj.ShowBulldozers(); if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Объект удален");
pictureBoxCollection.Image = obj.ShowBulldozers();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
}
} }
else catch (BulldozerNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
}
catch (Exception ex) {
MessageBox.Show("Неверный ввод");
_logger.LogWarning("Неверный ввод");
} }
} }
@ -188,13 +207,16 @@ namespace Bulldozer
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} _logger.LogInformation("Сохранение прошло успешно");
else
} catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation($"Не сохранилось: {ex.Message}");
} }
} }
} }
@ -207,15 +229,17 @@ namespace Bulldozer
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка прошла успешно");
ReloadObjects(); ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
} }
} }
} }

View File

@ -50,11 +50,11 @@ namespace Bulldozer.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public static int operator +(BulldozersGenericCollection<T, U> collect, T? obj) public static bool operator +(BulldozersGenericCollection<T, U> collect, T obj)
{ {
if (obj == null) if (obj == null)
return -1; return false;
return collect?._collection.Insert(obj) ?? -1; return collect._collection.Insert(obj);
} }
/// <summary> /// <summary>

View File

@ -1,6 +1,8 @@
using Bulldozer.DrawingObjects; using Bulldozer.DrawingObjects;
using Bulldozer.MovementStrategy; using Bulldozer.MovementStrategy;
using System.Text; using System.Text;
using Bulldozer.Exceptions;
using System.Numerics;
namespace Bulldozer.Generics namespace Bulldozer.Generics
{ {
@ -116,7 +118,7 @@ namespace Bulldozer.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
string toWrite = $"BulldozerStorage{Environment.NewLine}{data}"; string toWrite = $"BulldozerStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@ -139,7 +141,7 @@ namespace Bulldozer.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -147,11 +149,11 @@ namespace Bulldozer.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
throw new IOException("Нет данных для загрузки"); throw new ArgumentException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("BulldozerStorage")) if (!strs[0].StartsWith("BulldozerStorage"))
{ {
throw new IOException("Неверный формат данных"); throw new ArgumentException("Неверный формат данных");
} }
_bulldozerStorages.Clear(); _bulldozerStorages.Clear();
do do
@ -170,9 +172,20 @@ namespace Bulldozer.Generics
elem?.CreateDrawingBulldozer(_separatorForObject, _pictureWidth, _pictureHeight); elem?.CreateDrawingBulldozer(_separatorForObject, _pictureWidth, _pictureHeight);
if (bulldozer != null) if (bulldozer != null)
{ {
if ((collection + bulldozer) == -1) if (collection + bulldozer)
{ {
throw new IOException("Ошибка добавления в коллекцию"); try
{
_ = collection + bulldozer;
}
catch (BulldozerNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System.Numerics; using Bulldozer.Exceptions;
using System.Numerics;
namespace Bulldozer.Generics namespace Bulldozer.Generics
{ {
@ -38,12 +39,9 @@ namespace Bulldozer.Generics
/// </summary> /// </summary>
/// <param name="bulldozer">Добавляемый бульдозер</param> /// <param name="bulldozer">Добавляемый бульдозер</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T bulldozer) public bool Insert(T bulldozer)
{ {
if (_places.Count == _maxCount) return Insert(bulldozer, 0);
return -1;
Insert(bulldozer, 0);
return 1;
} }
/// <summary> /// <summary>
@ -51,11 +49,14 @@ namespace Bulldozer.Generics
/// </summary> /// </summary>
/// <param name="bulldozer">Добавляемый бульдозер</param> /// <param name="bulldozer">Добавляемый бульдозер</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T bulldozer , int position) public bool Insert(T bulldozer , int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount) {
throw new StorageOverflowException("Вставка невозможна.");
}
if (Count >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, bulldozer); _places.Insert(position, bulldozer);
return position; return true;
} }
/// <summary> /// <summary>
@ -66,8 +67,8 @@ namespace Bulldozer.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
return false; throw new BulldozerNotFoundException("Невалидная операция");
if (_places[position] == null) throw new BulldozerNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;

View File

@ -1,4 +1,10 @@
namespace Bulldozer.MovementStrategy using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Bulldozer;
namespace Bulldozer
{ {
internal static class Program internal static class Program
{ {
@ -9,7 +15,29 @@ namespace Bulldozer.MovementStrategy
static void Main() static void Main()
{ {
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormBulldozerCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBulldozerCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBulldozerCollection>().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);
});
} }
} }
} }