PIBD-13_Fomichev_V.S._LabWork07_Simple_ #8

Closed
slavaxom9k wants to merge 4 commits from labwork07 into labwork06
8 changed files with 110 additions and 89 deletions
Showing only changes of commit c2e1ca2cc1 - Show all commits

View File

@ -10,9 +10,13 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.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.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" />
</ItemGroup>
<ItemGroup>
@ -30,4 +34,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

@ -107,7 +107,7 @@ public class StorageCollection<T>
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
@ -175,11 +175,11 @@ public class StorageCollection<T>
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningArmoredCar() is T truck)
if (elem?.CreateDrawningArmoredCar() is T armoredCar)
{
try
{
if (collection.Insert(truck) == -1)
if (collection.Insert(armoredCar) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}

View File

@ -10,7 +10,7 @@ namespace AntiAircraftGun.Exceptions;
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
public class PositionOutOfCollectionException
public class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }

View File

@ -73,10 +73,11 @@ public partial class FormArmoredCarCollection : Form
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", armoredCar.GetDataForSave());
}
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
@ -92,7 +93,7 @@ public partial class FormArmoredCarCollection : Form
/// <param name="e"></param>
private void buttonRemoveArmoredCar_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
@ -102,7 +103,7 @@ public partial class FormArmoredCarCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null)
@ -111,12 +112,17 @@ public partial class FormArmoredCarCollection : Form
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -130,13 +136,8 @@ public partial class FormArmoredCarCollection : Form
{
return;
}
try
{
pictureBox.Image = _company.Show();
}
catch (PositionOutOfCollectionException) { }
catch (Exception) { }
pictureBox.Image = _company.Show();
}
/// <summary>
@ -153,27 +154,35 @@ public partial class FormArmoredCarCollection : Form
DrawningArmoredCar? armoredcar = null;
int counter = 100;
while (armoredcar == null)
try
{
armoredcar = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (armoredcar == null)
{
break;
armoredcar = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (armoredcar == null)
{
return;
}
FormAntiAircraftGun form = new()
{
SetArmoredCar = armoredcar
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (armoredcar == null)
{
return;
}
FormAntiAircraftGun form = new()
{
SetArmoredCar = armoredcar
};
form.ShowDialog();
}
/// <summary>
/// Обновление списка в listBoxCollection
@ -274,7 +283,7 @@ public partial class FormArmoredCarCollection : Form
{
switch (comboBoxSelectorCompany.Text)
{
case "База":
case "Хранилище":
_company = new CarBase(pictureBox.Width, pictureBox.Height, collection);
break;
}
@ -323,15 +332,13 @@ public partial class FormArmoredCarCollection : Form
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storageCollection.Keys)
{
listBoxCollection.Items.Add(collection);
}
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}

View File

@ -26,23 +26,18 @@ namespace AntiAircraftGun
/// <param name="services"></param>
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<FormArmoredCarCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
services
.AddSingleton<FormArmoredCarCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}
}
}

View File

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

View File

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