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

This commit is contained in:
ShuryginDima 2024-05-20 14:06:46 +03:00
parent 89b32379e6
commit bf12e1a9bf
17 changed files with 332 additions and 65 deletions

View File

@ -1,4 +1,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
@ -103,10 +104,17 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception)
{
continue;
}
}
return bitmap;
}

View File

@ -1,4 +1,6 @@
namespace ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -42,35 +44,42 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position < 0 || position > _collection.Count)
try
{
return null;
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public int Insert(T obj)
{
return Insert(obj, _collection.Count);
}
public int Insert(T obj, int position)
{
if (_maxCount == _collection.Count || position < 0 || position > _collection.Count)
{
return -1;
}
if (position > MaxCount) throw new CollectionOverflowException(position);
if (obj == null) throw new ArgumentNullException(nameof(obj));
_collection.Insert(position, obj);
return _collection.Count;
}
public T? Remove(int position)
{
if (position < 0 || position > _collection.Count)
try
{
return null;
}
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public IEnumerable<T?> GetItems()
{

View File

@ -1,4 +1,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
@ -51,13 +52,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
try
{
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
else
catch (IndexOutOfRangeException)
{
return null;
throw new PositionOutOfCollectionException(position);
}
}
@ -94,23 +96,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= _collection.Count())
{
return null;
}
if (_collection[position] != null)
try
{
T obj = _collection[position];
if (obj == null) throw new ObjectNotFoundException(position);
_collection[position] = null;
return obj;
}
return null;
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public IEnumerable<T?> GetItems()

View File

@ -24,6 +24,7 @@ public class PlaneSharingService : AbstractCompany
protected override void DrawBackgound(Graphics g)
{
Pen pen = new Pen(Color.Brown);
int max_count = 0;
int x = 1, y = 0;
while (y + _placeSizeHeight <= _pictureHeight)
{
@ -31,6 +32,7 @@ public class PlaneSharingService : AbstractCompany
while (x + _placeSizeWidth <= _pictureWidth)
{
count++;
max_count++;
g.DrawLine(pen, x, y, x + _placeSizeWidth, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight);
g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight);
@ -43,6 +45,7 @@ public class PlaneSharingService : AbstractCompany
y += _placeSizeHeight + 5;
countRow++;
}
_collection.MaxCount = max_count;
}
protected override void SetObjectsPosition()
@ -53,6 +56,8 @@ public class PlaneSharingService : AbstractCompany
}
int row = countRow, col = 1;
for (int i = 0; i < _collection?.Count; i++, col++)
{
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5);
@ -62,5 +67,10 @@ public class PlaneSharingService : AbstractCompany
row--;
}
}
catch (Exception)
{
continue;
}
}
}
}

View File

@ -1,5 +1,6 @@
using ProjectSeaplane.Drawnings;
using System.Text;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
@ -105,8 +106,7 @@ public class StorageCollection<T>
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -115,7 +115,7 @@ public class StorageCollection<T>
if (_storage.Count == 0)
{
return false;
throw new NoCollectionException("В хранилище отсутствуют коллекции для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
@ -133,26 +133,31 @@ public class StorageCollection<T>
writer.Write(data + _separatorItems);
}
}
}
writer.WriteLine();
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </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;
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader reader = new StreamReader(filename))
{
string line = reader.ReadLine();
if (line == null || !line.Equals(_collectionKey))
if (line == null)
{
return false;
throw new FileIsEmptyException(filename);
}
if (!line.Equals(_collectionKey))
{
throw new FileHasWrongDataException(filename);
}
_storage.Clear();
@ -169,7 +174,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new NullCollectionException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -179,17 +184,21 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningPlane() is T plane)
{
if (collection.Insert(plane) == -1)
try
{
return false;
collection.Insert(plane);
}
catch (Exception ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storage.Add(record[0], collection);
line = reader.ReadLine();
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectSeaplane.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,19 @@
using System.Runtime.Serialization;
namespace ProjectSeaplane.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
internal class FileHasWrongDataException : ApplicationException
{
public FileHasWrongDataException() : base() { }
public FileHasWrongDataException(string message) : base("Файл имеет неверные данные: " + message) { }
public FileHasWrongDataException(string message, Exception exception) : base(message, exception) { }
public FileHasWrongDataException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

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

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace ProjectSeaplane.Exceptions;
[Serializable]
internal class NoCollectionException : ApplicationException
{
public NoCollectionException() : base() { }
public NoCollectionException(string message) : base(message) { }
public NoCollectionException(string message, Exception exception) : base(message, exception) { }
public NoCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace ProjectSeaplane.Exceptions;
[Serializable]
internal class NullCollectionException : ApplicationException
{
public NullCollectionException() : base() { }
public NullCollectionException(string message) : base(message) { }
public NullCollectionException(string message, Exception exception) : base(message, exception) { }
public NullCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,22 @@
using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.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,16 @@
using System.Runtime.Serialization;
namespace ProjectSeaplane.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,4 +1,6 @@
using ProjectSeaplane.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using System.Security.Cryptography;
using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawnings;
namespace ProjectSeaplane;
@ -18,13 +20,19 @@ public partial class FormPlaneCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -53,21 +61,25 @@ public partial class FormPlaneCollection : Form
/// Добавление самолёта в коллекцию
/// </summary>
/// <param name="plane"></param>
private void SetPlane(DrawningPlane? plane)
private void SetPlane(DrawningPlane plane)
{
if (_company == null || plane == null)
if (_company == null)
{
return;
}
try
{
if ((_company + plane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект: {entity}", plane.GetDataForSave());
pictureBox.Image = _company.Show();
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Объект не был добавлен");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -89,14 +101,17 @@ public partial class FormPlaneCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if ((_company - pos) != null)
try
{
DrawningPlane plane = _company - pos;
_logger.LogInformation("Объект по позиции {pos} удаден", pos);
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -174,6 +189,8 @@ public partial class FormPlaneCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType);
}
/// <summary>
@ -192,6 +209,7 @@ public partial class FormPlaneCollection : Form
{
return;
}
_logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString());
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty);
RefreshListBoxItems();
}
@ -230,6 +248,7 @@ public partial class FormPlaneCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogInformation("Коллекция не проиннициализирована");
return;
}
@ -237,8 +256,10 @@ public partial class FormPlaneCollection : Form
{
case "Хранилище":
_company = new PlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Создана компания типа плейншейринг, коллекция: {CollectionName}", listBoxCollection.SelectedItem);
break;
}
_logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem);
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
@ -252,13 +273,16 @@ public partial class FormPlaneCollection : 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);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -272,15 +296,18 @@ public partial class FormPlaneCollection : Form
{
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(loadFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_storageCollection.LoadData(loadFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка прошла успешно из файла, {filename}", loadFileDialog.FileName);
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogError("Ошибка {Message}", ex.Message);
}
RefreshListBoxItems();
}
}
}

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.File;
using Serilog.Configuration;
using Microsoft.Extensions.Configuration;
namespace ProjectSeaplane
{
internal static class Program
@ -11,7 +19,31 @@ namespace ProjectSeaplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormPlaneCollection());
}
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormPlaneCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("Settings.json")
.Build();
services.AddSingleton<FormPlaneCollection>()
.AddLogging(builder =>
{
builder.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.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.FileExtensions" 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.11" />
<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.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="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/planeLog.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>