Borschevskaya A.A. Lab Work 7 #9

Closed
pgirl1 wants to merge 12 commits from lab7 into lab6
8 changed files with 197 additions and 39 deletions

View File

@ -6,6 +6,29 @@
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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

View File

@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Windows.Forms;
using System;
using Microsoft.Extensions.Logging;
namespace ArmoredCar
{
@ -20,11 +21,16 @@ namespace ArmoredCar
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetArmoredCars()
public FormMapWithSetArmoredCars(ILogger<FormMapWithSetArmoredCars> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@ -64,15 +70,18 @@ namespace ArmoredCar
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты были заполнены не все данные");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Нет такой карты: {comboBoxSelectorMap.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Выбор карты
@ -83,6 +92,7 @@ namespace ArmoredCar
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
@ -100,6 +110,7 @@ namespace ArmoredCar
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
}
/// <summary>
@ -109,9 +120,9 @@ namespace ArmoredCar
/// <param name="e"></param>
private void ButtonAddarmoredCar_Click(object sender, EventArgs e)
{
var form = new FormArmoredCarConfig();
var form = new FormArmoredCarConfig();
form.AddEvent(AddArmoredCar);
form.Show();
form.Show();
}
private void AddArmoredCar(DrawningArmoredCar drawningArmoredCar)
@ -122,16 +133,30 @@ namespace ArmoredCar
}
DrawningObjectArmCar armoredCar = new(drawningArmoredCar);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + armoredCar > -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + armoredCar > -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект: {armoredCar.GetInfo()}");
}
else
{
_logger.LogWarning("Не удалось добавить объект");
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка добавления: {ex.Message}");
MessageBox.Show($"Ошибка добавления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка:{ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта
@ -153,15 +178,32 @@ namespace ArmoredCar
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
var armoredCar = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (armoredCar != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удален объект: {armoredCar.GetInfo()}");
}
else
{
_logger.LogWarning("Не удалось удалить объект");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (ArmoredCarNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка удаления: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
@ -229,14 +271,17 @@ namespace ArmoredCar
{
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);
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
_logger.LogWarning($"Не сохранилось: {ex.Message}");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -250,15 +295,19 @@ namespace ArmoredCar
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Загрузка карты из файла {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
_logger.LogWarning($"Не загрузилось: {ex.Message}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

View File

@ -83,7 +83,7 @@ namespace ArmoredCar
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -99,25 +99,24 @@ namespace ArmoredCar
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
}
}
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 FileNotFoundException("Файл не найден");
}
using (FileStream f = new(filename, FileMode.Open))
using (StreamReader sw = new(f, Encoding.UTF8))
{
if (!sw.ReadLine().Contains("MapsCollection"))
return false;
throw new FileFormatException("Формат данных в файле не правильный");
string? line;
_mapStorages.Clear();
while ((line = sw.ReadLine()) != null)
@ -138,8 +137,7 @@ namespace ArmoredCar
}
_mapStorages.Add(elem[0], new MapWithSetArmoredCarsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}
}

View File

@ -1,8 +1,10 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ArmoredCar
{
@ -16,8 +18,33 @@ namespace ArmoredCar
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMapWithSetArmoredCars());
Application.SetCompatibleTextRenderingDefault(false);
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetArmoredCars>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetArmoredCars>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -33,10 +33,8 @@ namespace ArmoredCar
/// <param name="armoredCar">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T armoredCar)
{
if (Count < _maxCount)
return Insert(armoredCar, 0);
return -1;
{
return Insert(armoredCar, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@ -46,6 +44,9 @@ namespace ArmoredCar
/// <returns></returns>
public int Insert(T armoredCar, int position)
{
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
if (position < 0 || position >= _maxCount)
return -1;
@ -62,6 +63,8 @@ namespace ArmoredCar
if (position < 0 || position >= Count)
return null;
T armoredCar = _places[position];
if (armoredCar == null)
throw new ArmoredCarNotFoundException(position);
_places.RemoveAt(position);
return armoredCar;
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredCar
{
[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

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "armoredCar_log-.log",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
}