Седьмая лабораторная работа
This commit is contained in:
parent
d3b63cd45f
commit
f9f2e0f4e8
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
|
||||
namespace projectDoubleDeckerBus.Exceptions
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
|
||||
}
|
@ -6,6 +6,8 @@ using System.Threading.Tasks;
|
||||
using projectDoubleDeckerBus.Drawings;
|
||||
using projectDouble_Decker_Bus.MovementStrategy;
|
||||
using projectDoubleDeckerBus.Generics;
|
||||
using System.Text;
|
||||
using projectDoubleDeckerBus.Exceptions;
|
||||
|
||||
namespace projectDoubleDeckerBus.Generics
|
||||
{
|
||||
@ -55,7 +57,7 @@ namespace projectDoubleDeckerBus.Generics
|
||||
}
|
||||
|
||||
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -74,42 +76,41 @@ namespace projectDoubleDeckerBus.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.WriteLine("BusStorage");
|
||||
writer.Write(data.ToString());
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при
|
||||
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не найден");
|
||||
}
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string checker = reader.ReadLine();
|
||||
if (checker == null)
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
if (!checker.StartsWith("BusStorage"))
|
||||
return false;
|
||||
throw new Exception("Неверный формат ввода");
|
||||
_busStorages.Clear();
|
||||
string strs;
|
||||
bool firstinit = true;
|
||||
while ((strs = reader.ReadLine()) != null)
|
||||
{
|
||||
if (strs == null && firstinit)
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
if (strs == null)
|
||||
break;
|
||||
firstinit = false;
|
||||
@ -121,20 +122,25 @@ namespace projectDoubleDeckerBus.Generics
|
||||
data?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (bus != null)
|
||||
{
|
||||
if (!(collection + bus))
|
||||
try { _ = collection + bus; }
|
||||
catch (BusNotFoundException e)
|
||||
{
|
||||
return false;
|
||||
throw e;
|
||||
}
|
||||
catch (StorageOverflowException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
_busStorages.Add(name, collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -10,6 +10,8 @@ using System.Windows.Forms;
|
||||
using projectDoubleDeckerBus.Drawings;
|
||||
using projectDouble_Decker_Bus.MovementStrategy;
|
||||
using projectDoubleDeckerBus.Generics;
|
||||
using projectDoubleDeckerBus.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace projectDoubleDeckerBus
|
||||
{
|
||||
@ -22,13 +24,17 @@ namespace projectDoubleDeckerBus
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormBusCollection()
|
||||
|
||||
private readonly ILogger _logger;
|
||||
public FormBusCollection(ILogger<FormBusCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new BusesGenericStorage(DrawBus.Width, DrawBus.Height);
|
||||
_logger = logger;
|
||||
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
|
||||
ReloadObjects();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
/// </summary>
|
||||
@ -40,11 +46,13 @@ namespace projectDoubleDeckerBus
|
||||
{
|
||||
listBoxStorages.Items.Add(_storage.Keys[i]);
|
||||
}
|
||||
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
|
||||
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
|
||||
>= listBoxStorages.Items.Count))
|
||||
{
|
||||
listBoxStorages.SelectedIndex = 0;
|
||||
}
|
||||
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
|
||||
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
|
||||
index < listBoxStorages.Items.Count)
|
||||
{
|
||||
listBoxStorages.SelectedIndex = index;
|
||||
}
|
||||
@ -55,16 +63,21 @@ namespace projectDoubleDeckerBus
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Добавление пустого объекта");
|
||||
return;
|
||||
}
|
||||
if (obj + bus)
|
||||
try
|
||||
{
|
||||
_ = obj + bus;
|
||||
|
||||
MessageBox.Show("Объект добавлен");
|
||||
DrawBus.Image = obj.ShowBuses();
|
||||
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -96,36 +109,42 @@ namespace projectDoubleDeckerBus
|
||||
private void ButtonRemoveBus_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
foreach (var it in maskedTextBoxNumber.Text)
|
||||
if (it < '0' || it > '9')
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
try
|
||||
{
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
DrawBus.Image = obj.ShowBuses();
|
||||
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
return;
|
||||
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
if (maskedTextBoxNumber.Text.Length == 0)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
catch (BusNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
DrawBus.Image = obj.ShowBuses();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление рисунка по набору
|
||||
@ -157,6 +176,7 @@ namespace projectDoubleDeckerBus
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -166,7 +186,25 @@ namespace projectDoubleDeckerBus
|
||||
/// <param name="e"></param>
|
||||
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
DrawBus.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
|
||||
DrawBus.Image =
|
||||
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
|
||||
}
|
||||
private void ButtonDelObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление невыбранного набора");
|
||||
return;
|
||||
}
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
|
||||
?? string.Empty);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -174,31 +212,23 @@ namespace projectDoubleDeckerBus
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonDelObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
|
||||
ReloadObjects();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -207,14 +237,17 @@ namespace projectDoubleDeckerBus
|
||||
{
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,44 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System;
|
||||
using System.Windows.Forms;
|
||||
using System.IO;
|
||||
|
||||
namespace projectDoubleDeckerBus
|
||||
{
|
||||
internal static class Program
|
||||
static class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBusCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBusCollection>().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);
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using projectDoubleDeckerBus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -42,19 +43,17 @@ namespace projectDoubleDeckerBus.Generics
|
||||
public bool Insert(T bus, int position)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount)
|
||||
return false;
|
||||
throw new BusNotFoundException(position);
|
||||
|
||||
if (Count >= _maxCount)
|
||||
return false;
|
||||
throw new StorageOverflowException(position);
|
||||
_places.Insert(0, bus);
|
||||
return true;
|
||||
}
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > _maxCount)
|
||||
return false;
|
||||
if (position >= Count)
|
||||
return false;
|
||||
if (position < 0 || position > _maxCount || position >= Count)
|
||||
throw new BusNotFoundException(position);
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
|
@ -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 projectDoubleDeckerBus.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) { }
|
||||
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -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": "projectDoubleDeckerBus"
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,20 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<PackageReference Include="NuGet.Frameworks" Version="6.8.0" />
|
||||
<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>
|
||||
|
Loading…
Reference in New Issue
Block a user