Changes: Throw exception

This commit is contained in:
Efi 2024-02-13 23:37:14 +04:00
parent 13465da48f
commit 1ca1dd6513
8 changed files with 132 additions and 158 deletions

View File

@ -11,18 +11,34 @@
<ItemGroup>
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.8" />
<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.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageReference Include="System.Text.Encodings.Web" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -38,8 +54,4 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</Project>

View File

@ -10,20 +10,20 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AirBomber.Exceptions;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace AirBomber
{
public partial class FormWarAirplaneCollection : Form
{
private readonly WarAirplaneGenericStorage _storage;
private readonly ILogger _logger;
public FormWarAirplaneCollection(ILogger<FormWarAirplaneCollection> logger)
public FormWarAirplaneCollection()
{
InitializeComponent();
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
@ -46,9 +46,9 @@ namespace AirBomber
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
private void ButtonAddObject_Click(object sender, EventArgs e) //работает
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
if (string.IsNullOrEmpty(textBoxStorageName.Text.ToString() ?? string.Empty))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -57,24 +57,26 @@ namespace AirBomber
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
Log.Information($"Добавлен набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
if (MessageBox.Show($"Удалить набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
if (listBoxStorages.SelectedIndex == null)
{
return;
}
Log.Information($"Удален набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {textBoxStorageName.Text}");
}
_logger.LogWarning("Отмена удаления набора");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@ -94,73 +96,83 @@ namespace AirBomber
if (obj == null)
{
return;
}
FormWarAirplaneConfig form = new FormWarAirplaneConfig();
form.Show();
Action<DrawingWarAirplane>? warAirplaneDelegate = new((m) =>
{
try
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
//int pos = Convert.ToInt32(maskedTextBoxNumber.Text); // TO DO
var q = obj + m;
if(q != -1)
{
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
MessageBox.Show("Не удалось добавить объект");
Log.Information("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogInformation($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
Action<Color>? ColorDelegate = new((m) =>
{
MessageBox.Show(m.ToString());
});
form.AddEvent(warAirplaneDelegate);
}
private void ButtonRemoveWarAirplane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
try
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
Log.Information("Не удалось удалить объект. Объект равен null");
MessageBox.Show("Не удалось удалить объект");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
if (maskedTextBoxNumber.Text == null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
MessageBox.Show("Не удалось удалить объект");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект номер {pos} из набора {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
catch(WarAirplaneNotFoundException ex)
catch (WarAirplaneNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -186,13 +198,13 @@ namespace AirBomber
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
Log.Information($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
Log.Warning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
@ -211,13 +223,13 @@ namespace AirBomber
{
listBoxStorages.Items.Add(collection);
}
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
Log.Information($"Данные загружены из файла {openFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
Log.Warning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}

View File

@ -1,27 +1,11 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Log = Serilog.Log;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Json;
using System;
using System.IO;
using System.Windows.Forms;
using Serilog.Configuration;
namespace AirBomber
{
@ -32,47 +16,26 @@ namespace AirBomber
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
Application.Run(serviceProvider.GetRequiredService<FormWarAirplaneCollection>());
pathNeed += path[i] + "\\";
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormWarAirplaneCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
logger.Information("Ñîçäàíèå Ëîãà");
});
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormWarAirplaneCollection());
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -18,31 +19,24 @@ namespace AirBomber.Generics
_maxCount = count;
_places = new List<T?>(count);
}
public bool Insert(T WarAirplane)
public int Insert(T WarAirplane)
{
if (_places.Count == _maxCount)
{
return false;
}
if (_places.Count == _maxCount) { throw new StorageOverflowException(_maxCount); }
Insert(WarAirplane, 0);
return true;
return 1;
}
public bool Insert(T WarAirplane, int position)
public int Insert(T WarAirplane, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) return -1;
_places.Insert(position, WarAirplane);
return true;
return position;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
throw new WarAirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
@ -53,23 +47,16 @@ namespace AirBomber.Generics
{
get
{
if (position < 0 || position >= _maxCount)
{
if (!(position >= 0 && position < Count))
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetWarAirplane(int? maxWarAirplane = null)
@ -83,6 +70,12 @@ namespace AirBomber.Generics
}
}
}
public T? Get(int position)
{
if (position < Count && position >= 0) { return _places[position]; }
return null;
}
}
}

View File

@ -10,7 +10,7 @@ namespace AirBomber.Exceptions
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе" +
public StorageOverflowException(int count) : base($"В наборе " +
$"превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }

View File

@ -13,6 +13,7 @@ namespace AirBomber.Generics
where T : DrawingWarAirplane
where U : IMoveableObject
{
public IEnumerable<T?> GetWarAirplane => _collection.GetWarAirplane();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 110;
@ -27,28 +28,26 @@ namespace AirBomber.Generics
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static bool operator +(WarAirplaneGenericCollection<T, U> collect, T?
public static int operator +(WarAirplaneGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return false;
return -1;
}
return collect?._collection.Insert(obj) ?? false;
collect._collection.Insert(obj);
return 1;
}
public static bool operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)
public static T? operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return true;
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
public Bitmap ShowWarAirplane()
{
@ -76,17 +75,16 @@ namespace AirBomber.Generics
}
private void DrawObjects(Graphics g)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
int i = 0;
foreach (var warAirplane in _collection.GetWarAirplane()) {
if (warAirplane != null)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
warAirplane.SetPosition((numPlacesInRow - 1 - (i % numPlacesInRow)) * _placeSizeWidth,
i / numPlacesInRow * _placeSizeHeight);
warAirplane.DrawTransport(g);
warAirplane.SetPosition((i % numPlacesInRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / numPlacesInRow) + _placeSizeHeight / 10);
warAirplane.DrawTransport(g);
}
i++;
}
i+=1;
}
}
}

View File

@ -124,8 +124,9 @@ namespace AirBomber.Generics
DrawingWarAirplane? warAirplane = elem?.CreateDrawingWarAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if(warAirplane != null)
{
if(!(collection + warAirplane))
if(collection + warAirplane == -1)
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}

View File

@ -1,20 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._AirBomber_Base\\AirBomber\\AirBomber\\Logs\\log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
"Args": { "path": "log.txt" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirBomber"
"Application": "Sample"
}
}
}