Рабочая 7 лаба

This commit is contained in:
Павел Ладягин 2024-05-14 20:02:13 +04:00
parent 15565fd27b
commit 6bc99aa840
12 changed files with 320 additions and 113 deletions

View File

@ -1,4 +1,5 @@
using ProjectAirplaneWithRadar.Drawnings;
using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@ -80,8 +81,15 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public DrawningAirplane? GetRandomObject()
{
Random rnd = new();
try
{
return _collection?.Get(rnd.Next(GetMaxCount));
}
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary>
/// Вывод всей коллекции
@ -95,10 +103,17 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningAirplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}

View File

@ -1,4 +1,6 @@

using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
/// <summary>
@ -48,33 +50,33 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public T? Get(int position)
{
if (position >= Count || position < 0)
return null;
throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount)
return -1;
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount)
return -1;
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
if (position < 0 || position > Count)
return -1;
throw new PositionOutOfCollectionException(position); ;
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count)
return null;
throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);

View File

@ -1,4 +1,6 @@

using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
/// <summary>
@ -51,7 +53,9 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= Count)
return null;
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
throw new ObjectNotFoundException(position);
return _collection[position];
}
@ -65,13 +69,13 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
return -1;
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -101,18 +105,16 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
temp--;
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= Count)
return null;
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
return null;
}
throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;

View File

@ -1,4 +1,5 @@
using ProjectAirplaneWithRadar.Drawnings;
using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@ -32,6 +33,8 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
int curHeight = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
{
if (_collection.Get(i) != null)
{
@ -51,6 +54,12 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return;
}
}
catch (ObjectNotFoundException)
{
break;
}
}
}
}

View File

@ -1,6 +1,8 @@
using System.IO;
using System.Data;
using System.IO;
using System.Text;
using ProjectAirplaneWithRadar.Drawnings;
using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@ -98,16 +100,17 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if(_storages.Count == 0)
return false;
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
if(File.Exists(filename))
if (File.Exists(filename))
File.Delete(filename);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
using (StreamWriter sw = new(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
@ -136,7 +139,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
sw.Write(_separatorItems);
}
}
return true;
}
}
/// <summary>
@ -144,26 +147,24 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// </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 (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new(filename))
{
using StreamReader sr = new StreamReader(fs);
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new FileFormatException("В файле нет данных");
}
if (!str.Equals(_collectionKey))
{
return false;
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
@ -179,7 +180,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -188,15 +189,21 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
foreach (string elem in set)
{
if (elem?.CreateDrawningAirplane() is T airplane)
{
try
{
if (collection.Insert(airplane) == -1)
return false;
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectAirplaneWithRadar.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectAirplaneWithRadar.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectAirplaneWithRadar.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,5 +1,7 @@
using ProjectAirplaneWithRadar.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAirplaneWithRadar.CollectionGenericObjects;
using ProjectAirplaneWithRadar.Drawnings;
using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar
{
@ -18,13 +20,20 @@ namespace ProjectAirplaneWithRadar
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneCollection()
public FormAirplaneCollection(ILogger<FormAirplaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -54,6 +63,8 @@ namespace ProjectAirplaneWithRadar
/// </summary>
/// <param name="airplane"></param>
private void SetAirplane(DrawningAirplane airplane)
{
try
{
if (_company == null || airplane == null)
{
@ -64,10 +75,13 @@ namespace ProjectAirplaneWithRadar
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", airplane.GetDataForSave());
}
else
}
catch
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
}
}
@ -88,15 +102,25 @@ namespace ProjectAirplaneWithRadar
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удалён объект по позиции {0}", pos);
}
else
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -112,6 +136,8 @@ namespace ProjectAirplaneWithRadar
return;
}
try
{
DrawningAirplane? plane = null;
int counter = 100;
while (plane == null)
@ -135,6 +161,11 @@ namespace ProjectAirplaneWithRadar
};
form.ShowDialog();
}
catch (ObjectNotFoundException)
{
_logger.LogError("Ошибка при передаче объекта на FormAirplaneWithRadar");
}
}
/// <summary>
/// Перерисовка коллекции
@ -161,6 +192,7 @@ namespace ProjectAirplaneWithRadar
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@ -172,6 +204,7 @@ namespace ProjectAirplaneWithRadar
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
}
/// <summary>
@ -193,6 +226,7 @@ namespace ProjectAirplaneWithRadar
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text);
}
/// <summary>
@ -233,6 +267,8 @@ namespace ProjectAirplaneWithRadar
{
case "Хранилище":
_company = new PlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text);
_logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text);
break;
}
@ -249,13 +285,16 @@ namespace ProjectAirplaneWithRadar
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -269,14 +308,17 @@ namespace ProjectAirplaneWithRadar
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirplaneWithRadar
{
internal static class Program
@ -11,7 +16,27 @@ namespace ProjectAirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirplaneCollection());
ServiceCollection services = new();
ConfigureService(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirplaneCollection>());
}
private static void ConfigureService(ServiceCollection services)
{
services
.AddSingleton<FormAirplaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" 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>
@ -23,4 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,24 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}|{Level:u}|{SourceContext}|{Message:lj}{NewLine}{Exception}"
}
}
]
}
}