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

This commit is contained in:
vkobi 2024-05-06 23:50:18 +04:00
parent c241b589f3
commit 1545959a0e
10 changed files with 269 additions and 75 deletions

View File

@ -1,4 +1,6 @@
namespace WarmlyLocomotive.CollectionGenericObjects;
using WarmlyLocomotive.Exceptions;
namespace WarmlyLocomotive.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -19,12 +21,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int MaxCount {
get
public int MaxCount
{
get
{
return _collection.Count;
}
set
set
{
if (value > 0)
{
@ -49,7 +52,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка позиции
if (position >= Count || position < 0)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
@ -59,7 +62,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
// TODO вставка в конец набора
_collection.Add(obj);
@ -70,12 +73,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
// TODO проверка позиции
if (position >= Count || position < 0)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
// TODO вставка по позиции
_collection.Insert(position, obj);
@ -86,7 +89,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка позиции
if (position >= Count || position < 0)
{
return null;
throw new PositionOutOfCollectionException(position);
}
// TODO удаление объекта из списка
T? obj = _collection[position];

View File

@ -1,4 +1,6 @@
namespace WarmlyLocomotive.CollectionGenericObjects;
using WarmlyLocomotive.Exceptions;
namespace WarmlyLocomotive.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -49,8 +51,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position < 0 || position > _collection.Length) {
return null;
if (position < 0 || position > _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
if (position >= Count && _collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
@ -58,14 +65,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj)
{
// TODO вставка в свободное место набора
for (int i=0; i < _collection.Length; i++)
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null) {
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
@ -73,7 +81,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка позиции
if (position > _collection.Length || position < 0)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
@ -102,19 +110,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
// TODO проверка позиции
if (position < 0 || position > _collection.Length) {
return null;
if (position < 0 || position > _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
return null;
throw new ObjectNotFoundException(position);
}
T? tmp = _collection[position];
_collection[position] = null;

View File

@ -1,5 +1,6 @@
using System.Text;
using WarmlyLocomotive.Drawnings;
using WarmlyLocomotive.Exceptions;
namespace WarmlyLocomotive.CollectionGenericObjects;
@ -103,11 +104,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 InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -115,11 +116,9 @@ public class StorageCollection<T>
File.Delete(filename);
}
//StringBuilder sb = new();
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(_collectionKey);
//sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
@ -148,7 +147,6 @@ public class StorageCollection<T>
sw.Write(_separatorItems);
}
}
return true;
}
/// <summary>
@ -156,25 +154,23 @@ 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 reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
throw new InvalidDataException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
return false;
throw new InvalidOperationException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
@ -189,7 +185,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -199,9 +195,16 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningLocomotive() is T locomotive)
{
if (collection.Insert(locomotive) == -1)
try
{
return false;
if (collection.Insert(locomotive) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new ArgumentOutOfRangeException("Коллекция переполнена", ex);
}
}
@ -209,7 +212,7 @@ public class StorageCollection<T>
_storages.Add(record[0], collection);
}
}
return true;
//return true;
}
/// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace WarmlyLocomotive.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,16 @@
using System.Runtime.Serialization;
namespace WarmlyLocomotive.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 WarmlyLocomotive.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 WarmlyLocomotive.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using WarmlyLocomotive.CollectionGenericObjects;
using WarmlyLocomotive.Drawnings;
using WarmlyLocomotive.Exceptions;
namespace WarmlyLocomotive;
@ -18,13 +20,20 @@ public partial class FormLocomotiveCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormLocomotiveCollection()
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -44,7 +53,7 @@ public partial class FormLocomotiveCollection : Form
/// <param name="e"></param>
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
if(_company == null)
if (_company == null)
{
return;
}
@ -64,14 +73,24 @@ public partial class FormLocomotiveCollection : Form
{
return;
}
if (_company + locomotive >= 0)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + locomotive >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + locomotive.GetDataForSave());
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -92,14 +111,24 @@ public partial class FormLocomotiveCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален, позиция: " + pos);
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -113,11 +142,24 @@ public partial class FormLocomotiveCollection : Form
int counter = 100;
while (locomotive == null)
{
locomotive = _company.GetRandomObject();
counter--;
if (counter <= 0)
try
{
break;
locomotive = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
if (locomotive == null)
@ -129,7 +171,6 @@ public partial class FormLocomotiveCollection : Form
SetLocomotive = locomotive
};
form.ShowDialog();
}
/// <summary>
@ -159,18 +200,26 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
collectionType = CollectionType.Massive;
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
//MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
@ -188,14 +237,20 @@ public partial class FormLocomotiveCollection : Form
{
return;
}
ICollectionGenericObjects<DrawningLocomotive>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция удалена: " + listBoxCollection.SelectedItem.ToString());
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@ -251,13 +306,17 @@ public partial class FormLocomotiveCollection : 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);
}
}
}
@ -271,15 +330,17 @@ public partial class FormLocomotiveCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_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);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace WarmlyLocomotive
{
internal static class Program
@ -11,7 +16,33 @@ namespace WarmlyLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormLocomotiveCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormLocomotiveCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormLocomotiveCollection>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.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,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<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.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +36,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

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