доделаю

This commit is contained in:
sqdselo 2024-04-29 00:51:57 +04:00
parent 3cae6dc2f4
commit 4fc0549d2e
5 changed files with 100 additions and 60 deletions

View File

@ -1,5 +1,7 @@
using HoistingCrane.CollectionGenericObjects; using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using HoistingCrane.Entities;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -17,11 +19,16 @@ namespace HoistingCrane
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
public FormCarCollection() /// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection(ILogger<FormCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
panelCompanyTool.Enabled = false; panelCompanyTool.Enabled = false;
this.logger = logger;
} }
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
@ -49,10 +56,6 @@ namespace HoistingCrane
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
//else
//{
// MessageBox.Show("Не удалось добавить объект");
//}
} }
private static Color GetColor(Random random) private static Color GetColor(Random random)
{ {
@ -72,43 +75,47 @@ namespace HoistingCrane
} }
private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle)
{ {
if (_company == null || drawningTrackedVehicle == null)
try
{ {
if (_company + drawningTrackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект DrawningTrackedVehicle");
}
else
{
throw new Exception();
}
}
catch (Exception ex)
{
logger.LogError("Не удалось добавить объект");
return; return;
} }
if (_company + drawningTrackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
//else
//{
// MessageBox.Show("Не удалось добавить объект");
//}
} }
private void buttonDeleteCar_Click(object sender, EventArgs e) private void buttonDeleteCar_Click(object sender, EventArgs e)
{ {
try
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) throw new Exception();
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) throw new Exception();
int pos = Convert.ToInt32(maskedTextBox.Text);
if ((_company - pos) != null)
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
logger.LogInformation("удален объект по позиции: {pos}", pos);
}
}
catch(Exception ex)
{
logger.LogError("Не удалось удалить объект по позиции: {pos}", Convert.ToInt32(maskedTextBox.Text));
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if ((_company - pos) != null)
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
}
//else
//{
// MessageBox.Show("Не удалось удалить объект");
//}
} }
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
{ {
@ -148,6 +155,7 @@ namespace HoistingCrane
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
} }
} }
logger.LogInformation("Коллекция успешно обновлена");
} }
private void buttonCollectionAdd_Click(object sender, EventArgs e) private void buttonCollectionAdd_Click(object sender, EventArgs e)
{ {
@ -184,17 +192,18 @@ namespace HoistingCrane
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} };
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -203,6 +212,8 @@ namespace HoistingCrane
} }
panelCompanyTool.Enabled = true; panelCompanyTool.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary> /// <summary>
@ -214,23 +225,16 @@ namespace HoistingCrane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
bool saveSuccessful = false;
try try
{ {
_storageCollection.SaveData(saveFileDialog.FileName); _storageCollection.SaveData(saveFileDialog.FileName);
saveSuccessful = true; 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(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} logger.LogError("Ошибка: {Message}", ex.Message);
if (saveSuccessful)
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -244,25 +248,17 @@ namespace HoistingCrane
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if(openFileDialog.ShowDialog() == DialogResult.OK)
{ {
bool loadSuccessful = false;
try try
{ {
_storageCollection.LoadData(openFileDialog.FileName); _storageCollection.LoadData(openFileDialog.FileName);
loadSuccessful = true;
}
catch(Exception ex)
{
MessageBox.Show("Ошибка при загрузке данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if(loadSuccessful)
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -31,6 +31,7 @@ namespace HoistingCrane
panelColorPurple.MouseDown += panel_MouseDown; panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
/// <summary> /// <summary>
/// Привязка метода к событию /// Привязка метода к событию
/// </summary> /// </summary>

View File

@ -12,6 +12,11 @@
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" /> <None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -27,4 +32,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace HoistingCrane namespace HoistingCrane
{ {
internal static class Program internal static class Program
@ -11,8 +15,23 @@ namespace HoistingCrane
// 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();
Application.Run(new FormCarCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormCarCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCarCollection>().AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -0,0 +1,13 @@
<?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="C:\Logs\mylogfile.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>