7 лабораторная

This commit is contained in:
sardq 2023-12-03 00:08:41 +04:00
parent 5ad06ae239
commit 0e7878555f
9 changed files with 161 additions and 47 deletions

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace HoistingCrane.Exceptions
{
[Serializable]
internal class CraneNotFoundException : ApplicationException
{
public CraneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public CraneNotFoundException() : base() { }
public CraneNotFoundException(string message) : base(message) { }
public CraneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected CraneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -41,10 +41,6 @@ namespace HoistingCrane.Generics
public static bool operator -(CranesGenericCollection<T, U> collect, int pos) public static bool operator -(CranesGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj == null)
{
return false;
}
return collect?._collection.Remove(pos) ?? false; return collect?._collection.Remove(pos) ?? false;
} }
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject

View File

@ -1,6 +1,7 @@
using HoistingCrane.DrawningObjects; using HoistingCrane.DrawningObjects;
using HoistingCrane.Generics; using HoistingCrane.Generics;
using HoistingCrane.MovementStrategy; using HoistingCrane.MovementStrategy;
using System.IO;
using System.Text; using System.Text;
namespace HoistingCrane namespace HoistingCrane
@ -40,7 +41,7 @@ namespace HoistingCrane
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
using (StreamWriter sw = new StreamWriter(filename)) using (StreamWriter sw = new StreamWriter(filename))
@ -55,7 +56,7 @@ namespace HoistingCrane
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
@ -63,11 +64,11 @@ namespace HoistingCrane
string cheker = reader.ReadLine(); string cheker = reader.ReadLine();
if (cheker == null) if (cheker == null)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!cheker.StartsWith("CarStorage")) if (!cheker.StartsWith("CarStorage"))
{ {
return false; throw new FormatException("Неверный формат данных");
} }
_craneStorages.Clear(); _craneStorages.Clear();
string strs; string strs;
@ -76,11 +77,7 @@ namespace HoistingCrane
{ {
if (strs == null && firstinit) if (strs == null && firstinit)
{ {
return false; throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
return false;
} }
firstinit = false; firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0]; string name = strs.Split(_separatorForKeyValue)[0];
@ -94,7 +91,7 @@ namespace HoistingCrane
int? result = collection + crane; int? result = collection + crane;
if (result == null || result.Value == -1) if (result == null || result.Value == -1)
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }

View File

@ -1,17 +1,22 @@
using HoistingCrane.DrawningObjects; using HoistingCrane.DrawningObjects;
using HoistingCrane.Exceptions;
using HoistingCrane.Generics; using HoistingCrane.Generics;
using HoistingCrane.MovementStrategy; using HoistingCrane.MovementStrategy;
using Microsoft.Extensions.Logging;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq;
namespace HoistingCrane namespace HoistingCrane
{ {
public partial class FormCraneCollection : Form public partial class FormCraneCollection : Form
{ {
private readonly CranesGenericStorage _storage; private readonly CranesGenericStorage _storage;
public FormCraneCollection() private readonly ILogger _logger;
public FormCraneCollection(ILogger<FormCraneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new CranesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new CranesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
{ {
@ -34,15 +39,18 @@ namespace HoistingCrane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл сохранен {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}",
MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
} }
} }
} }
@ -50,16 +58,19 @@ namespace HoistingCrane
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Файл загружен {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
} }
} }
} }
@ -73,6 +84,7 @@ namespace HoistingCrane
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{ {
@ -85,11 +97,13 @@ namespace HoistingCrane
{ {
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
private void ButtonAddCrane_Click(object sender, EventArgs e) private void ButtonAddCrane_Click(object sender, EventArgs e)
@ -101,22 +115,31 @@ namespace HoistingCrane
var formCraneConfig = new FormCraneConfig(); var formCraneConfig = new FormCraneConfig();
formCraneConfig.AddEvent(crane => formCraneConfig.AddEvent(crane =>
{ {
if (listBoxStorages.SelectedIndex != -1) try
{ {
var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]; if (listBoxStorages.SelectedIndex != -1)
if (obj != null)
{ {
if (obj + crane != -1) var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty];
if (obj != null)
{ {
MessageBox.Show("Объект добавлен"); if (obj + crane != 1)
pictureBoxCollection.Image = obj.ShowCars(); {
} MessageBox.Show("Объект добавлен");
else pictureBoxCollection.Image = obj.ShowCars();
{ _logger.LogInformation("Объект добавлен");
MessageBox.Show("Не удалось добавить объект"); }
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
} }
} }
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}); });
formCraneConfig.Show(); formCraneConfig.Show();
} }
@ -133,20 +156,28 @@ namespace HoistingCrane
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try
if (obj - pos)
{ {
MessageBox.Show("Объект удален"); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
pictureBoxCollection.Image = obj.ShowCars(); if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowCars();
_logger.LogInformation("Объект удален");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (CraneNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
} }
} }

View File

@ -8,4 +8,10 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions" Version="2.2.2" />
</ItemGroup>
</Project> </Project>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace HoistingCrane namespace HoistingCrane
{ {
internal static class Program internal static class Program
@ -11,7 +16,32 @@ namespace HoistingCrane
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCraneCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormCraneCollection>());
}
static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCraneCollection>().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);
});
}
} }
} }
} }

View File

@ -1,4 +1,6 @@
namespace HoistingCrane.Generics using HoistingCrane.Exceptions;
namespace HoistingCrane.Generics
{ {
/// Параметризованный набор объектов /// Параметризованный набор объектов
internal class SetGeneric<T> internal class SetGeneric<T>
@ -20,22 +22,26 @@
/// Добавление объекта в набор /// Добавление объекта в набор
public int Insert(T crane) public int Insert(T crane)
{ {
if(crane==null) if (Count >= _maxCount)
return -1; throw new StorageOverflowException(Count);
_places.Insert(0, crane); _places.Insert(0, crane);
return 0; return 0;
} }
public int Insert(T crane, int position) public int Insert(T crane, int position)
{ {
if (position < 0 || position >= _maxCount|| Count >= _maxCount) if (position < 0 || position >= _maxCount || Count >= _maxCount)
return -1; throw new CraneNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
_places.Insert(position, crane); _places.Insert(position, crane);
return position; return position;
} }
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
public bool Remove(int position) public bool Remove(int position)
{ {
if ((position < 0) || (position > _maxCount)|| (_places[position] == null)) return false; if (_places[position] == null)
throw new CraneNotFoundException(position);
if ((position < 0) || (position > _maxCount)) return false;
_places[position] = null; _places[position] = null;
return true; return true;
} }

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace HoistingCrane.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) { }
}
}

View 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": "HoistingCrane"
}
}
}