Compare commits

...

2 Commits

Author SHA1 Message Date
crum61kg
86398dc418 Логирование 2023-02-08 21:48:34 +04:00
crum61kg
7884e5e29c Генерация ошибок 2023-02-08 21:21:52 +04:00
8 changed files with 138 additions and 21 deletions

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -26,12 +27,18 @@ namespace WarmlyShip
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarmlyShip()
public FormMapWithSetWarmlyShip(ILogger<FormMapWithSetWarmlyShip> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@ -78,6 +85,7 @@ namespace WarmlyShip
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@ -155,6 +163,8 @@ namespace WarmlyShip
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
@ -165,6 +175,16 @@ namespace WarmlyShip
MessageBox.Show("Не удалось удалить объект");
}
}
catch (WarmlyShipNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления : {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка : {ex.Message}");
}
}
/// <summary>
/// Вывод набора
@ -237,13 +257,15 @@ namespace WarmlyShip
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -257,14 +279,16 @@ namespace WarmlyShip
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -98,7 +98,7 @@ namespace WarmlyShip
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -112,25 +112,24 @@ namespace WarmlyShip
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
using (StreamReader sr = new(filename))
{
if (!sr.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
@ -152,7 +151,6 @@ namespace WarmlyShip
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace WarmlyShip
{
internal static class Program
@ -11,7 +15,24 @@ namespace WarmlyShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarmlyShip());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetWarmlyShip>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetWarmlyShip>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -51,6 +51,7 @@ namespace WarmlyShip
/// <returns></returns>
public int Insert(T ship, int position)
{
//
if (position < 0 || position > Count)
{
return -1;
@ -69,6 +70,9 @@ namespace WarmlyShip
return null;
var result = _places[position];
_places.RemoveAt(position);
//throw new WarmlyShipNotFoundException(position);
return result;
}

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 WarmlyShip
{
[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,23 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<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.2.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

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 WarmlyShip
{
[Serializable]
internal class WarmlyShipNotFoundException : ApplicationException
{
public WarmlyShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public WarmlyShipNotFoundException() : base() { }
public WarmlyShipNotFoundException(string message) : base(message) { }
public WarmlyShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected WarmlyShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,15 @@
<?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>