некоторые изменения

This commit is contained in:
xom9kxom9k 2024-05-05 12:00:21 +04:00
parent 9699679939
commit 176d02b1f8
13 changed files with 126 additions and 138 deletions

View File

@ -30,10 +30,4 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -98,8 +98,12 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningArmoredCar? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningArmoredCar? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
} }
return bitmap; return bitmap;

View File

@ -39,26 +39,30 @@ public class CarBase : AbstractCompany
/// </summary> /// </summary>
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int nowWidth = 0; int width = _pictureWidth / _placeSizeWidth;
int nowHeight = 0; int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (nowHeight > _pictureHeight / _placeSizeHeight) try
{ {
return; _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth, curHeight * _placeSizeHeight + 4);
} }
if (_collection?.Get(i) != null) catch (Exception) { }
{ if (curWidth > 0)
_collection?.Get(i)?.SetPictureSize(_pictureWidth , _pictureHeight); curWidth--;
_collection?.Get(i)?.SetPosition(_placeSizeWidth * nowWidth + 10, nowHeight * _placeSizeHeight * 2 );
}
if (nowWidth < _pictureWidth / _placeSizeWidth - 1) nowWidth++;
else else
{ {
nowWidth = 0; curWidth = width - 1;
nowHeight++; curHeight++;
}
if (curHeight > height)
{
return;
} }
} }
} }

View File

@ -1,6 +1,5 @@
using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.CollectionGenereticObject;
using AntiAircraftGun.Exceptions; using AntiAircraftGun.Exceptions;
using Exceptions;
namespace AntiAircraftGun.CollectionGenericObjects; namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary> /// <summary>

View File

@ -76,42 +76,33 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null) if (_collection[position] == null)
{ {
bool pushed = false; _collection[position] = obj;
for (int index = position + 1; index < Count; index++) return position;
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
} }
int index = position + 1;
// вставка while (index < _collection.Length)
_collection[position] = obj; {
return position; if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
++index;
}
index = position - 1;
while (index >= 0)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
--index;
}
throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)

View File

@ -9,6 +9,7 @@ namespace AntiAircraftGun.Exceptions;
/// <summary> /// <summary>
/// Класс, описывающий ошибку переполнения коллекции /// Класс, описывающий ошибку переполнения коллекции
/// </summary> /// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException public class CollectionOverflowException : ApplicationException
{ {
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое колличество: " + count) { } public CollectionOverflowException(int count) : base("В коллекции превышено допустимое колличество: " + count) { }

View File

@ -9,6 +9,7 @@ namespace AntiAircraftGun.Exceptions;
/// <summary> /// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента /// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary> /// </summary>
[Serializable]
public class ObjectNotFoundException : ApplicationException public class ObjectNotFoundException : ApplicationException
{ {
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }

View File

@ -12,7 +12,7 @@ namespace AntiAircraftGun.Exceptions;
[Serializable] [Serializable]
public class PositionOutOfCollectionException public class PositionOutOfCollectionException
{ {
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { } public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }

View File

@ -32,6 +32,7 @@ public partial class FormArmoredCarCollection : Form
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger; _logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -75,9 +76,11 @@ public partial class FormArmoredCarCollection : Form
} }
} }
catch (CollectionOverflowException) catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -93,10 +96,12 @@ public partial class FormArmoredCarCollection : Form
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try try
{ {
@ -104,19 +109,13 @@ public partial class FormArmoredCarCollection : Form
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} _logger.LogInformation("Удален объект по позиции " + pos);
else
{
MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (PositionOutOfCollectionException) catch (Exception ex)
{ {
MessageBox.Show("Ошибка при удалении объекта"); MessageBox.Show("Не удалось удалить объект");
} _logger.LogError("Ошибка: {Message}", ex.Message);
catch (Exception)
{
MessageBox.Show("Неизвестная ошибка при удалении объекта");
} }
} }
@ -205,18 +204,25 @@ public partial class FormArmoredCarCollection : Form
return; return;
} }
CollectionType collectionType = CollectionType.None; try
if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
} }
else if (radioButtonList.Checked) catch (Exception ex)
{ {
collectionType = CollectionType.List; _logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -230,13 +236,20 @@ public partial class FormArmoredCarCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// Создание комании /// Создание комании

View File

@ -14,31 +14,35 @@ namespace AntiAircraftGun
// 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();
var services = new ServiceCollection();
ConfigureService(services); ServiceCollection services = new();
using (ServiceProvider serviceProvider = services.BuildServiceProvider()) ConfigureServices(services);
{ using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormArmoredCarCollection>()); Application.Run(serviceProvider.GetRequiredService<FormArmoredCarCollection>());
}
} }
/// <summary> /// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI /// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary> /// </summary>
/// <param name="services"></param> /// <param name="services"></param>
private static void ConfigureService(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
{ {
services string[] path = Directory.GetCurrentDirectory().Split('\\');
.AddSingleton<FormArmoredCarCollection>() string pathNeed = "";
.AddLogging(option => for (int i = 0; i < path.Length - 3; i++)
{ {
option.SetMinimumLevel(LogLevel.Information); pathNeed += path[i] + "\\";
var config = new ConfigurationBuilder() }
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true) services.AddSingleton<FormArmoredCarCollection>()
.Build(); .AddLogging(option =>
option.AddSerilog(Log.Logger = new LoggerConfiguration() {
.ReadFrom.Configuration(config) option.SetMinimumLevel(LogLevel.Information);
.CreateLogger()); option.AddSerilog(new LoggerConfiguration()
}); .ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
} }
} }
}
} }

View File

@ -1,13 +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>

View File

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

View File

@ -1,25 +0,0 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Users\\ipazu\\Desktop\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}