PIbd-21_Rasubaev S.M._Lab7 #7

Closed
Sergey wants to merge 2 commits from lab_7 into lab_6
9 changed files with 169 additions and 48 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)
{
T? obj = collect._collection[pos];
if (obj == null)
{
return false;
}
return collect?._collection.Remove(pos) ?? false;
}
/// Получение объекта IMoveableObject

View File

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

View File

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

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace HoistingCrane
{
internal static class Program
@ -11,7 +16,32 @@ namespace HoistingCrane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
@ -20,22 +22,29 @@
/// Добавление объекта в набор
public int Insert(T crane)
{
if(crane==null)
return -1;
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
_places.Insert(0, crane);
if (_places.Contains(null)) _places.Remove(null);
return 0;
}
public int Insert(T crane, int position)
{
if (position < 0 || position >= _maxCount|| Count >= _maxCount)
return -1;
if (position < 0 || position >= _maxCount || Count >= _maxCount)
throw new CraneNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
_places.Insert(position, crane);
if(_places.Contains(null)) _places.Remove(null);
return position;
}
/// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
if ((position < 0) || (position > _maxCount)|| (_places[position] == null)) return false;
if (position < 0 || position > _maxCount || position >= Count || _places[position] == null)
throw new CraneNotFoundException(position);
if ((position < 0) || (position > _maxCount)) return false;
_places[position] = null;
return true;
}
@ -50,7 +59,9 @@
{
get
{
if (position < 0 || position > _maxCount)
if (position < 0 || position > Count)
return null;
if (_places.Count <= position)
return null;
return _places[position];
}
@ -58,6 +69,8 @@
{
if (position < 0 || position > _maxCount)
return;
if (_places.Count <= position)
return;
_places[position] = value;
}
}

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"
}
}
}