PIbd-21_MasenkinMS_LabWork07 #8
@ -8,6 +8,17 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" 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="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,6 +1,8 @@
|
||||
using AccordionBus.Drawings;
|
||||
using AccordionBus.Exceptions;
|
||||
using AccordionBus.Generics;
|
||||
using AccordionBus.MovementStrategy;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@ -24,13 +26,19 @@ namespace AccordionBus
|
||||
/// </summary>
|
||||
private readonly BusGenericStorage _storage;
|
||||
|
||||
/// <summary>
|
||||
/// Логгер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public BusCollectionForm()
|
||||
public BusCollectionForm(ILogger<BusCollectionForm> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new BusGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -66,11 +74,13 @@ namespace AccordionBus
|
||||
if (string.IsNullOrEmpty(buttonAddObject.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось добавить набор: {maskedTextBoxStorageName.Text}. Не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
|
||||
_storage.AddSet(maskedTextBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: {maskedTextBoxStorageName.Text}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -92,14 +102,18 @@ namespace AccordionBus
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Не выбран набор для удаления");
|
||||
return;
|
||||
}
|
||||
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
_logger.LogWarning("Отмена удаления набора");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -111,6 +125,7 @@ namespace AccordionBus
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Не выбран набор для добавления объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -120,18 +135,25 @@ namespace AccordionBus
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Выбранный набор не существует");
|
||||
return;
|
||||
}
|
||||
|
||||
if (obj + bus > -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
if (obj + bus > -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
_logger.LogInformation($"Добавлен объект: {bus}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
|
||||
MessageBox.Show($"Не удалось добавить объект: {ex.Message}");
|
||||
}
|
||||
|
||||
});
|
||||
form.Show();
|
||||
}
|
||||
@ -145,29 +167,37 @@ namespace AccordionBus
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Не выбран набор для удаления объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Выбранный набор не существует");
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning("Отмена удаления объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
if (obj - pos != false)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
_logger.LogInformation($"Удален объект с позиции {pos}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
|
||||
MessageBox.Show($"Не удалось удалить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -201,13 +231,16 @@ namespace AccordionBus
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -221,14 +254,17 @@ namespace AccordionBus
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
ReloadObjects();
|
||||
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($"Не удалось сохранить данные из файла: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -72,7 +72,7 @@ namespace AccordionBus.Generics
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
return -1;
|
||||
throw new NullReferenceException();
|
||||
}
|
||||
|
||||
return collect?._collection.Insert(obj) ?? -1;
|
||||
@ -86,14 +86,14 @@ namespace AccordionBus.Generics
|
||||
/// <returns></returns>
|
||||
public static bool operator -(BusGenericCollection<T, U> collect, int pos)
|
||||
{
|
||||
T? obj = collect._collection[pos];
|
||||
|
||||
if (obj != null)
|
||||
try
|
||||
{
|
||||
return collect._collection.Remove(pos);
|
||||
}
|
||||
|
||||
return false;
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -129,7 +129,7 @@ namespace AccordionBus
|
||||
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалидная операция, нет данных для сохранения!");
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
@ -149,17 +149,21 @@ namespace AccordionBus
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден!");
|
||||
}
|
||||
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0 || !line.StartsWith("BusStorage"))
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
// Если строка пустая
|
||||
// Или если нет записи "BusStorage", то это не те данные
|
||||
return false;
|
||||
throw new IOException("Нет данных для загрузки!");
|
||||
}
|
||||
if (!line.StartsWith("BusStorage"))
|
||||
{
|
||||
// Если нет записи "BusStorage", то это не те данные
|
||||
throw new FileFormatException("Неверный формат данных!");
|
||||
}
|
||||
|
||||
_busStorages.Clear();
|
||||
@ -182,7 +186,7 @@ namespace AccordionBus
|
||||
{
|
||||
if (collection + bus == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Ошибка добавления в коллекцию!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
19
AccordionBus/AccordionBus/BusNotFoundException.cs
Normal file
19
AccordionBus/AccordionBus/BusNotFoundException.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 AccordionBus.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public 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 context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace AccordionBus
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,34 @@ namespace AccordionBus
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new BusCollectionForm());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<BusCollectionForm>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Íàñòðîéêà ëîããåðà
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<BusCollectionForm>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AccordionBus.Exceptions;
|
||||
|
||||
namespace AccordionBus.Generics
|
||||
{
|
||||
@ -55,6 +56,11 @@ namespace AccordionBus.Generics
|
||||
/// <returns></returns>
|
||||
public int Insert(T bus, int position)
|
||||
{
|
||||
if (_places.Count >= _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
|
||||
// Проверка позиции
|
||||
if (position < 0 || position >= _maxCount)
|
||||
{
|
||||
@ -73,6 +79,11 @@ namespace AccordionBus.Generics
|
||||
/// <returns></returns>
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position >= Count && position < _maxCount)
|
||||
{
|
||||
throw new BusNotFoundException(position);
|
||||
}
|
||||
|
||||
// Проверка позиции
|
||||
if (position < 0 || position >= _maxCount)
|
||||
{
|
||||
|
19
AccordionBus/AccordionBus/StorageOverflowException.cs
Normal file
19
AccordionBus/AccordionBus/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 AccordionBus.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public 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
AccordionBus/AccordionBus/appSettings.json
Normal file
20
AccordionBus/AccordionBus/appSettings.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"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": "AccordionBus"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user