Предварительно

This commit is contained in:
Victoria_Isaeva 2024-05-02 12:16:38 +04:00
parent 762dfe62da
commit 6f6529c9fe
7 changed files with 142 additions and 135 deletions

View File

@ -1,4 +1,5 @@
using ProjectAirbus.Drawnings;
using ProjectAirbus.Exceptions;
namespace ProjectAirbus.CollectionGenericObjects;
@ -35,7 +36,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -96,8 +97,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningBus? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningBus? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap;

View File

@ -1,6 +1,7 @@
using ProjectAirbus.CollectionGenericObjects;
using ProjectAirbus.Drawnings;
using ProjectAirbus.CollectionGenericObjects;
using ProjectAirbus.Exceptions;
namespace ProjectAirbus.CollectionGenericObjects;
@ -23,27 +24,17 @@ public class AerodromService : AbstractCompany
protected override void DrawBackgound(Graphics g)
{
Pen pen = new Pen(Color.LightBlue, 3);
int offsetX = 10;
int offsetY = -12;
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
numRows = 0;
while (y >= 0)
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width + 1; i++)
{
int numCols = 0;
while (x + _placeSizeWidth <= _pictureWidth)
for (int j = 0; j < height + 1; ++j)
{
numCols++;
g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8);
locCoord.Add(new Tuple<int, int>(x, y));
x += _placeSizeWidth + 2;
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight);
}
numRows++;
x = 1 + offsetX;
y -= _placeSizeHeight + 5 + offsetY;
}
}
protected override void SetObjectsPosition()
@ -56,12 +47,13 @@ public class AerodromService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 35);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 20);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0)
curWidth--;
else

View File

@ -43,27 +43,25 @@ public partial class FormBusCollection : Form
private void SetBus(DrawningBus? bus)
{
if (_company == null || bus == null)
{
return;
}
try
{
if (_company == null || bus == null)
{
return;
}
if (_company + bus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox1.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + bus.GetDataForSave());
}
var res = _company + bus;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox1.Image = _company.Show();
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
@ -76,7 +74,8 @@ public partial class FormBusCollection : Form
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
@ -84,17 +83,16 @@ public partial class FormBusCollection : Form
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox1.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции" + pos);
}
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox1.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -109,29 +107,27 @@ public partial class FormBusCollection : Form
{
return;
}
DrawningBus? bus = null;
int counter = 100;
try
while (bus == null)
{
while (bus == null)
bus = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
bus = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
break;
}
FormAirbus form = new()
{
SetBus = bus
};
form.ShowDialog();
}
catch (Exception ex)
if (bus == null)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
FormAirbus form = new()
{
SetBus = bus
};
form.ShowDialog();
}
/// <summary>
@ -156,31 +152,35 @@ public partial class FormBusCollection : Form
/// <param name="e"></param>
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
@ -189,30 +189,21 @@ public partial class FormBusCollection : Form
/// <param name="e"></param>
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
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);
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
@ -246,7 +237,8 @@ public partial class FormBusCollection : Form
return;
}
ICollectionGenericObjects<DrawningBus>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningBus>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -257,6 +249,7 @@ public partial class FormBusCollection : Form
{
case "Хранилище":
_company = new AerodromService(pictureBox1.Width, pictureBox1.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
@ -274,12 +267,11 @@ public partial class FormBusCollection : Form
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -290,16 +282,15 @@ public partial class FormBusCollection : Form
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@ -1,35 +1,44 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectAirbus
namespace ProjectAirbus;
internal static class Program
{
internal static class Program
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </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())
{
// 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);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
}
private static void ConfigureServices(ServiceCollection services)
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBusCollection>().AddLogging(option =>
{
services.AddSingleton<FormBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
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}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}

View File

@ -13,6 +13,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog" Version="5.3.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
@ -31,7 +33,7 @@
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

View File

@ -1,15 +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,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": "Airbus"
}
}
}