Zargarov M.A LabWork07 #8

Closed
klllst wants to merge 2 commits from LabWork07 into LabWork06
8 changed files with 183 additions and 27 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 DoubleDeckerBus
{
[Serializable]
internal class BusNotFoundException : ApplicationException
{
public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BusNotFoundException() : base() { }
public BusNotFoundException(string message) : base(message) { }
public BusNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -8,6 +8,31 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilog.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="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<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

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -19,10 +20,12 @@ namespace DoubleDeckerBus
};
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
public FormMapWithSetBuses()
public FormMapWithSetBuses(ILogger<FormMapWithSetBuses> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var item in _mapsDict)
@ -64,15 +67,23 @@ namespace DoubleDeckerBus
{
return;
}
DrawningObjectBus boat = new(bus);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
try
{
DrawningObjectBus _bus = new(bus);
_ = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + _bus;
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Объект добавлен");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Не удалось добавить объект {ex.Message}");
_logger.LogInformation($"Объект не добаавлен {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось добавить объект {ex.Message}");
_logger.LogInformation($"Объект не добаавлен {ex.Message}");
}
}
private void ButtonRemoveBus_Click(object sender, EventArgs e)
@ -86,15 +97,31 @@ namespace DoubleDeckerBus
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();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Объект не удален");
}
}
else
catch (BusNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning("Автобус не найден");
}
catch (Exception ex)
{
MessageBox.Show($"Неизветсная шибка: {ex.Message}");
_logger.LogWarning("Неизвестная ошибка при удалении");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
@ -104,6 +131,7 @@ namespace DoubleDeckerBus
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Отображение хранилища");
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
@ -113,6 +141,7 @@ namespace DoubleDeckerBus
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
_logger.LogInformation($"Отображение карты");
}
private void ButtonMove_Click(object sender, EventArgs e)
@ -140,6 +169,7 @@ namespace DoubleDeckerBus
break;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
_logger.LogInformation($"Передвижение {name}");
}
private void ButtonAddMap_Click(object sender, EventArgs e)
@ -147,32 +177,38 @@ namespace DoubleDeckerBus
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($"Добавлена карта {textBoxNewMapName.Text}");
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Выбраная карта изменилась {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
_logger.LogWarning("Удаление карты не произошло. Не выбрана карта");
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
ReloadMaps();
}
}
@ -181,13 +217,16 @@ namespace DoubleDeckerBus
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
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} прошло не успешно");
}
}
}
@ -196,14 +235,17 @@ namespace DoubleDeckerBus
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна");
ReloadMaps();
}
else
catch (Exception ex)
{
MessageBox.Show("Ошибка при загрузке", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Ошибка при загрузке: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} прошла не успешно");
}
}
}

View File

@ -48,7 +48,7 @@ namespace DoubleDeckerBus
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -62,14 +62,13 @@ namespace DoubleDeckerBus
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
string line;
using (StreamReader sw = new(filename))
@ -77,7 +76,7 @@ namespace DoubleDeckerBus
line = sw.ReadLine();
if (line == null || !line.Contains("MapsCollection"))
{
return false;
throw new FileFormatException("Формат данных в файле не совпадает");
}
_mapStorages.Clear();
@ -99,8 +98,6 @@ namespace DoubleDeckerBus
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
line = sw.ReadLine();
}
return true;
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
namespace DoubleDeckerBus
{
internal static class Program
@ -11,7 +17,29 @@ namespace DoubleDeckerBus
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetBuses());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBuses>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetBuses>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -45,7 +45,10 @@ namespace DoubleDeckerBus
/// <returns></returns>
public int Insert(T bus, int position)
{
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1;
if (position < 0 || position >= _maxCount)
{
throw new BusNotFoundException("Место указано неверно");
}
BusyPlaces++;
_places.Insert(position, bus);
@ -58,7 +61,10 @@ namespace DoubleDeckerBus
/// <returns></returns>
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
if (position < 0 || position >= _maxCount)
{
throw new BusNotFoundException(position);
}
T savedBus = _places[position];
_places.RemoveAt(position);
return savedBus;

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 DoubleDeckerBus
{
[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,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": "DoubleDeckerBus"
}
}
}