Potapov N.S. LabWork07 #9
19
Boats/Boats/BoatNotFoundException.cs
Normal file
19
Boats/Boats/BoatNotFoundException.cs
Normal 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 Boats
|
||||
{
|
||||
[Serializable]
|
||||
internal class BoatNotFoundException : ApplicationException
|
||||
{
|
||||
public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public BoatNotFoundException() : base() { }
|
||||
public BoatNotFoundException(string message) : base(message) { }
|
||||
public BoatNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -8,6 +8,29 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</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.FileExtensions" 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.1.0" />
|
||||
<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>
|
||||
@ -23,4 +46,6 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties jsconfig1_1json__JsonSchema="{" /></VisualStudio></ProjectExtensions>
|
||||
|
||||
</Project>
|
@ -51,9 +51,9 @@ namespace Boats
|
||||
/// <returns></returns>
|
||||
public static string GetDataForSave(this DrawingBoat drawingBoat)
|
||||
{
|
||||
var car = drawingBoat.Boat;
|
||||
var str = $"{car.Speed}{_separatorForObject}{car.Weight}{_separatorForObject}{car.BodyColor.Name}";
|
||||
if (car is not EntityCatamaran catamaran)
|
||||
var boat = drawingBoat.Boat;
|
||||
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
|
||||
if (boat is not EntityCatamaran catamaran)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@ -25,6 +26,7 @@ namespace Boats
|
||||
/// Объект от коллекции карт
|
||||
/// </summary>
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Объект от класса карты с набором объектов
|
||||
/// </summary>
|
||||
@ -32,9 +34,10 @@ namespace Boats
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormMapWithSetBoats()
|
||||
public FormMapWithSetBoats(ILogger<FormMapWithSetBoats> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
|
||||
ComboBoxSelectorMap.Items.Clear();
|
||||
foreach (var elem in _mapsDict)
|
||||
@ -124,15 +127,29 @@ namespace Boats
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
pos -= 1;
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
var deletedBoat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
if (deletedBoat != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Удален объект {deletedBoat.GetType().Name}");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}: объект равен null");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (BoatNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -212,6 +229,7 @@ namespace Boats
|
||||
}
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление карты
|
||||
@ -228,6 +246,7 @@ namespace Boats
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? ""}");
|
||||
ReloadMaps();
|
||||
}
|
||||
}
|
||||
@ -239,6 +258,7 @@ namespace Boats
|
||||
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem?.ToString() ?? ""}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Listener для добавления новой лодки из формы
|
||||
@ -246,19 +266,30 @@ namespace Boats
|
||||
/// <param name="drawingBoat"></param>
|
||||
private void AddBoatListener(DrawingBoat drawingBoat)
|
||||
{
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawingObjectBoat boat = new(drawingBoat);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавлен объект {drawingBoat.GetType().Name}");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
DrawingObjectBoat boat = new(drawingBoat);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
|
||||
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -270,13 +301,16 @@ namespace Boats
|
||||
{
|
||||
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);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось сохранить файл '{saveFileDialog.FileName}'. Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -289,15 +323,18 @@ namespace Boats
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
ReloadMaps();
|
||||
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Открытие файла '{openFileDialog.FileName}' прошло успешно");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось открыть файл {openFileDialog.FileName}. Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -247,9 +247,9 @@ namespace Boats
|
||||
public string GetData(char separatorType, char separatorData)
|
||||
{
|
||||
string data = $"{_map.GetType().Name}{separatorType}";
|
||||
foreach (var car in _setBoats.GetBoats())
|
||||
foreach (var boat in _setBoats.GetBoats())
|
||||
{
|
||||
data += $"{car.GetInfo()}{separatorData}";
|
||||
data += $"{boat.GetInfo()}{separatorData}";
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
@ -93,7 +93,7 @@ namespace Boats
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns></returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -107,18 +107,17 @@ namespace Boats
|
||||
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 (StreamReader sr = File.OpenText(filename))
|
||||
{
|
||||
@ -126,7 +125,7 @@ namespace Boats
|
||||
if (currentLine == null || !currentLine.Contains("MapsCollection"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new FileFormatException("Формат данных в файле не правильный");
|
||||
}
|
||||
//очищаем записи
|
||||
_mapStorages.Clear();
|
||||
@ -156,7 +155,6 @@ namespace Boats
|
||||
currentLine = sr.ReadLine();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,9 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Extensions.Logging;
|
||||
|
||||
namespace Boats
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +17,30 @@ namespace Boats
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetBoats());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBoats>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetBoats>()
|
||||
.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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -42,8 +42,9 @@ namespace Boats
|
||||
public int Insert(T boat)
|
||||
{
|
||||
// Проверка на _maxCount
|
||||
// Если достигли максимального значения - выбрасываем исключение
|
||||
if (Count == _maxCount)
|
||||
return -1;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
// Вставка в начало набора
|
||||
return Insert(boat, 0);
|
||||
}
|
||||
@ -69,10 +70,12 @@ namespace Boats
|
||||
public T Remove(int position)
|
||||
{
|
||||
// Проверка позиции
|
||||
if (Count == 0 || position < 0 || position >= _maxCount)
|
||||
return null;
|
||||
// Если позиция неверная (пустой быть не может, потому что у нас список),
|
||||
// то выбрасываем исключение
|
||||
if (position < 0 || position >= Count)
|
||||
throw new BoatNotFoundException(position);
|
||||
T boat = _places[position];
|
||||
_places[position] = null;
|
||||
_places.RemoveAt(position);
|
||||
return boat;
|
||||
}
|
||||
public T this[int position]
|
||||
|
19
Boats/Boats/StorageOverflowException.cs
Normal file
19
Boats/Boats/StorageOverflowException.cs
Normal 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 Boats
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
}
|
20
Boats/Boats/appSettings.json
Normal file
20
Boats/Boats/appSettings.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Boats"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user