изменения
This commit is contained in:
parent
05134ead4f
commit
1284f2afaa
@ -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.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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -4,6 +4,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AirBomber.DrawningObjects;
|
||||
using AirBomber.Exceptions;
|
||||
using AirBomber.MovementStrategy;
|
||||
|
||||
namespace AirBomber.Generics
|
||||
@ -77,7 +78,7 @@ namespace AirBomber.Generics
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -95,15 +96,13 @@ namespace AirBomber.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write($"BomberStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -111,11 +110,11 @@ namespace AirBomber.Generics
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не найден");
|
||||
}
|
||||
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
@ -123,11 +122,11 @@ namespace AirBomber.Generics
|
||||
string cheker = reader.ReadLine();
|
||||
if (cheker == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (!cheker.StartsWith("BomberStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Неверный формат ввода");
|
||||
}
|
||||
_bomberStorage.Clear();
|
||||
string strs;
|
||||
@ -136,31 +135,35 @@ namespace AirBomber.Generics
|
||||
{
|
||||
if (strs == null && firstinit)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (strs == null)
|
||||
{
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
firstinit = false;
|
||||
string name = strs.Split(_separatorForKeyValue)[0];
|
||||
BomberGenericCollection<DrawningBomber, DrawningObjectBomber> collection = new(_pictureWidth, _pictureHeight);
|
||||
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
|
||||
{
|
||||
DrawningBomber? usta =
|
||||
DrawningBomber? air =
|
||||
data?.CreateDrawningBomber(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (usta != null)
|
||||
if (air != null)
|
||||
{
|
||||
int? result = collection + usta;
|
||||
if (result == null || result.Value == -1)
|
||||
try { _ = collection + air; }
|
||||
catch (BomberNotFoundException e)
|
||||
{
|
||||
return false;
|
||||
throw e;
|
||||
}
|
||||
catch (StorageOverflowException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
_bomberStorage.Add(name, collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
19
AirBomber/BomberNotFoundException.cs
Normal file
19
AirBomber/BomberNotFoundException.cs
Normal 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) { }
|
||||
}
|
||||
}
|
@ -52,13 +52,13 @@ namespace AirBomber.DrawningObjects
|
||||
}
|
||||
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;
|
||||
_startPosY = y;
|
||||
|
@ -10,6 +10,9 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.Xml.Linq;
|
||||
using AirBomber.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AirBomber
|
||||
{
|
||||
@ -17,10 +20,13 @@ namespace AirBomber
|
||||
{
|
||||
private readonly BomberGenericStorage _bomber;
|
||||
|
||||
public FormBomberCollection()
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public FormBomberCollection(ILogger<FormBomberCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_bomber = new BomberGenericStorage(PicBoxBomberCollection.Width, PicBoxBomberCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private void ReloadObjects()
|
||||
@ -92,6 +98,7 @@ namespace AirBomber
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||
return;
|
||||
}
|
||||
var obj = _bomber[listBoxStorages.SelectedItem.ToString() ??
|
||||
@ -106,14 +113,24 @@ namespace AirBomber
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(MessageBoxBomber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
PicBoxBomberCollection.Image = obj.ShowBomber();
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
PicBoxBomberCollection.Image = obj.ShowBomber();
|
||||
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (BomberNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -123,23 +140,28 @@ namespace AirBomber
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Пустое название набора");
|
||||
return;
|
||||
}
|
||||
_bomber.AddSet(KitTextbox.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: {KitTextbox.Text}");
|
||||
}
|
||||
|
||||
private void RemoveKit_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление невыбранного набора");
|
||||
return;
|
||||
}
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_bomber.DelSet(listBoxStorages.SelectedItem.ToString()
|
||||
?? string.Empty);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -152,15 +174,16 @@ namespace AirBomber
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_bomber.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_bomber.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($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -169,14 +192,17 @@ namespace AirBomber
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_bomber.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Данные успешно загружены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_bomber.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($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace AirBomber
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,30 @@ namespace AirBomber
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using AirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
@ -53,12 +54,11 @@ namespace ProjectBomber.Generics
|
||||
public int Insert(T plane, int position)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount)
|
||||
return -1;
|
||||
throw new BomberNotFoundException(position);
|
||||
|
||||
if (Count >= _maxCount)
|
||||
return -1;
|
||||
|
||||
_places.Insert(position, plane);
|
||||
throw new StorageOverflowException(position);
|
||||
_places.Insert(0, plane);
|
||||
return position;
|
||||
}
|
||||
/// <summary>
|
||||
@ -70,14 +70,14 @@ namespace ProjectBomber.Generics
|
||||
{
|
||||
/// Проверка позиции
|
||||
if (position < 0 || position >= _places.Count)
|
||||
return false;
|
||||
throw new BomberNotFoundException(position);
|
||||
/// Удаление объекта из массива, присвоив элементу массива значение null
|
||||
_places[position] = null;
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта из набора по позиции
|
||||
/// </summary>
|
||||
/// </summary>
|
||||
/// <param name="position"></param>
|
||||
/// <returns></returns>
|
||||
public T? this[int position]
|
||||
@ -86,12 +86,16 @@ namespace ProjectBomber.Generics
|
||||
{
|
||||
if (position < 0 || position > _maxCount)
|
||||
return null;
|
||||
if (_places.Count <= position)
|
||||
return null;
|
||||
return _places[position];
|
||||
}
|
||||
set
|
||||
{
|
||||
if (position < 0 || position > _maxCount)
|
||||
return;
|
||||
if (_places.Count <= position)
|
||||
return;
|
||||
_places[position] = value;
|
||||
}
|
||||
}
|
||||
|
19
AirBomber/StorageOverflowException.cs
Normal file
19
AirBomber/StorageOverflowException.cs
Normal 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) { }
|
||||
}
|
||||
}
|
20
AirBomber/appsettings.json
Normal file
20
AirBomber/appsettings.json
Normal 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"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user