Лабораторная работа №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>
protected readonly int _pictureHeight;
/// <summary>
/// Максимальное количество мест
/// </summary>
protected int _maxCount;
/// <summary>
/// Коллекция грузовиков
/// </summary>
@ -35,7 +40,19 @@ public abstract class AbstractCompany
/// <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>
/// Конструктор

View File

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

View File

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

View File

@ -1,4 +1,5 @@
using GasolineTanker.Drawnings;
using GasolineTanker.Exceptions;
using System.Text;
namespace GasolineTanker.CollectionGenericObjects;
@ -53,7 +54,7 @@ public class StorageCollection<T>
{
if (_storages.ContainsKey(name) || name == null)
{
return;
throw new Exception("Неверное имя коллекции");
}
if (collectionType == CollectionType.Massive)
{
@ -98,12 +99,11 @@ public class StorageCollection<T>
/// Сохранение информации по грузовикам в хранилище в файл
/// </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 Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -146,19 +146,17 @@ public class StorageCollection<T>
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
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;
throw new Exception("Файл не существует");
}
string bufferTextFromFile = "";
@ -175,13 +173,12 @@ public class StorageCollection<T>
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
@ -194,11 +191,8 @@ public class StorageCollection<T>
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
@ -207,17 +201,22 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningTanker() is T tanker)
{
if (!collection.Insert(tanker))
try
{
return false;
if (!collection.Insert(tanker))
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
/// <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.Drawnings;
using GasolineTanker.Entities;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace GasolineTanker;
@ -19,13 +21,19 @@ public partial class FormTankerCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTankerCollection()
public FormTankerCollection(ILogger<FormTankerCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -61,14 +69,19 @@ public partial class FormTankerCollection : Form
return;
}
if (_company + tanker)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + tanker)
{
MessageBox.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);
if (_company - pos)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos)
{
MessageBox.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 (_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);
}
}
}
@ -278,13 +299,16 @@ public partial class FormTankerCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
try
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
RerfreshListBoxItems();

View File

@ -8,6 +8,12 @@
<ImplicitUsings>enable</ImplicitUsings>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +29,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace GasolineTanker
{
internal static class Program
@ -11,7 +15,25 @@ namespace GasolineTanker
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>