Готовая 7 лабораторная
This commit is contained in:
parent
0e051a1904
commit
65cd145a4e
20
RoadTrain/AppSettings.json
Normal file
20
RoadTrain/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": "RoadTrain"
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
using RoadTrain.DrawningObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using RoadTrain.DrawningObjects;
|
||||
using RoadTrain.Generics;
|
||||
using RoadTrain;
|
||||
using RoadTrain.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -16,11 +18,13 @@ namespace RoadTrain
|
||||
public partial class FormTrainCollection : Form
|
||||
{
|
||||
private readonly RoadTrainGenericStorage _storage;
|
||||
public FormTrainCollection()
|
||||
private readonly ILogger _logger;
|
||||
public FormTrainCollection(ILogger<FormTrainCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new RoadTrainGenericStorage(pictureBoxCollection.Width,
|
||||
pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
@ -57,14 +61,17 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (obj + train != -1)
|
||||
try
|
||||
{
|
||||
_ = obj + train;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowTrains();
|
||||
_logger.LogInformation($"Обьект добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Обьект не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
private void ButtonAddTrain_Click(object sender, EventArgs e)
|
||||
@ -92,17 +99,25 @@ pictureBoxCollection.Height);
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(InputTextBox.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowTrains();
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowTrains();
|
||||
_logger.LogInformation($"Обьект удален из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить обьект");
|
||||
_logger.LogWarning($"Обьект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (TrainNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Обьект не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
||||
@ -128,26 +143,29 @@ pictureBoxCollection.Height);
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Добавление набора неуспешно Не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
|
||||
}
|
||||
|
||||
private void ButtonDelObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Удаление набора неуспешно");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
|
||||
?? string.Empty);
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {name}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void ListBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -160,15 +178,16 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTrains()
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранено: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не удалось");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -177,16 +196,17 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTrains()
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
|
||||
MessageBox.Show($"Не сохранено: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не удалось");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,11 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using NLog.Extensions.Logging;
|
||||
using System;
|
||||
|
||||
|
||||
namespace RoadTrain
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +19,28 @@ namespace RoadTrain
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormTrainCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormTrainCollection>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,17 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -75,10 +75,7 @@ namespace RoadTrain.Generics
|
||||
pos)
|
||||
{
|
||||
T? obj = collect._collection[pos];
|
||||
if (obj != null)
|
||||
{
|
||||
collect._collection.Remove(pos);
|
||||
}
|
||||
collect._collection.Remove(pos);
|
||||
return obj;
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -93,7 +93,7 @@ namespace RoadTrain.Generics
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -112,7 +112,7 @@ namespace RoadTrain.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new ArgumentException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
string dataStr = data.ToString();
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
@ -120,29 +120,28 @@ namespace RoadTrain.Generics
|
||||
writer.WriteLine("TrainStorage");
|
||||
writer.WriteLine(dataStr);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string checker = reader.ReadLine();
|
||||
if (checker == null)
|
||||
{
|
||||
return false;
|
||||
throw new ArgumentException("Нет данных для загрузки");
|
||||
}
|
||||
if (!checker.StartsWith("TrainStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new InvalidDataException("Неверный формат данных");
|
||||
}
|
||||
_trainStorages.Clear();
|
||||
string strs;
|
||||
@ -150,7 +149,7 @@ namespace RoadTrain.Generics
|
||||
while ((strs = reader.ReadLine()) != null)
|
||||
{
|
||||
if (strs == null && firstinit)
|
||||
return false;
|
||||
throw new ArgumentException("Нет данных для загрузки");
|
||||
if (strs == null)
|
||||
break;
|
||||
if (strs == String.Empty)
|
||||
@ -166,14 +165,24 @@ namespace RoadTrain.Generics
|
||||
{
|
||||
if (collection + train == -1)
|
||||
{
|
||||
return false;
|
||||
try
|
||||
{
|
||||
_ = collection + train;
|
||||
}
|
||||
catch (TrainNotFoundException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
catch (StorageOverflowException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
_trainStorages.Add(name, collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using RoadTrain;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -44,10 +45,10 @@ namespace RoadTrain.Generics
|
||||
public int Insert(T train, int position)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount)
|
||||
return -1;
|
||||
throw new StorageOverflowException("Невалидная операция");
|
||||
|
||||
if (Count >= _maxCount)
|
||||
return -1;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
_places.Insert(position, train);
|
||||
return position;
|
||||
}
|
||||
@ -58,7 +59,14 @@ namespace RoadTrain.Generics
|
||||
/// <returns></returns>
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if ((position < 0) || (position > _maxCount)) return false;
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new TrainNotFoundException("Невалидная операция");
|
||||
}
|
||||
if (_places[position] == null)
|
||||
{
|
||||
throw new TrainNotFoundException(position);
|
||||
}
|
||||
_places[position] = null;
|
||||
return true;
|
||||
}
|
||||
@ -71,7 +79,7 @@ namespace RoadTrain.Generics
|
||||
{
|
||||
get
|
||||
{
|
||||
if ((position < 0) || (position > _maxCount)) return null;
|
||||
if ((position < 0) || (position >= Count)) return null;
|
||||
return _places[position];
|
||||
}
|
||||
set
|
||||
|
21
RoadTrain/StorageOverflowException.cs
Normal file
21
RoadTrain/StorageOverflowException.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RoadTrain
|
||||
{
|
||||
[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) { }
|
||||
}
|
||||
}
|
22
RoadTrain/TrainNotFoundException.cs
Normal file
22
RoadTrain/TrainNotFoundException.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RoadTrain
|
||||
{
|
||||
[Serializable]
|
||||
internal class TrainNotFoundException : ApplicationException
|
||||
{
|
||||
public TrainNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public TrainNotFoundException() : base() { }
|
||||
public TrainNotFoundException(string message) : base(message) { }
|
||||
public TrainNotFoundException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected TrainNotFoundException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user