есть трабла
This commit is contained in:
parent
a6bdc22ffe
commit
4f3cbbd9fd
20
ProjectExcavator/ProjectExcavator/AppSettings.json
Normal file
20
ProjectExcavator/ProjectExcavator/AppSettings.json
Normal 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": "Excavator"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectExcavator.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class ExcavatorNotFoundException : ApplicationException
|
||||
{
|
||||
public ExcavatorNotFoundException(int i) : base ($"Не найден объект по позиции {i}"){ }
|
||||
public ExcavatorNotFoundException():base() { }
|
||||
public ExcavatorNotFoundException(string message) : base(message) { }
|
||||
public ExcavatorNotFoundException(string message,Exception exception): base(message,exception) { }
|
||||
protected ExcavatorNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -58,7 +58,7 @@ namespace ProjectExcavator.Generic
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -76,27 +76,34 @@ namespace ProjectExcavator.Generic
|
||||
storageString += $"{excavator?.GetDataForSave(_separatorForObject)}{_separatorRecords}";
|
||||
}
|
||||
sw.WriteLine($"{storage.Key}{_separatorForKeyValue}{storageString}");
|
||||
if (storageString.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
{
|
||||
string? currentLine = sr.ReadLine();
|
||||
if (currentLine == null || !currentLine.Contains("ExcavatorStorage"))
|
||||
if (currentLine == null)
|
||||
{
|
||||
return false;
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
if (!currentLine.Contains("ExcavatorStorage"))
|
||||
{
|
||||
throw new FormatException("Неверный формат данных");
|
||||
}
|
||||
_excavatorStorages.Clear();
|
||||
currentLine = sr.ReadLine();
|
||||
@ -116,14 +123,13 @@ namespace ProjectExcavator.Generic
|
||||
{
|
||||
if (collection + excavator == -1)
|
||||
{
|
||||
return false;
|
||||
throw new ApplicationException("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
_excavatorStorages.Add(record[0], collection);
|
||||
currentLine = sr.ReadLine();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -10,6 +10,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectExcavator.Exceptions;
|
||||
|
||||
namespace ProjectExcavator
|
||||
{
|
||||
@ -19,11 +21,13 @@ namespace ProjectExcavator
|
||||
/// Набор объектов
|
||||
/// </summary>
|
||||
private readonly ExcavatorsGenericStorage _storage;
|
||||
public FormExcavatorCollection()
|
||||
private readonly ILogger _logger;
|
||||
public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new ExcavatorsGenericStorage(pictureBoxCollection.Width,
|
||||
pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
@ -51,11 +55,13 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
_logger.LogWarning($"Обновление набора не удалось (не все данные заполнены)");
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text} ");
|
||||
ReloadObjects();
|
||||
}
|
||||
/// <summary>
|
||||
@ -88,28 +94,39 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Добавление не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Добавление не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
if ((obj + excavator) != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowExcavator();
|
||||
}
|
||||
else
|
||||
if ((obj + excavator) != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавление успешно {listBoxStorages.SelectedItem.ToString()}");
|
||||
pictureBoxCollection.Image = obj.ShowExcavator();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Объект добавить не удалось");
|
||||
}
|
||||
}catch(ApplicationException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void buttonAddExcavator_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Добавление не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
@ -118,36 +135,49 @@ pictureBoxCollection.Height);
|
||||
return;
|
||||
}
|
||||
FormExcavatorConfig form = new FormExcavatorConfig();
|
||||
form.Show();
|
||||
form.AddEvent(AddExcavator);
|
||||
form.Show();
|
||||
}
|
||||
|
||||
private void buttonRemoveExcavator_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogInformation($"Удаление не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Удаление не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning($"Удаление не удалось (выбран вариант 'Нет')");
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowExcavator();
|
||||
if (obj - pos != null)
|
||||
{
|
||||
_logger.LogInformation($"Удаление успешно {listBoxStorages.SelectedItem.ToString()} {pos}");
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowExcavator();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Удаление не удалось(обьект не найден)");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch(ExcavatorNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Удаление не удалось {ex.Message}");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
private void RefreshCollection()
|
||||
@ -178,14 +208,16 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation($"Cохранение успешно");
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
else
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Сохранение не удалось {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -198,15 +230,18 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
ReloadObjects();
|
||||
RefreshCollection();
|
||||
MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Загрузка успешна");
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation($"Загрузка успешна");
|
||||
}
|
||||
}
|
||||
ReloadObjects();
|
||||
|
@ -1,3 +1,11 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Extensions.Logging;
|
||||
using Serilog.Settings.Configuration;
|
||||
|
||||
namespace ProjectExcavator
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +19,29 @@ namespace ProjectExcavator
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormExcavatorCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormExcavatorCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormExcavatorCollection>().AddLogging(option =>
|
||||
{
|
||||
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}appsettings.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,15 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectExcavator.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class StorageOverflowException: ApplicationException
|
||||
{
|
||||
public StorageOverflowException(int count): base($"В наборе превышено допустимое количество: {count}") { }
|
||||
public StorageOverflowException():base() { }
|
||||
public StorageOverflowException(string message):base(message) { }
|
||||
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user