Лабораторная работа №7

This commit is contained in:
VladaM 2024-02-21 18:02:03 +04:00
parent fc415a22b3
commit 522a85b337
11 changed files with 222 additions and 56 deletions

View File

@ -27,6 +27,11 @@ public abstract class AbstractCompany
/// </summary> /// </summary>
protected readonly int _pictureHeight; protected readonly int _pictureHeight;
/// <summary>
/// Максимальное количество мест
/// </summary>
protected int _maxCount;
/// <summary> /// <summary>
/// Коллекция грузовиков /// Коллекция грузовиков
/// </summary> /// </summary>
@ -35,7 +40,19 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount
{
get
{
double _divisibleOfWidth = _pictureWidth / _placeSizeWidth;
double _divisibleOfHeight = _pictureHeight / _placeSizeHeight;
double _placesInWidth = Math.Truncate(_divisibleOfWidth);
double _placesInHeight = Math.Truncate(_divisibleOfHeight);
_maxCount = (int)(_placesInWidth * _placesInHeight);
return _maxCount;
}
}
/// <summary> /// <summary>
/// Конструктор /// Конструктор

View File

@ -1,4 +1,5 @@
using GasolineTanker.CollectionGenericObjects; using GasolineTanker.CollectionGenericObjects;
using GasolineTanker.Exceptions;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -46,9 +47,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= _maxCount)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
@ -57,7 +58,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
if (Count == _maxCount) if (Count == _maxCount)
{ {
return false; throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); _collection.Add(obj);
return true; return true;
@ -65,9 +66,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public bool Insert(T obj, int position) public bool Insert(T obj, int position)
{ {
if (Count >= _maxCount || position < 0 || position >= Count) if (Count == _maxCount)
{ {
return false; throw new CollectionOverflowException(Count);
}
if (position < 0 || position >= _maxCount)
{
throw new PositionOutOfCollectionException(position);
} }
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
@ -75,12 +80,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count || _collection[position] == null) if (position < 0 || position >= _maxCount)
{ {
return false; throw new PositionOutOfCollectionException(position);
} }
_collection.RemoveAt(position); _collection.RemoveAt(position);
return true; return true;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,6 @@
namespace GasolineTanker.CollectionGenericObjects; using GasolineTanker.Exceptions;
namespace GasolineTanker.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -48,9 +50,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if(position < 0 || position >= Count) if (position < 0 || position >= _collection.Length)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
@ -69,7 +71,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return true; return true;
} }
} }
return false; throw new CollectionOverflowException(Count);
} }
/// <summary> /// <summary>
@ -78,6 +80,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public bool Insert(T obj, int position) public bool Insert(T obj, int position)
{ {
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -103,14 +110,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
} }
return false; throw new CollectionOverflowException(Count);
} }
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
return false; throw new ObjectNotFoundException(position);
} }
_collection[position] = null; _collection[position] = null;
return true; return true;

View File

@ -1,4 +1,5 @@
using GasolineTanker.Drawnings; using GasolineTanker.Drawnings;
using GasolineTanker.Exceptions;
using System.Text; using System.Text;
namespace GasolineTanker.CollectionGenericObjects; namespace GasolineTanker.CollectionGenericObjects;
@ -53,7 +54,7 @@ public class StorageCollection<T>
{ {
if (_storages.ContainsKey(name) || name == null) if (_storages.ContainsKey(name) || name == null)
{ {
return; throw new Exception("Неверное имя коллекции");
} }
if (collectionType == CollectionType.Massive) if (collectionType == CollectionType.Massive)
{ {
@ -98,12 +99,11 @@ public class StorageCollection<T>
/// Сохранение информации по грузовикам в хранилище в файл /// Сохранение информации по грузовикам в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -146,19 +146,17 @@ public class StorageCollection<T>
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length); fs.Write(info, 0, info.Length);
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по грузовикам в хранилище из файла /// Загрузка информации по грузовикам в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
@ -175,13 +173,12 @@ public class StorageCollection<T>
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!strs[0].Equals(_collectionKey)) if (!strs[0].Equals(_collectionKey))
{ {
//если нет такой записи, то это не те данные throw new Exception("В файле неверные данные");
return false;
} }
_storages.Clear(); _storages.Clear();
@ -194,11 +191,8 @@ public class StorageCollection<T>
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
if (collection == null) throw new Exception("Не удалось определить тип коллекции:" + record[1]);
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -206,18 +200,23 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTanker() is T tanker) if (elem?.CreateDrawningTanker() is T tanker)
{
try
{ {
if (!collection.Insert(tanker)) if (!collection.Insert(tanker))
{ {
return false; throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace GasolineTanker.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,20 @@
using System.Runtime.Serialization;
namespace GasolineTanker.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,20 @@
using System.Runtime.Serialization;
namespace GasolineTanker.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 GasolineTanker.CollectionGenericObjects; using GasolineTanker.CollectionGenericObjects;
using GasolineTanker.Drawnings; using GasolineTanker.Drawnings;
using GasolineTanker.Entities;
using Microsoft.Extensions.Logging;
using System.Windows.Forms; using System.Windows.Forms;
namespace GasolineTanker; namespace GasolineTanker;
@ -19,13 +21,19 @@ public partial class FormTankerCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTankerCollection() public FormTankerCollection(ILogger<FormTankerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -61,14 +69,19 @@ public partial class FormTankerCollection : Form
return; return;
} }
try
{
if (_company + tanker) if (_company + tanker)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {tanker}", tanker.GetDataForSave());
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -90,14 +103,19 @@ public partial class FormTankerCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos) if (_company - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект с индексом: {pos}", pos);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -257,13 +275,16 @@ public partial class FormTankerCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -278,13 +299,16 @@ public partial class FormTankerCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
RerfreshListBoxItems(); RerfreshListBoxItems();

View File

@ -8,6 +8,12 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +29,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace GasolineTanker namespace GasolineTanker
{ {
internal static class Program internal static class Program
@ -11,7 +15,25 @@ namespace GasolineTanker
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTankerCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankerCollection>());
}
/// <summary>
/// Configuration of DI service
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTankerCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

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>