Лабораторная работа 7
This commit is contained in:
parent
f52af0e723
commit
7c2ac102e0
@ -8,6 +8,21 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
|
||||||
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.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>
|
||||||
@ -23,4 +38,8 @@
|
|||||||
</EmbeddedResource>
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Logs\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
@ -10,16 +10,20 @@ using System.Linq;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
using AirBomber.Exceptions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace AirBomber
|
namespace AirBomber
|
||||||
{
|
{
|
||||||
public partial class FormWarAirplaneCollection : Form
|
public partial class FormWarAirplaneCollection : Form
|
||||||
{
|
{
|
||||||
private readonly WarAirplaneGenericStorage _storage;
|
private readonly WarAirplaneGenericStorage _storage;
|
||||||
public FormWarAirplaneCollection()
|
private readonly ILogger _logger;
|
||||||
|
public FormWarAirplaneCollection(ILogger<FormWarAirplaneCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
private void ReloadObjects()
|
private void ReloadObjects()
|
||||||
{
|
{
|
||||||
@ -53,11 +57,13 @@ namespace AirBomber
|
|||||||
|
|
||||||
_storage.AddSet(textBoxStorageName.Text);
|
_storage.AddSet(textBoxStorageName.Text);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
|
||||||
}
|
}
|
||||||
private void ButtonDelObject__Click(object sender, EventArgs e)
|
private void ButtonDelObject__Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (listBoxStorages.SelectedIndex == -1)
|
if (listBoxStorages.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление невыбранного набора");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
|
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
|
||||||
@ -66,8 +72,9 @@ namespace AirBomber
|
|||||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
|
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
|
||||||
?? string.Empty);
|
?? string.Empty);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Удален набор: {textBoxStorageName.Text}");
|
||||||
}
|
}
|
||||||
|
_logger.LogWarning("Отмена удаления набора");
|
||||||
}
|
}
|
||||||
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
|
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
@ -106,6 +113,7 @@ namespace AirBomber
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogWarning($"Не удалось добавить объект");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -119,6 +127,7 @@ namespace AirBomber
|
|||||||
{
|
{
|
||||||
if (listBoxStorages.SelectedIndex == -1)
|
if (listBoxStorages.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||||
@ -130,17 +139,28 @@ namespace AirBomber
|
|||||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Отмена удаления объекта");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||||
if (obj - pos != null)
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
if (obj - pos != null)
|
||||||
pictureBoxCollection.Image = obj.ShowWarAirplane();
|
{
|
||||||
|
MessageBox.Show("Объект удален");
|
||||||
|
_logger.LogInformation($"Удален объект с позиции {pos}");
|
||||||
|
pictureBoxCollection.Image = obj.ShowWarAirplane();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||||
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
catch(WarAirplaneNotFoundException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show(ex.Message);
|
||||||
|
_logger.LogWarning($"{ex.Message} из {listBoxStorages.SelectedItem.ToString()}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
||||||
@ -161,15 +181,18 @@ namespace AirBomber
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storage.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storage.SaveData(saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно",
|
MessageBox.Show("Сохранение прошло успешно",
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
|
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
|
||||||
}
|
}
|
||||||
else
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат",
|
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -179,19 +202,22 @@ namespace AirBomber
|
|||||||
{
|
{
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storage.LoadData(openFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storage.LoadData(openFileDialog.FileName);
|
||||||
MessageBox.Show("Загрузка прошла успешно",
|
MessageBox.Show("Загрузка прошла успешно",
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
foreach (var collection in _storage.Keys)
|
foreach (var collection in _storage.Keys)
|
||||||
{
|
{
|
||||||
listBoxStorages.Items.Add(collection);
|
listBoxStorages.Items.Add(collection);
|
||||||
}
|
}
|
||||||
|
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
|
||||||
}
|
}
|
||||||
else
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не загрузилось", "Результат",
|
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,28 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Drawing;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
using Microsoft.VisualBasic.Logging;
|
||||||
|
using Serilog;
|
||||||
|
using Serilog.Events;
|
||||||
|
using Serilog.Formatting.Json;
|
||||||
|
using Log = Serilog.Log;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Serilog;
|
||||||
|
using Serilog.Core;
|
||||||
|
using Serilog.Events;
|
||||||
|
using Serilog.Formatting.Json;
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace AirBomber
|
namespace AirBomber
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -6,12 +31,48 @@ namespace AirBomber
|
|||||||
/// The main entry point for the application.
|
/// The main entry point for the application.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[STAThread]
|
[STAThread]
|
||||||
|
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
// 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 FormWarAirplaneCollection());
|
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
ConfigureServices(services);
|
||||||
|
|
||||||
|
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||||
|
{
|
||||||
|
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormWarAirplaneCollection>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
|
||||||
|
string path = Directory.GetCurrentDirectory();
|
||||||
|
path = path.Substring(0, path.LastIndexOf("\\"));
|
||||||
|
path = path.Substring(0, path.LastIndexOf("\\"));
|
||||||
|
path = path.Substring(0, path.LastIndexOf("\\"));
|
||||||
|
|
||||||
|
services.AddSingleton<FormWarAirplaneCollection>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
var configuration = new ConfigurationBuilder()
|
||||||
|
.SetBasePath(Directory.GetCurrentDirectory())
|
||||||
|
.AddJsonFile(path: path + "\\appSetting.json", optional: false, reloadOnChange: true)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var logger = new LoggerConfiguration()
|
||||||
|
.ReadFrom.Configuration(configuration)
|
||||||
|
.CreateLogger();
|
||||||
|
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddSerilog(logger);
|
||||||
|
logger.Information("Ñîçäàíèå Ëîãà");
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
20
AirBomber/AirBomber/StorageOverflowException.cs
Normal file
20
AirBomber/AirBomber/StorageOverflowException.cs
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace AirBomber.Exceptions
|
||||||
|
{
|
||||||
|
[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) { }
|
||||||
|
public StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||||
|
}
|
||||||
|
}
|
@ -73,7 +73,7 @@ namespace AirBomber.Generics
|
|||||||
}
|
}
|
||||||
if(data.Length == 0)
|
if(data.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||||
}
|
}
|
||||||
using FileStream fs = new(filename, FileMode.Create);
|
using FileStream fs = new(filename, FileMode.Create);
|
||||||
byte[] info = new UTF8Encoding(true).GetBytes($"WarAirplaneStorage" +
|
byte[] info = new UTF8Encoding(true).GetBytes($"WarAirplaneStorage" +
|
||||||
@ -85,7 +85,7 @@ namespace AirBomber.Generics
|
|||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Файл не найден");
|
||||||
}
|
}
|
||||||
string bufferTextFromFile = "";
|
string bufferTextFromFile = "";
|
||||||
using (FileStream fs = new(filename, FileMode.Open))
|
using (FileStream fs = new(filename, FileMode.Open))
|
||||||
@ -101,11 +101,11 @@ namespace AirBomber.Generics
|
|||||||
StringSplitOptions.RemoveEmptyEntries);
|
StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (strs == null || strs.Length == 0)
|
if (strs == null || strs.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Нет данных для загрузки");
|
||||||
}
|
}
|
||||||
if (!strs[0].StartsWith("WarAirplaneStorage"))
|
if (!strs[0].StartsWith("WarAirplaneStorage"))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Неверный формат данных");
|
||||||
}
|
}
|
||||||
_warAirplaneStorages.Clear();
|
_warAirplaneStorages.Clear();
|
||||||
foreach (string data in strs)
|
foreach (string data in strs)
|
||||||
@ -126,7 +126,7 @@ namespace AirBomber.Generics
|
|||||||
{
|
{
|
||||||
if(!(collection + warAirplane))
|
if(!(collection + warAirplane))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Ошибка добавления в коллекцию");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
20
AirBomber/AirBomber/WarAirplaneNotFoundException.cs
Normal file
20
AirBomber/AirBomber/WarAirplaneNotFoundException.cs
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace AirBomber.Exceptions
|
||||||
|
{
|
||||||
|
[Serializable]
|
||||||
|
internal class WarAirplaneNotFoundException : ApplicationException
|
||||||
|
{
|
||||||
|
public WarAirplaneNotFoundException(int i) : base($"Не найден объект по" +
|
||||||
|
$"позиции {i}") { }
|
||||||
|
public WarAirplaneNotFoundException() : base() { }
|
||||||
|
public WarAirplaneNotFoundException(string message) : base(message) { }
|
||||||
|
public WarAirplaneNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||||
|
public WarAirplaneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||||
|
}
|
||||||
|
}
|
20
AirBomber/AirBomber/appSetting.json
Normal file
20
AirBomber/AirBomber/appSetting.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"Serilog": {
|
||||||
|
"Using": [ "Serilog.Sinks.File" ],
|
||||||
|
"MinimumLevel": "Information",
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._AirBomber_Base\\AirBomber\\AirBomber\\Logs\\log.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "AirBomber"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user