Laba7 PIbd-22 Kalyshev Y V #10

Closed
Zyzf wants to merge 4 commits from Laba7 into Laba6
9 changed files with 218 additions and 39 deletions

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 PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
[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 context) : base(info, context) { }
}
}

View File

@ -1,4 +1,5 @@
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
@ -18,11 +19,16 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <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)
@ -68,6 +74,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@ -93,6 +100,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem}");
}
}
/// <summary>
@ -114,15 +122,30 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
return;
}
DrawningObjectBoat boat = new DrawningObjectBoat(drawingBoats);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
try
{
MessageBox.Show("Object added");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"В карту {listBoxMaps.SelectedItem} добавлен объект {boat.GetInfo()}");
}
else
{
MessageBox.Show("Невозможно добавить объект");
_logger.LogInformation($"Невозможно добавить объект {boat.GetInfo()} в карту {listBoxMaps.SelectedItem}");
}
} catch (StorageOverflowException ex)
{
MessageBox.Show("Cant add object");
MessageBox.Show($"Ошибка добавления: {ex.Message}");
_logger.LogWarning($"Ошибка добавления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта
@ -144,14 +167,28 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
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();
}
else
IDrawningObject boat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (boat != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Из карты {listBoxMaps.SelectedItem} удален объект {boat.GetInfo()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Невозможно удалить объект {boat.GetInfo()} в карту {listBoxMaps.SelectedItem}");
}
} catch (BoatNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка удаления: {ex.Message}");
} catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
@ -166,6 +203,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Показана гавань для карты {listBoxMaps.SelectedItem}");
}
/// <summary>
/// Вывод карты
@ -179,6 +217,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
_logger.LogInformation($"Показана карта {listBoxMaps.SelectedItem}");
}
/// <summary>
/// Перемещение
@ -221,13 +260,15 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
_logger.LogInformation($"Сохранен файл {saveFileDialog.FileName}");
} catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не сохранилось: {ex.Message}");
}
}
}
@ -240,14 +281,16 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
_logger.LogInformation($"Загружен файл {openFileDialog.FileName}");
} catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
}

View File

@ -94,7 +94,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -103,36 +103,35 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
using (FileStream fs = new(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine($"MapsCollection{Environment.NewLine}");
sw.WriteLine($"MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine($"{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 StreamReader(filename))
{
string str;
int count = 0;
while ((str = sr.ReadLine()) != null)
while ((str = sr.ReadLine()) != null && str != "")
{
if (count == 0)
{
if (!str.Contains("MapsCollection"))
{
return false;
throw new Exception("Формат данных в файле не правильный");
} else
{
count++;
@ -154,7 +153,6 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
_mapStorages.Add(elem[0], new MapWithSetBoatsGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}

View File

@ -9,4 +9,26 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serialog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serialog.json">
<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.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.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>
</Project>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
internal static class Program
@ -11,7 +16,31 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
// 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: "serialog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -55,14 +55,17 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
/// <param name="boat">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T boat, int position)
public void Insert(T boat, int position)
{
if (position < 0 || position > _places.Count)
if (_places.Count < _maxCount)
{
return false;
if (position < 0 || position > _places.Count)
{
throw new StorageOverflowException();
}
_places.Insert(position, boat);
}
_places.Insert(position, boat);
return true;
return;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@ -73,11 +76,11 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
if (position < 0 || position > _places.Count)
{
return null;
throw new BoatNotFoundException(position);
}
if (_places[position] == null)
{
return null;
throw new BoatNotFoundException(position);
}
T removed = _places[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 PIbd_22_Kalyshev_Y_V_MotorBoat_Base
{
[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) { }
}
}

View File

@ -0,0 +1,48 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "{Message:lj}: [{Level:u4}]{Timestamp:HH:mm:ss.fff}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Destructure": [
{
"Name": "ByTransforming",
"Args": {
"returnType": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base.EntityBoat",
"transformation": "r => new {r.Speed, r.Weight, BodyColor = r.BodyColor.Name }"
}
},
{
"Name": "ByTransforming",
"Args": {
"returnType": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base.EntitySpeedboat",
"transformation": "r => new {r.Speed, r.Weight, BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.bodyKit, r.wing, r.sportLine }"
}
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 10 }
}
],
"Properties": {
"Application": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base"
}
}
}

2
ok.txt
View File

@ -1,2 +0,0 @@
MapsCollection
ok|SimpleMap|100:100:Blue;100:100:Yellow:Blue:False:True:True;