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

This commit is contained in:
ikswi 2024-05-13 17:08:23 +04:00
parent bacf66aad8
commit 696f879bad
16 changed files with 213 additions and 94 deletions

3
11.txt
View File

@ -1,3 +0,0 @@
CollectionsStorage
11|Massive|45|EntityMilitaryAircraft:100:100:Gray;EntityAirFighter:100:100:Gray:True:True:Gray;EntityAirFighter:100:100:Gray:True:True:Gray;
12|Massive|45|EntityAirFighter:100:100:BlueViolet:True:True:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet;EntityAirFighter:100:100:BlueViolet:True:True:BlueViolet;

2
111.txt Normal file
View File

@ -0,0 +1,2 @@
CollectionsStorage
111|Massive|45|EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;

3
12.txt
View File

@ -1,3 +0,0 @@
CollectionsStorage
11|Massive|45|EntityMilitaryAircraft:100:100:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet;EntityMilitaryAircraft:100:100:BlueViolet;
12|Massive|45|EntityMilitaryAircraft:100:100:Yellow;EntityMilitaryAircraft:100:100:Yellow;EntityMilitaryAircraft:100:100:Yellow;

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -95,10 +96,19 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningMilitaryAircraft? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
catch (CollectionOverflowException e)
{ }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -42,11 +43,13 @@ public class Angar : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0)
curWidth--;
@ -55,7 +58,7 @@ public class Angar : AbstractCompany
curWidth = width - 1;
curHeight--;
}
if (curHeight > height)
if (curHeight >= height)
{
return;
}

View File

@ -1,4 +1,4 @@
using ProjectSportCar.Exceptions;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -48,36 +48,36 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount) throw new CollectionOverflowException();
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount) throw new CollectionOverflowException();
if (position < 0 || position > Count) throw new PositionOutOfCollectionException();
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T temp = _collection[position];
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return temp;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}

View File

@ -1,4 +1,4 @@
using ProjectSportCar.Exceptions;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -50,14 +50,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
for (int i = 0; i < Count; i++)
for (int i = 0; i < Count - 3; i++)
{
if (_collection[i] == null)
{
@ -65,47 +65,55 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
throw new CollectionOverflowException();
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null)
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
++temp;
}
temp = position - 1;
while (temp >= 0)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
--temp;
}
throw new CollectionOverflowException();
}
public T? Remove(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position >= Count - 3 || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
T obj = _collection[position];
_collection[position] = null;
return obj;
}

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
using System.Text;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -39,7 +40,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); //вот тут какое-то свойство
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -94,11 +95,11 @@ public class StorageCollection<T>
/// <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 InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -141,10 +142,7 @@ public class StorageCollection<T>
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
@ -152,11 +150,11 @@ public class StorageCollection<T>
/// </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 (StreamReader fs = File.OpenText(filename))
{
@ -164,12 +162,12 @@ public class StorageCollection<T>
if (str == null || str.Length == 0)
{
return false;
throw new FormatException("В файле неверные данные");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new FormatException("В файле неверные данные");
}
_storages.Clear();
@ -190,7 +188,7 @@ public class StorageCollection<T>
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -200,16 +198,22 @@ public class StorageCollection<T>
foreach (string elem in set)
{
if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft)
{
try
{
if (collection.Insert(militaryAircraft) == -1)
{
return false;
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

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

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace ProjectSportCar.Exceptions;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace ProjectSportCar.Exceptions;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции

View File

@ -1,5 +1,7 @@
using ProjectAirFighter.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter;
@ -15,13 +17,19 @@ public partial class FormMilitaryAircraftCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftCollection()
public FormMilitaryAircraftCollection(ILogger<FormMilitaryAircraftCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -58,14 +66,18 @@ public partial class FormMilitaryAircraftCollection : Form
return;
}
if (_company + militaryAircraft != -1)
try
{
var res = _company + militaryAircraft;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -88,14 +100,18 @@ public partial class FormMilitaryAircraftCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -168,9 +184,18 @@ public partial class FormMilitaryAircraftCollection : Form
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
@ -184,6 +209,7 @@ public partial class FormMilitaryAircraftCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -220,6 +246,7 @@ public partial class FormMilitaryAircraftCollection : Form
{
case "Хранилище":
_company = new Angar(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
@ -231,13 +258,16 @@ public partial class FormMilitaryAircraftCollection : Form
{
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);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -246,14 +276,17 @@ public partial class FormMilitaryAircraftCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,5 +1,10 @@
namespace ProjectAirFighter
{
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter;
internal static class Program
{
/// <summary>
@ -11,7 +16,35 @@ namespace ProjectAirFighter
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMilitaryAircraftCollection());
}
var services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService <FormMilitaryAircraftCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMilitaryAircraftCollection>().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}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

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

View File

@ -0,0 +1,2 @@
CollectionsStorage
11|Massive|45|EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;EntityMilitaryAircraft:100:100:Black;