2 Commits
Lab06 ... Lab07

8 changed files with 181 additions and 36 deletions

View File

@@ -1,4 +1,6 @@
using System; using Microsoft.Extensions.Logging;
using Serilog.Core;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -25,13 +27,17 @@ namespace Stormtrooper
/// Объект от коллекции карт /// Объект от коллекции карт
/// </summary> /// </summary>
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetStormtroopers() public FormMapWithSetStormtroopers(ILogger<FormMapWithSetStormtroopers> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@@ -46,28 +52,37 @@ namespace Stormtrooper
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddStorm_Click(object sender, EventArgs e) private void ButtonAddStorm_Click(object sender, EventArgs e)
{ {
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
var formStormConfig = new FormStormtrooperConfig(); var formStormConfig = new FormStormtrooperConfig();
formStormConfig.AddEvent(AddStormtrooper); formStormConfig.AddEvent(AddStormtrooper);
formStormConfig.Show(); formStormConfig.Show();
} }
private void AddStormtrooper (Drawning storm) private void AddStormtrooper(Drawning storm)
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
return; return;
} }
DrawningObjectStorm st = new(storm); try
{ {
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + st != -1) int res = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectStorm(storm);
{ MessageBox.Show("Объект добавлен");
MessageBox.Show("Объект добавлен"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); _logger.LogInformation($"Добавление объекта: {storm.ToString()}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show($"Не удалось добавить объект: {ex.Message}");
} _logger.LogWarning($"Ошибка добавления объекта: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Ошибка добавления объекта: {ex.Message}");
} }
} }
/// <summary> /// <summary>
@@ -89,16 +104,26 @@ namespace Stormtrooper
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{ {
IDrawningObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удаление объекта: {drawingObject.ToString()}");
} }
else catch (StormtrooperNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
} }
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
}
} }
/// <summary> /// <summary>
/// Вывод набора /// Вывод набора
@@ -188,11 +213,13 @@ namespace Stormtrooper
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
} }
private void ButtonDeleteMap_Click(object sender, EventArgs e) private void ButtonDeleteMap_Click(object sender, EventArgs e)
@@ -206,6 +233,7 @@ namespace Stormtrooper
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
} }
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}");
} }
/// <summary> /// <summary>
/// Обработка нажатия "Сохранение" /// Обработка нажатия "Сохранение"
@@ -216,13 +244,16 @@ namespace Stormtrooper
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Information); _mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение данных в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка сохранения данных: {ex.Message}");
} }
} }
} }
@@ -235,14 +266,17 @@ namespace Stormtrooper
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Загрузка данных из файла {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка загрузки данных: {ex.Message}");
} }
} }
} }

View File

@@ -83,7 +83,7 @@ namespace Stormtrooper
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@@ -98,18 +98,17 @@ namespace Stormtrooper
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"); sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по самолётам в ангаре из файла /// Загрузка информации по самолётам в ангаре из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
string line; string line;
using (StreamReader sw = new(filename)) using (StreamReader sw = new(filename))
@@ -117,7 +116,7 @@ namespace Stormtrooper
line = sw.ReadLine(); line = sw.ReadLine();
if (line == null || !line.Contains("MapsCollection")) if (line == null || !line.Contains("MapsCollection"))
{ {
return false; throw new FileFormatException("Неверный формат файла");
} }
_mapStorages.Clear(); _mapStorages.Clear();
@@ -142,8 +141,6 @@ namespace Stormtrooper
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
line = sw.ReadLine(); line = sw.ReadLine();
} }
return true;
} }
} }

View File

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

View File

@@ -39,7 +39,6 @@ namespace Stormtrooper
/// <returns></returns> /// <returns></returns>
public int Insert(T stormtrooper) public int Insert(T stormtrooper)
{ {
if (_places.Count + 1 >= _maxCount) return -1;
return Insert(stormtrooper, 0); return Insert(stormtrooper, 0);
} }
/// <summary> /// <summary>
@@ -50,8 +49,9 @@ namespace Stormtrooper
/// <returns></returns> /// <returns></returns>
public int Insert(T stormtrooper, int position) public int Insert(T stormtrooper, int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount)
if (_places.Count + 1 >= _maxCount) return -1; throw new StorageOverflowException(_maxCount);
if (_places.Count >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, stormtrooper); _places.Insert(position, stormtrooper);
return position; return position;
} }
@@ -62,7 +62,9 @@ namespace Stormtrooper
/// <returns></returns> /// <returns></returns>
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _maxCount) return null; if (position < 0 || position >= _maxCount)
throw new StormtrooperNotFoundException();
if (position >= _places.Count) throw new StormtrooperNotFoundException(position);
T saveStorm = _places[position]; T saveStorm = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);
return saveStorm; return saveStorm;

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 Stormtrooper
{
[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

@@ -8,6 +8,28 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

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 Stormtrooper
{
[Serializable]
internal class StormtrooperNotFoundException : ApplicationException
{
public StormtrooperNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public StormtrooperNotFoundException() : base("Выход за границы") { }
public StormtrooperNotFoundException(string message) : base(message) { }
public StormtrooperNotFoundException(string message, Exception exception) : base(message, exception) { }
protected StormtrooperNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,24 @@
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
],
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs/log.log" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
}
}