Lab7
This commit is contained in:
parent
123978bbf8
commit
13cdd03f7e
19
Lab/CarNotFoundException.cs
Normal file
19
Lab/CarNotFoundException.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 Lab
|
||||||
|
{
|
||||||
|
[Serializable] internal class CarNotFoundException : ApplicationException
|
||||||
|
{
|
||||||
|
public CarNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||||
|
public CarNotFoundException() : base() { }
|
||||||
|
public CarNotFoundException(string message) : base(message) { }
|
||||||
|
public CarNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||||
|
protected CarNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -47,7 +47,7 @@ namespace Lab.Generics
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public bool SaveData(string filename)
|
public void SaveData(string filename)
|
||||||
{
|
{
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
@ -66,37 +66,36 @@ namespace Lab.Generics
|
|||||||
}
|
}
|
||||||
if (data.Length == 0)
|
if (data.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||||
}
|
}
|
||||||
using (StreamWriter writer = new StreamWriter(filename))
|
using (StreamWriter writer = new StreamWriter(filename))
|
||||||
{
|
{
|
||||||
writer.WriteLine("CarStorage");
|
writer.WriteLine("CarStorage");
|
||||||
writer.Write(data.ToString());
|
writer.Write(data.ToString());
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool LoadData(string filename)
|
public void LoadData(string filename)
|
||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Файл не найден");
|
||||||
}
|
}
|
||||||
using (StreamReader reader = new StreamReader(filename))
|
using (StreamReader reader = new StreamReader(filename))
|
||||||
{
|
{
|
||||||
string checker = reader.ReadLine();
|
string checker = reader.ReadLine();
|
||||||
if (checker == null)
|
if (checker == null)
|
||||||
return false;
|
throw new Exception("Нет данных для загрузки");
|
||||||
if (!checker.StartsWith("CarStorage"))
|
if (!checker.StartsWith("CarStorage"))
|
||||||
return false;
|
throw new Exception("Неверный формат ввода");
|
||||||
_carStorages.Clear();
|
_carStorages.Clear();
|
||||||
string strs;
|
string strs;
|
||||||
bool firstinit = true;
|
bool firstinit = true;
|
||||||
while ((strs = reader.ReadLine()) != null)
|
while ((strs = reader.ReadLine()) != null)
|
||||||
{
|
{
|
||||||
if (strs == null && firstinit)
|
if (strs == null && firstinit)
|
||||||
return false;
|
throw new Exception("Нет данных для загрузки");
|
||||||
if (strs == null )
|
if (strs == null )
|
||||||
break;
|
break;
|
||||||
firstinit = false;
|
firstinit = false;
|
||||||
@ -108,17 +107,19 @@ namespace Lab.Generics
|
|||||||
data?.CreateDrawTanker(_separatorForObject, _pictureWidth, _pictureHeight);
|
data?.CreateDrawTanker(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||||
if (car != null)
|
if (car != null)
|
||||||
{
|
{
|
||||||
if (!(collection + car))
|
try {_ = collection + car; }
|
||||||
|
catch (CarNotFoundException e)
|
||||||
{
|
{
|
||||||
return false;
|
throw e;
|
||||||
|
}
|
||||||
|
catch (StorageOverflowException e)
|
||||||
|
{
|
||||||
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
_carStorages.Add(name, collection);
|
_carStorages.Add(name, collection);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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 Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace Lab
|
namespace Lab
|
||||||
{
|
{
|
||||||
public partial class CollectionsFrame : Form
|
public partial class CollectionsFrame : Form
|
||||||
{
|
{
|
||||||
private readonly CarsGenericStorage _storage;
|
private readonly CarsGenericStorage _storage;
|
||||||
public CollectionsFrame()
|
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
public CollectionsFrame(ILogger<CollectionsFrame> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storage = new CarsGenericStorage(DrawTank.Width, DrawTank.Height);
|
_storage = new CarsGenericStorage(DrawTank.Width, DrawTank.Height);
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
private void ReloadObjects()
|
private void ReloadObjects()
|
||||||
{
|
{
|
||||||
@ -46,10 +50,12 @@ namespace Lab
|
|||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning("Пустое название набора");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_storage.AddSet(SetTextBox.Text);
|
_storage.AddSet(SetTextBox.Text);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Добавлен набор: {SetTextBox.Text}");
|
||||||
}
|
}
|
||||||
private void ListBoxObjects_SelectedIndexChanged(object sender,
|
private void ListBoxObjects_SelectedIndexChanged(object sender,
|
||||||
EventArgs e)
|
EventArgs e)
|
||||||
@ -61,14 +67,17 @@ namespace Lab
|
|||||||
{
|
{
|
||||||
if (CollectionListBox.SelectedIndex == -1)
|
if (CollectionListBox.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление невыбранного набора");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show($"Удалить объект {CollectionListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
|
string name = CollectionListBox.SelectedItem.ToString() ?? string.Empty;
|
||||||
|
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo,
|
||||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||||
{
|
{
|
||||||
_storage.DelSet(CollectionListBox.SelectedItem.ToString()
|
_storage.DelSet(CollectionListBox.SelectedItem.ToString()
|
||||||
?? string.Empty);
|
?? string.Empty);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Удален набор: {name}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,16 +87,21 @@ namespace Lab
|
|||||||
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
|
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Добавление пустого объекта");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (obj + tanker)
|
try
|
||||||
{
|
{
|
||||||
|
_ = obj + tanker;
|
||||||
|
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
DrawTank.Image = obj.ShowCars();
|
DrawTank.Image = obj.ShowCars();
|
||||||
|
_logger.LogInformation($"Добавлен объект в набор {CollectionListBox.SelectedItem.ToString()}");
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogWarning($"{ex.Message} в наборе {CollectionListBox.SelectedItem.ToString()}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void ButtonAddCar_Click(object sender, EventArgs e)
|
private void ButtonAddCar_Click(object sender, EventArgs e)
|
||||||
@ -104,6 +118,7 @@ namespace Lab
|
|||||||
{
|
{
|
||||||
if (CollectionListBox.SelectedIndex == -1)
|
if (CollectionListBox.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var obj = _storage[CollectionListBox.SelectedItem.ToString() ??
|
var obj = _storage[CollectionListBox.SelectedItem.ToString() ??
|
||||||
@ -118,14 +133,24 @@ namespace Lab
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(CarTextBox.Text);
|
int pos = Convert.ToInt32(CarTextBox.Text);
|
||||||
if (obj - pos != null)
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
if (obj - pos != null)
|
||||||
DrawTank.Image = obj.ShowCars();
|
{
|
||||||
|
MessageBox.Show("Объект удален");
|
||||||
|
DrawTank.Image = obj.ShowCars();
|
||||||
|
_logger.LogInformation($"Удален объект из набора {CollectionListBox.SelectedItem.ToString()}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
_logger.LogWarning($"Не удалось удалить объект из набора {CollectionListBox.SelectedItem.ToString()}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
catch (CarNotFoundException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show(ex.Message);
|
||||||
|
_logger.LogWarning($"{ex.Message} из набора {CollectionListBox.SelectedItem.ToString()}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void ButtonRefreshCollection_Click(object sender, EventArgs
|
private void ButtonRefreshCollection_Click(object sender, EventArgs
|
||||||
@ -147,13 +172,16 @@ namespace Lab
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storage.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storage.SaveData(saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
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}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -162,14 +190,17 @@ namespace Lab
|
|||||||
|
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storage.LoadData(openFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storage.LoadData(openFileDialog.FileName);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
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}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,20 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<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.Console" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||||
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Sinks.Console" Version="5.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>
|
||||||
|
@ -1,26 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<OutputType>WinExe</OutputType>
|
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<UseWindowsForms>true</UseWindowsForms>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
|
||||||
<DesignTime>True</DesignTime>
|
|
||||||
<AutoGen>True</AutoGen>
|
|
||||||
<DependentUpon>Resources.resx</DependentUpon>
|
|
||||||
</Compile>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<EmbeddedResource Update="Properties\Resources.resx">
|
|
||||||
<Generator>ResXFileCodeGenerator</Generator>
|
|
||||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
|
||||||
</EmbeddedResource>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
@ -1,17 +1,42 @@
|
|||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Serilog;
|
||||||
namespace Lab
|
namespace Lab
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// The main entry point for the application.
|
|
||||||
/// </summary>
|
|
||||||
[STAThread]
|
[STAThread]
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
// To customize application configuration such as set high DPI settings or default font,
|
|
||||||
// see https://aka.ms/applicationconfiguration.
|
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new CollectionsFrame());
|
var services = new ServiceCollection();
|
||||||
|
ConfigureServices(services);
|
||||||
|
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||||
|
{
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<CollectionsFrame>());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<CollectionsFrame>().AddLogging(option =>
|
||||||
|
{
|
||||||
|
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||||
|
string pathNeed = "";
|
||||||
|
for (int i = 0; i < path.Length - 3; i++)
|
||||||
|
{
|
||||||
|
pathNeed += path[i] + "\\";
|
||||||
|
}
|
||||||
|
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
|
||||||
|
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||||
|
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddSerilog(logger);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -26,20 +26,18 @@ namespace Lab.Generics
|
|||||||
public bool Insert(T car, int position)
|
public bool Insert(T car, int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= _maxCount)
|
if (position < 0 || position >= _maxCount)
|
||||||
return false;
|
throw new CarNotFoundException(position);
|
||||||
|
|
||||||
if (Count >= _maxCount)
|
if (Count >= _maxCount)
|
||||||
return false;
|
throw new StorageOverflowException(position);
|
||||||
_places.Insert(0, car);
|
_places.Insert(0, car);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Remove(int position)
|
public bool Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position > _maxCount)
|
if (position < 0 || position > _maxCount || position >= Count)
|
||||||
return false;
|
throw new CarNotFoundException(position);
|
||||||
if (position >= Count)
|
|
||||||
return false;
|
|
||||||
_places.RemoveAt(position);
|
_places.RemoveAt(position);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
18
Lab/StorageOverflowException.cs
Normal file
18
Lab/StorageOverflowException.cs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Lab
|
||||||
|
{
|
||||||
|
[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) { }
|
||||||
|
}
|
||||||
|
}
|
20
Lab/appsettings.json
Normal file
20
Lab/appsettings.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"Serilog": {
|
||||||
|
"Using": [ "Serilog.Sinks.File" ],
|
||||||
|
"MinimumLevel": "Information",
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/log_.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "GasolineTanker"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user