Готовая 7 лабораторная
This commit is contained in:
parent
6d86c591d1
commit
193940f62c
@ -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" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" 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>
|
||||
|
21
DumpTruck/Exceptions/StorageOverflowException.cs
Normal file
21
DumpTruck/Exceptions/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 DumpTruck.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) { }
|
||||
}
|
||||
}
|
19
DumpTruck/Exceptions/TruckNotFoundException.cs
Normal file
19
DumpTruck/Exceptions/TruckNotFoundException.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 DumpTruck.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class TruckNotFoundException : ApplicationException
|
||||
{
|
||||
public TruckNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
|
||||
public TruckNotFoundException() : base() { }
|
||||
public TruckNotFoundException(string message) : base(message) { }
|
||||
public TruckNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected TruckNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -10,6 +10,8 @@ using System.Windows.Forms;
|
||||
using DumpTruck.Generics;
|
||||
using DumpTruck.DrawingObjects;
|
||||
using DumpTruck.MovementStrategy;
|
||||
using DumpTruck.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DumpTruck
|
||||
{
|
||||
@ -23,13 +25,19 @@ namespace DumpTruck
|
||||
/// </summary>
|
||||
private readonly TrucksGenericStorage _storage;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormTruckCollection()
|
||||
public FormTruckCollection(ILogger<FormTruckCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private void ReloadObjects()
|
||||
@ -66,6 +74,7 @@ namespace DumpTruck
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор набора
|
||||
@ -87,10 +96,13 @@ namespace DumpTruck
|
||||
{
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,23 +117,34 @@ namespace DumpTruck
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (obj + truck != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowTrucks();
|
||||
_logger.LogInformation($"Объект добавлен {truck}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonAddTruck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Не удалось добавить объект: не выбран набор");
|
||||
return;
|
||||
}
|
||||
var formTruckConfig = new FormTruckConfig();
|
||||
@ -133,11 +156,13 @@ namespace DumpTruck
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Не удалось удалить объект: не выбран набор");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Не удалось удалить объект: набор пуст");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
@ -146,16 +171,25 @@ namespace DumpTruck
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
if (obj - pos)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowTrucks();
|
||||
_logger.LogInformation($"Удален объект на позиции: {pos}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (TruckNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonRefreshCollection_Click(object sender, EventArgs e)
|
||||
{
|
||||
@ -179,14 +213,16 @@ namespace DumpTruck
|
||||
{
|
||||
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("Не сохранилось", "Результат",
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
@ -200,16 +236,19 @@ namespace DumpTruck
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBox.Show($"Не загрузилось {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не загрузилось: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using DumpTruck.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -51,7 +52,10 @@ namespace DumpTruck.Generics
|
||||
/// <returns></returns>
|
||||
public int Insert(T truck, int position)
|
||||
{
|
||||
if (position < 0 || position > Count || Count >= _maxCount) return -1;
|
||||
if (position < 0 || position > Count)
|
||||
throw new TruckNotFoundException(position);
|
||||
if (Count >= _maxCount)
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
_places.Insert(position, truck);
|
||||
return position;
|
||||
}
|
||||
@ -62,7 +66,7 @@ namespace DumpTruck.Generics
|
||||
/// <returns></returns>
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) return false;
|
||||
if (position < 0 || position >= Count) throw new TruckNotFoundException(position);
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
|
@ -74,14 +74,10 @@ namespace DumpTruck.Generics
|
||||
/// <param name="collect"></param>
|
||||
/// <param name="pos"></param>
|
||||
/// <returns></returns>
|
||||
public static T? operator -(TrucksGenericCollection<T, U> collect, int pos)
|
||||
public static bool operator -(TrucksGenericCollection<T, U> collect, int pos)
|
||||
{
|
||||
T? obj = collect._collection[pos];
|
||||
if (obj != null)
|
||||
{
|
||||
collect._collection.Remove(pos);
|
||||
}
|
||||
return obj;
|
||||
return collect._collection.Remove(pos);
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта IMoveableObject
|
||||
|
@ -87,7 +87,7 @@ namespace DumpTruck.Generics
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -105,33 +105,32 @@ namespace DumpTruck.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
using StreamWriter sw = new(filename);
|
||||
sw.Write($"TruckStorage{Environment.NewLine}{data}");
|
||||
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 Exception("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (!str.StartsWith("TruckStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Неверный формат данных");
|
||||
}
|
||||
_truckStorages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
@ -143,21 +142,20 @@ namespace DumpTruck.Generics
|
||||
}
|
||||
TrucksGenericCollection < DrawingTruck, DrawningObjectTruck > collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
foreach (string elem in set.Reverse())
|
||||
{
|
||||
DrawingTruck? truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (truck != null)
|
||||
{
|
||||
if (collection + truck == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
_truckStorages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace DumpTruck
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,28 @@ namespace DumpTruck
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormTruckCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormTruckCollection>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
20
DumpTruck/appsettings.json
Normal file
20
DumpTruck/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": "DumpTruck"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user