PIbd-22 Isaeva A.I. Lab work 7 Base #9
19
Airbus/Exceptions/AirbusNotFoundException.cs
Normal file
19
Airbus/Exceptions/AirbusNotFoundException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirbus.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class AirbusNotFoundException : ApplicationException
|
||||
{
|
||||
public AirbusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public AirbusNotFoundException() : base() { }
|
||||
public AirbusNotFoundException(string message) : base(message) { }
|
||||
public AirbusNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected AirbusNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
19
Airbus/Exceptions/StorageOverflowException.cs
Normal file
19
Airbus/Exceptions/StorageOverflowException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirbus.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 context) : base(info, context) { }
|
||||
}
|
||||
}
|
6
Airbus/FormAirbusCollection.Designer.cs
generated
6
Airbus/FormAirbusCollection.Designer.cs
generated
@ -67,7 +67,7 @@
|
||||
pictureBoxCollection.Location = new Point(0, 28);
|
||||
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
|
||||
pictureBoxCollection.Name = "pictureBoxCollection";
|
||||
pictureBoxCollection.Size = new Size(631, 553);
|
||||
pictureBoxCollection.Size = new Size(630, 556);
|
||||
pictureBoxCollection.TabIndex = 1;
|
||||
pictureBoxCollection.TabStop = false;
|
||||
//
|
||||
@ -184,14 +184,14 @@
|
||||
// SaveToolStripMenuItem
|
||||
//
|
||||
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
|
||||
SaveToolStripMenuItem.Size = new Size(224, 26);
|
||||
SaveToolStripMenuItem.Size = new Size(166, 26);
|
||||
SaveToolStripMenuItem.Text = "Сохранить";
|
||||
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// LoadToolStripMenuItem
|
||||
//
|
||||
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
|
||||
LoadToolStripMenuItem.Size = new Size(224, 26);
|
||||
LoadToolStripMenuItem.Size = new Size(166, 26);
|
||||
LoadToolStripMenuItem.Text = "Загрузить";
|
||||
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
|
@ -7,9 +7,11 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAirbus.Generics;
|
||||
using ProjectAirbus.Drawnings;
|
||||
using ProjectAirbus.MovementStrategy;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace ProjectAirbus
|
||||
{
|
||||
@ -17,11 +19,14 @@ namespace ProjectAirbus
|
||||
{
|
||||
// Набор объектов
|
||||
private readonly AirbusGenericStorage _storage;
|
||||
// Логер
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public FormAirbusCollection()
|
||||
public FormAirbusCollection(ILogger<FormAirbusCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new AirbusGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// Обработка нажатия "Сохранение"
|
||||
@ -29,13 +34,16 @@ namespace ProjectAirbus
|
||||
{
|
||||
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 (InvalidOperationException ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -45,15 +53,16 @@ namespace ProjectAirbus
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
//var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
//pictureBoxCollection.Image = obj.ShowAirbus();
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
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);
|
||||
}
|
||||
}
|
||||
ReloadObjects();
|
||||
@ -89,6 +98,7 @@ namespace ProjectAirbus
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
|
||||
}
|
||||
|
||||
// выбрать набор
|
||||
@ -104,10 +114,12 @@ namespace ProjectAirbus
|
||||
{
|
||||
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);
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удалён набор: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,14 +145,23 @@ namespace ProjectAirbus
|
||||
}
|
||||
// меняем границы после закрытия конфига
|
||||
_airbus.ChangeBordersPicture(Width, Height);
|
||||
if (obj + _airbus != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowAirbus();
|
||||
if (obj + _airbus != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowAirbus();
|
||||
_logger.LogInformation($"Добавлен объект: {_airbus.EntityAirbus.BodyColor}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -160,24 +181,29 @@ namespace ProjectAirbus
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = 0;
|
||||
try
|
||||
{
|
||||
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowAirbus();
|
||||
_logger.LogInformation($"Удалён объект по позиции : {pos}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch
|
||||
catch (FormatException ex)
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
MessageBox.Show("Неверный формат ввода");
|
||||
_logger.LogWarning("Неверный формат ввода");
|
||||
}
|
||||
if (obj - pos)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowAirbus();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -130,6 +130,6 @@
|
||||
<value>462, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>89</value>
|
||||
<value>25</value>
|
||||
</metadata>
|
||||
</root>
|
4
Airbus/FormPlane.Designer.cs
generated
4
Airbus/FormPlane.Designer.cs
generated
@ -1,6 +1,6 @@
|
||||
namespace ProjectAirbus
|
||||
{
|
||||
partial class FormPlane
|
||||
partial class FormAirbus
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
@ -28,7 +28,7 @@
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPlane));
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAirbus));
|
||||
pictureAirBus = new PictureBox();
|
||||
buttonUp = new Button();
|
||||
buttonLeft = new Button();
|
||||
|
@ -4,7 +4,7 @@ using ProjectAirbus.Entities;
|
||||
|
||||
namespace ProjectAirbus
|
||||
{
|
||||
public partial class FormPlane : Form
|
||||
public partial class FormAirbus : Form
|
||||
{
|
||||
private DrawningAirbus? _drawningAirbus;
|
||||
private AbstractStrategy? _abstractStrategy;
|
||||
@ -12,7 +12,7 @@ namespace ProjectAirbus
|
||||
// Выбранный автомобиль
|
||||
public DrawningAirbus? SelectedAirbus { get; private set; }
|
||||
|
||||
public FormPlane()
|
||||
public FormAirbus()
|
||||
{
|
||||
InitializeComponent();
|
||||
_abstractStrategy = null;
|
||||
|
@ -12,11 +12,12 @@ namespace ProjectAirbus.Generics
|
||||
where T : DrawningAirbus
|
||||
where U : IMoveableObject
|
||||
{
|
||||
public int count => _collection.Count;
|
||||
private readonly int _pictureWidth;
|
||||
private readonly int _pictureHeight;
|
||||
// Размер занимаемого места
|
||||
private readonly int _placeSizeWidth = 89;
|
||||
private readonly int _placeSizeHeight = 34;
|
||||
// Размер занимаемого места 89х34
|
||||
private readonly int _placeSizeWidth = 189;
|
||||
private readonly int _placeSizeHeight = 134;
|
||||
// коллекция
|
||||
private readonly SetGeneric<T> _collection;
|
||||
|
||||
@ -29,6 +30,7 @@ namespace ProjectAirbus.Generics
|
||||
|
||||
_collection = new SetGeneric<T>(width * height);
|
||||
}
|
||||
|
||||
public static int operator +(AirbusGenericCollection<T, U> collect, T? obj)
|
||||
{
|
||||
if (obj != null)
|
||||
|
@ -77,7 +77,9 @@ namespace ProjectAirbus.Generics
|
||||
public bool SaveData(string filename)
|
||||
{
|
||||
if (_airbusStorages.Count == 0)
|
||||
return false;
|
||||
{
|
||||
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -92,6 +94,10 @@ namespace ProjectAirbus.Generics
|
||||
{
|
||||
StringBuilder records = new();
|
||||
|
||||
if (record.Value.count <= 0)
|
||||
{
|
||||
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
foreach (DrawningAirbus? elem in record.Value.GetAirbus)
|
||||
{
|
||||
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
||||
@ -99,7 +105,6 @@ namespace ProjectAirbus.Generics
|
||||
sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -108,7 +113,7 @@ namespace ProjectAirbus.Generics
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException($"Файл {filename} не найден");
|
||||
}
|
||||
|
||||
using (StreamReader sr = File.OpenText(filename))
|
||||
@ -118,21 +123,31 @@ namespace ProjectAirbus.Generics
|
||||
// пустая или не те данные
|
||||
if (curLine == null || curLine.Length == 0 || !curLine.StartsWith("AirbusStorage"))
|
||||
{
|
||||
return false;
|
||||
throw new ArgumentException("Неверный формат данных");
|
||||
}
|
||||
// очищаем
|
||||
_airbusStorages.Clear();
|
||||
|
||||
// загружаем данные построчно
|
||||
curLine = sr.ReadLine();
|
||||
if (curLine == null || curLine.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("Нет данных");
|
||||
}
|
||||
while (curLine != null)
|
||||
{
|
||||
// загружаем запись
|
||||
if (!curLine.Contains(_separatorRecords))
|
||||
{
|
||||
throw new ArgumentException("Коллекция пуста");
|
||||
}
|
||||
|
||||
string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
// загружаем набор
|
||||
AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> collection = new(_pictureWidth, _pictureHeight);
|
||||
// record[0] - название набора, record[1] - куча объектов
|
||||
|
||||
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (string elem in set)
|
||||
@ -143,7 +158,7 @@ namespace ProjectAirbus.Generics
|
||||
{
|
||||
if (collection + airbus == -1)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Невалидная операция, ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -25,25 +26,22 @@ namespace ProjectAirbus.Generics
|
||||
// Добавление объекта в начало набора
|
||||
public int Insert(T airbus)
|
||||
{
|
||||
if (_places.Count >= _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
_places.Insert(0, airbus);
|
||||
return 0;
|
||||
return Insert(airbus, 0);
|
||||
}
|
||||
|
||||
// Добавление объекта в набор на конкретную позицию
|
||||
public bool Insert(T airbus, int position)
|
||||
public int Insert(T airbus, int position)
|
||||
{
|
||||
if (Count >= _maxCount || position < 0 || position >= Count)
|
||||
if (Count >= _maxCount)
|
||||
{
|
||||
return false;
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
if (position < 0 || position >= _maxCount)
|
||||
{
|
||||
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
|
||||
}
|
||||
|
||||
_places.Insert(position, airbus);
|
||||
return true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Удаление объекта из набора с конкретной позиции
|
||||
@ -51,10 +49,9 @@ namespace ProjectAirbus.Generics
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return false;
|
||||
throw new AirbusNotFoundException(position);
|
||||
}
|
||||
_places.RemoveAt(position);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAirbus
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,30 @@ namespace ProjectAirbus
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormAirbusCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormAirbusCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormAirbusCollection>().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}serilog.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -23,4 +23,24 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" 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.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties /></VisualStudio></ProjectExtensions>
|
||||
|
||||
</Project>
|
20
Airbus/serilog.json
Normal file
20
Airbus/serilog.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/carlog.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "ProjectAirbus"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user