изменения

This commit is contained in:
Salikh 2023-11-29 09:54:55 +04:00
parent 05134ead4f
commit 1284f2afaa
9 changed files with 176 additions and 45 deletions

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" 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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using AirBomber.DrawningObjects; using AirBomber.DrawningObjects;
using AirBomber.Exceptions;
using AirBomber.MovementStrategy; using AirBomber.MovementStrategy;
namespace AirBomber.Generics namespace AirBomber.Generics
@ -77,7 +78,7 @@ namespace AirBomber.Generics
return null; return null;
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -95,15 +96,13 @@ namespace AirBomber.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write($"BomberStorage{Environment.NewLine}{data}"); writer.Write($"BomberStorage{Environment.NewLine}{data}");
} }
return true;
} }
/// <summary> /// <summary>
@ -111,11 +110,11 @@ namespace AirBomber.Generics
/// </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 Exception("Файл не найден");
} }
using (StreamReader reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
@ -123,11 +122,11 @@ namespace AirBomber.Generics
string cheker = reader.ReadLine(); string cheker = reader.ReadLine();
if (cheker == null) if (cheker == null)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!cheker.StartsWith("BomberStorage")) if (!cheker.StartsWith("BomberStorage"))
{ {
return false; throw new Exception("Неверный формат ввода");
} }
_bomberStorage.Clear(); _bomberStorage.Clear();
string strs; string strs;
@ -136,31 +135,35 @@ namespace AirBomber.Generics
{ {
if (strs == null && firstinit) if (strs == null && firstinit)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (strs == null) if (strs == null)
{ {
return false; break;
} }
firstinit = false; firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0]; string name = strs.Split(_separatorForKeyValue)[0];
BomberGenericCollection<DrawningBomber, DrawningObjectBomber> collection = new(_pictureWidth, _pictureHeight); BomberGenericCollection<DrawningBomber, DrawningObjectBomber> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords)) foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{ {
DrawningBomber? usta = DrawningBomber? air =
data?.CreateDrawningBomber(_separatorForObject, _pictureWidth, _pictureHeight); data?.CreateDrawningBomber(_separatorForObject, _pictureWidth, _pictureHeight);
if (usta != null) if (air != null)
{ {
int? result = collection + usta; try { _ = collection + air; }
if (result == null || result.Value == -1) catch (BomberNotFoundException e)
{ {
return false; throw e;
}
catch (StorageOverflowException e)
{
throw e;
} }
} }
} }
_bomberStorage.Add(name, collection); _bomberStorage.Add(name, collection);
} }
return true;
} }
} }
} }

View File

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

View File

@ -52,13 +52,13 @@ namespace AirBomber.DrawningObjects
} }
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
if (x < 0 || x + _PlaneWidth > _pictureWidth) if (_startPosX + _PlaneWidth > _pictureWidth + 180)
{ {
x = _pictureWidth - _PlaneWidth; _startPosX = _pictureWidth - _PlaneWidth;
} }
if (y < 0 || y + _PlaneWidth > _pictureHeight) if (_startPosY + _PlaneHeight > 740)
{ {
y = _pictureHeight - _PlaneWidth; _startPosY = 740 - _PlaneHeight;
} }
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;

View File

@ -10,6 +10,9 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq;
using AirBomber.Exceptions;
using Microsoft.Extensions.Logging;
namespace AirBomber namespace AirBomber
{ {
@ -17,10 +20,13 @@ namespace AirBomber
{ {
private readonly BomberGenericStorage _bomber; private readonly BomberGenericStorage _bomber;
public FormBomberCollection() private readonly ILogger _logger;
public FormBomberCollection(ILogger<FormBomberCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_bomber = new BomberGenericStorage(PicBoxBomberCollection.Width, PicBoxBomberCollection.Height); _bomber = new BomberGenericStorage(PicBoxBomberCollection.Width, PicBoxBomberCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
@ -92,6 +98,7 @@ namespace AirBomber
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление объекта из несуществующего набора");
return; return;
} }
var obj = _bomber[listBoxStorages.SelectedItem.ToString() ?? var obj = _bomber[listBoxStorages.SelectedItem.ToString() ??
@ -106,14 +113,24 @@ namespace AirBomber
return; return;
} }
int pos = Convert.ToInt32(MessageBoxBomber.Text); int pos = Convert.ToInt32(MessageBoxBomber.Text);
try
{
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
PicBoxBomberCollection.Image = obj.ShowBomber(); PicBoxBomberCollection.Image = obj.ShowBomber();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (BomberNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
@ -123,23 +140,28 @@ namespace AirBomber
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return; return;
} }
_bomber.AddSet(KitTextbox.Text); _bomber.AddSet(KitTextbox.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {KitTextbox.Text}");
} }
private void RemoveKit_Click(object sender, EventArgs e) private void RemoveKit_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление невыбранного набора");
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_bomber.DelSet(listBoxStorages.SelectedItem.ToString() _bomber.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
@ -152,15 +174,16 @@ namespace AirBomber
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_bomber.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _bomber.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }
@ -169,14 +192,17 @@ namespace AirBomber
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_bomber.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Данные успешно загружены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); _bomber.LoadData(openFileDialog.FileName);
ReloadObjects(); 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($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirBomber namespace AirBomber
{ {
internal static class Program internal static class Program
@ -11,7 +16,30 @@ namespace AirBomber
// 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 FormBomberCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBomberCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBomberCollection>().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

@ -1,4 +1,5 @@
using System; using AirBomber.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics; using System.Numerics;
@ -53,12 +54,11 @@ namespace ProjectBomber.Generics
public int Insert(T plane, int position) public int Insert(T plane, int position)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return -1; throw new BomberNotFoundException(position);
if (Count >= _maxCount) if (Count >= _maxCount)
return -1; throw new StorageOverflowException(position);
_places.Insert(0, plane);
_places.Insert(position, plane);
return position; return position;
} }
/// <summary> /// <summary>
@ -70,9 +70,9 @@ namespace ProjectBomber.Generics
{ {
/// Проверка позиции /// Проверка позиции
if (position < 0 || position >= _places.Count) if (position < 0 || position >= _places.Count)
return false; throw new BomberNotFoundException(position);
/// Удаление объекта из массива, присвоив элементу массива значение null /// Удаление объекта из массива, присвоив элементу массива значение null
_places[position] = null; _places.RemoveAt(position);
return true; return true;
} }
/// <summary> /// <summary>
@ -86,12 +86,16 @@ namespace ProjectBomber.Generics
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount)
return null; return null;
if (_places.Count <= position)
return null;
return _places[position]; return _places[position];
} }
set set
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount)
return; return;
if (_places.Count <= position)
return;
_places[position] = value; _places[position] = value;
} }
} }

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.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,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": "GasolineTanker"
}
}
}