This commit is contained in:
Alkin Ivan 2024-05-21 03:17:11 +04:00
parent 1dc111bb61
commit 5e46d4770d
13 changed files with 150 additions and 115 deletions

View File

@ -9,8 +9,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
@ -28,10 +32,4 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -59,9 +59,13 @@ public class AirPlaneSharingService : AbstractCompany
}
int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--)
{
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1)
{
col = numCols + 1;

View File

@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -40,38 +41,31 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
else
{
return null;
}
}
public int Insert(T obj)
{
if (Count == _maxCount) { return -1; }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;

View File

@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -49,14 +50,11 @@ where T : class
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
return null;
}
public int Insert(T obj)
{
for (int i = 0; i < Count; i++)
@ -67,14 +65,14 @@ where T : class
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@ -99,15 +97,16 @@ where T : class
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;

View File

@ -1,5 +1,5 @@
using AirBomber.Drawnings;
using ProjectCatamaran.Exceptions;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -188,11 +188,11 @@ public class StorageCollection<T>
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAirPlane() is T boat)
if (elem?.CreateDrawningAirPlane() is T airplane)
{
try
{
if (collection.Insert(boat) == -1)
if (collection.Insert(airplane) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace ProjectCatamaran.Exceptions;
namespace AirBomber.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace ProjectCatamaran.Exceptions;
namespace AirBomber.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace ProjectCatamaran.Exceptions;
namespace AirBomber.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции

View File

@ -275,7 +275,6 @@
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
файлToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// saveToolStripMenuItem
//

View File

@ -10,6 +10,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
namespace AirBomber
{
@ -70,6 +71,8 @@ namespace AirBomber
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
{
try
{
if (_company == null || airplane == null)
{
@ -80,10 +83,14 @@ namespace AirBomber
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
}
else
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -111,10 +118,13 @@ namespace AirBomber
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@ -122,15 +132,18 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -146,11 +159,13 @@ namespace AirBomber
return;
}
DrawningAirPlane? airplane = null;
DrawningAirPlane? airPlane = null;
int counter = 100;
while (airplane == null)
try
{
airplane = _company.GetRandomObject();
while (airPlane == null)
{
airPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
@ -158,15 +173,20 @@ namespace AirBomber
}
}
if (airplane == null)
if (airPlane == null)
{
return;
}
FormAirBomber form = new FormAirBomber();
form.SetAirPlane = airplane;
form.SetAirPlane = airPlane;
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
@ -195,6 +215,9 @@ namespace AirBomber
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -207,6 +230,12 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void RefreshListBoxItems()

View File

@ -1,6 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging
using Serilog;
namespace AirBomber;
@ -14,19 +16,28 @@ internal static class Program
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
ApplicationConfiguration.Initialize();
Application.Run(new FormAirPlaneCollection());
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirPlaneCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormAirPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
}

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

15
AirBomber/serilog.json Normal file
View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Applicatoin": "Sample"
}
}
}