Промежуточный коммит

This commit is contained in:
Danil Malin 2022-11-17 21:07:16 +04:00
parent 8438c8071d
commit 971fa53780
7 changed files with 144 additions and 27 deletions

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -27,11 +28,16 @@ namespace WarmlyLocomotive
/// </summary> /// </summary>
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetLocomotives() public FormMapWithSetLocomotives(ILogger<FormMapWithSetLocomotives> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@ -77,14 +83,29 @@ namespace WarmlyLocomotive
return; return;
} }
DrawningObjectLocomotive locomotive = new(drawningLocomotive); DrawningObjectLocomotive locomotive = new(drawningLocomotive);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1) try
{ {
MessageBox.Show("Объект добавлен"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive != -1)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); {
_logger.LogInformation($"Добавление объекта {locomotive}");
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект");
MessageBox.Show("Не удалось добавить объект");
}
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
} }
} }
/// <summary> /// <summary>
@ -107,14 +128,30 @@ namespace WarmlyLocomotive
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{ {
MessageBox.Show("Объект удален"); var deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); if (deletedLocomotive != null)
{
_logger.LogInformation($"Объект {deletedLocomotive} удалён");
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}");
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (LocomotiveNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); _logger.LogWarning($"Ошибка удаления: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
} }
} }
/// <summary> /// <summary>
@ -183,21 +220,25 @@ namespace WarmlyLocomotive
{ {
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
_logger.LogInformation("Не все данные заполнены при попытке создании карты");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
_logger.LogWarning($"Нет карты с названием {comboBoxSelectorMap.Text}");
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';')) if(textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{ {
_logger.LogInformation("Присутствуют символы, недопустимые для имени карты");
MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
/// <summary> /// <summary>
/// Выбор карты /// Выбор карты
@ -207,6 +248,7 @@ namespace WarmlyLocomotive
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Текущая карта сменена на {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
} }
/// <summary> /// <summary>
/// Удаление карты /// Удаление карты
@ -224,6 +266,7 @@ namespace WarmlyLocomotive
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
} }
} }
/// <summary> /// <summary>
@ -235,13 +278,16 @@ namespace WarmlyLocomotive
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Успешное сохранение по пути {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить данные. Ошибка - {ex.Message}");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -254,14 +300,17 @@ namespace WarmlyLocomotive
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if(openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Успешная загрузка по пути {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось загрузить данные. Ошибка - {ex.Message}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive
{
[Serializable]
internal class LocomotiveNotFoundException : ApplicationException
{
public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public LocomotiveNotFoundException() : base() { }
public LocomotiveNotFoundException(string message) : base(message) { }
public LocomotiveNotFoundException(string message, Exception exception) : base(message, exception) { }
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -94,7 +94,7 @@ namespace WarmlyLocomotive
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -108,18 +108,17 @@ namespace WarmlyLocomotive
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по локомотивам в депо из файла /// Загрузка информации по локомотивам в депо из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -127,7 +126,7 @@ namespace WarmlyLocomotive
if (!str.Contains("MapsCollection")) if (!str.Contains("MapsCollection"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
return false; throw new FileFormatException("Формат данных в файле не правильный");
} }
_mapStorages.Clear(); _mapStorages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
@ -150,7 +149,6 @@ namespace WarmlyLocomotive
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
} }
return true;
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace WarmlyLocomotive namespace WarmlyLocomotive
{ {
internal static class Program internal static class Program
@ -11,7 +16,25 @@ namespace WarmlyLocomotive
// 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 FormMapWithSetLocomotives()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetLocomotives>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetLocomotives>()
.AddLogging(option =>
{
var serilogLogger = new LoggerConfiguration()
.WriteTo.File("LogOfProgram.txt")
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(serilogLogger, true);
});
} }
} }
} }

View File

@ -46,7 +46,7 @@ namespace WarmlyLocomotive
{ {
if (position < 0 || position > Count || _maxCount == Count) if (position < 0 || position > Count || _maxCount == Count)
{ {
return -1; throw new StorageOverflowException(Count);
} }
_places.Insert(position, locomotive); _places.Insert(position, locomotive);
return position; return position;
@ -60,7 +60,7 @@ namespace WarmlyLocomotive
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new LocomotiveNotFoundException(position);
} }
T memoryObj = _places[position]; T memoryObj = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyLocomotive
{
[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 contex) : base(info, contex) { }
}
}

View File

@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>