Compare commits
2 Commits
e2305e4cdb
...
858eabc855
Author | SHA1 | Date | |
---|---|---|---|
858eabc855 | |||
ee1f6c1637 |
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@ -20,10 +21,11 @@ namespace GasolineTanker
|
||||
{ "Лужайка", new FormLawn() }
|
||||
};
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
|
||||
public FormMapWithSetTankers()
|
||||
private ILogger _logger;
|
||||
public FormMapWithSetTankers(ILogger<FormMapWithSetTankers> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
|
||||
comboBoxSelectorMap.Items.Clear();
|
||||
foreach (var elem in _mapsDict)
|
||||
@ -57,20 +59,24 @@ namespace GasolineTanker
|
||||
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||
return;
|
||||
}
|
||||
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
|
||||
{
|
||||
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
|
||||
return;
|
||||
}
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
|
||||
}
|
||||
|
||||
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
}
|
||||
|
||||
private void ButtonDeleteMap_Click(object sender, EventArgs e)
|
||||
@ -82,6 +88,7 @@ namespace GasolineTanker
|
||||
|
||||
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
ReloadMaps();
|
||||
}
|
||||
@ -94,6 +101,8 @@ namespace GasolineTanker
|
||||
formTankerConfig.Show();
|
||||
}
|
||||
private void InsertTankerCheck(DrawningTanker _tanker)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
{
|
||||
@ -103,11 +112,19 @@ namespace GasolineTanker
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + tanker >= 0)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation("Добавлен объект {@Tanker}", _tanker);
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@ -126,16 +143,32 @@ namespace GasolineTanker
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
|
||||
try
|
||||
{
|
||||
var deletedTanker = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
if (deletedTanker != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation("Из текущей карты удалён объект {@Tanker}", deletedTanker);
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (TankerNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonShowStorage_Click(object sender, EventArgs e)
|
||||
{
|
||||
@ -184,13 +217,18 @@ namespace GasolineTanker
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", 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);
|
||||
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -203,14 +241,17 @@ namespace GasolineTanker
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
|
||||
ReloadMaps();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
|
||||
MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,30 @@
|
||||
<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.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
|
||||
<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.0" />
|
||||
<PackageReference Include="Serilog" Version="2.12.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
|
||||
<PackageReference Include="Serilog.LoggerConfiguration.ConditionExtensions" Version="1.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -54,7 +54,7 @@ namespace GasolineTanker
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns></returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -68,7 +68,6 @@ namespace GasolineTanker
|
||||
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -76,18 +75,18 @@ namespace GasolineTanker
|
||||
/// </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 FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
string str = "";
|
||||
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
|
||||
{
|
||||
return false;
|
||||
throw new FileFormatException("Формат данных в файле не правильный");
|
||||
}
|
||||
_mapStorages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
@ -111,7 +110,6 @@ namespace GasolineTanker
|
||||
_mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
namespace GasolineTanker
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +15,47 @@ namespace GasolineTanker
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetTankers());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetTankers>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetTankers>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: "appsettings.json")
|
||||
.Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
/* private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetTankers>();
|
||||
|
||||
var serilogLogger = new LoggerConfiguration()
|
||||
.WriteTo.RollingFile("Logs\\log.txt")
|
||||
.CreateLogger();
|
||||
|
||||
services.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger: serilogLogger, dispose: true);
|
||||
});
|
||||
|
||||
}*/
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -18,7 +18,12 @@
|
||||
return Insert(tanker, 0);
|
||||
}
|
||||
public int Insert(T tanker, int position)
|
||||
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
if (position <= _places.Count && _places.Count < _maxCount && position >= 0)
|
||||
{
|
||||
_places.Insert(position, tanker);
|
||||
@ -29,6 +34,10 @@
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new TankerNotFoundException(position);
|
||||
}
|
||||
if (position < _places.Count && position >= 0)
|
||||
{
|
||||
var tanker = _places[position];
|
||||
|
19
GasolineTanker/GasolineTanker/StorageOverflowException.cs
Normal file
19
GasolineTanker/GasolineTanker/StorageOverflowException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GasolineTanker
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
}
|
19
GasolineTanker/GasolineTanker/TankerNotFoundException.cs
Normal file
19
GasolineTanker/GasolineTanker/TankerNotFoundException.cs
Normal file
@ -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 GasolineTanker
|
||||
{
|
||||
[Serializable]
|
||||
internal class TankerNotFoundException : ApplicationException
|
||||
{
|
||||
public TankerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public TankerNotFoundException() : base() { }
|
||||
public TankerNotFoundException(string message) : base(message) { }
|
||||
public TankerNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected TankerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
19
GasolineTanker/GasolineTanker/appsettings.json
Normal file
19
GasolineTanker/GasolineTanker/appsettings.json
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"outputTemplate": "{Timestamp:HH:mm:ss. zzz} [{Level}] {Message} {Exception} {NewLine}",
|
||||
"path": "D:/log.txt",
|
||||
"fileSizeLimitBytes": 2147483648
|
||||
}
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Serilog-Demo"
|
||||
}
|
||||
}
|
||||
}
|
13
GasolineTanker/GasolineTanker/nlog.config
Normal file
13
GasolineTanker/GasolineTanker/nlog.config
Normal 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 ="tankerlog-${shortdate}.log"/>
|
||||
</targets>
|
||||
<rules>
|
||||
<logger name ="*" minlevel ="Debug" writeTo ="toFile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
Loading…
Reference in New Issue
Block a user