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

This commit is contained in:
qkrlnt 2024-05-17 14:10:29 +04:00
parent 744a9cec65
commit 5d47765f02
12 changed files with 255 additions and 89 deletions

View File

@ -1,5 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -41,7 +42,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, которые можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureHeight / _placeSizeHeight) * (_pictureWidth / _placeSizeWidth);
/// <summary>
/// Конструктор
@ -106,8 +107,12 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
DrawingTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawingTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException) { }
}
return bitmap;
}

View File

@ -1,9 +1,5 @@
using ProjectMonorail.CollectionGenericObject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObjects;
@ -40,28 +36,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count) { return null; }
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
return _collection[position];
}
public int Insert(T obj)
{
if (obj == null || Count + 1 > _maxCount) { return -1; }
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
_collection.Add(obj);
return Count + 1;
}
public int Insert(T obj, int position)
{
if (obj == null || Count + 1 > _maxCount) { return -1; }
if (position < 0 || position >= Count) { return -1; }
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
_collection.Insert(position, obj);
return Count + 1;
}
public T Remove(int position)
{
if (position < 0 || position >= Count) { return null; }
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
T tmp = _collection[position];
_collection.RemoveAt(position);
return tmp;

View File

@ -1,9 +1,5 @@
using ProjectMonorail.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObject;
@ -55,11 +51,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection[position] == null) { throw new ObjectNotFoundException(); }
return _collection[position];
}
public int Insert(T obj)
@ -72,15 +66,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException();
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
}
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
@ -97,15 +88,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException();
}
public T Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection == null) { throw new ObjectNotFoundException(); }
T tmp = _collection[position];
_collection[position] = null;
return tmp;

View File

@ -1,10 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObjects;
@ -97,12 +93,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 ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -142,19 +137,17 @@ public class StorageCollection<T>
streamWriter.Write(_separatorItems);
}
}
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 FileNotFoundException("Данный файл не существует");
}
using FileStream fs = new(filename, FileMode.Open);
@ -162,12 +155,11 @@ public class StorageCollection<T>
string firstString = streamReader.ReadLine();
if (firstString != _collectionKey || firstString.Length == 0)
{
return false;
throw new ArgumentException("В файле нет данных");
}
if (!firstString.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
@ -182,7 +174,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidCastException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -192,18 +184,22 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawingTrain() is T train)
{
if (collection.Insert(train) == -1)
try
{
return false;
if (collection.Insert(train) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
/// <summary>

View File

@ -1,5 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -45,9 +46,14 @@ public class TrainSharingService : AbstractCompany
{
for (int x = 10; x + _placeSizeWidth < _pictureWidth; x += _placeSizeWidth)
{
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(counter)?.SetPosition(x, y);
counter++;
try
{
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(counter)?.SetPosition(x, y);
counter++;
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException) { }
}
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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 context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.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 context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.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 context) : base(info, context) { }
}

View File

@ -1,14 +1,7 @@
using ProjectMonorail.CollectionGenericObject;
using Microsoft.Extensions.Logging;
using ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectMonorail.Exceptions;
using System.Windows.Forms;
namespace ProjectMonorail;
@ -28,13 +21,19 @@ public partial class FormTrainCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTrainCollection()
public FormTrainCollection(ILogger<FormTrainCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -70,14 +69,17 @@ public partial class FormTrainCollection : Form
return;
}
if (_company + train != -1)
try
{
var set = _company + train;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект: {train.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Коллекция переполнена");
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
}
@ -90,6 +92,7 @@ public partial class FormTrainCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
@ -98,15 +101,30 @@ public partial class FormTrainCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление объекта по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -126,11 +144,17 @@ public partial class FormTrainCollection : Form
int counter = 100;
while (train == null)
{
train = _company.GetRandomObject();
counter--;
if (counter <= 0)
try
{
break;
train = _company.GetRandomObject();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
}
@ -171,6 +195,7 @@ public partial class FormTrainCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Создание компании без данных");
return;
}
@ -185,6 +210,7 @@ public partial class FormTrainCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция {textBoxCollectionName.Text}");
RefreshListBoxItems();
}
@ -198,13 +224,16 @@ public partial class FormTrainCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление компании, не выбрав коллекцию");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция {name}");
RefreshListBoxItems();
}
@ -234,13 +263,15 @@ public partial class FormTrainCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании, не выбрав коллекцию");
return;
}
ICollectionGenericObjects<DrawingTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionGenericObject.ICollectionGenericObjects<DrawingTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не далось иницализировать коллекцию");
return;
}
@ -248,6 +279,7 @@ public partial class FormTrainCollection : Form
{
case "Хранилище":
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
@ -264,13 +296,16 @@ public partial class FormTrainCollection : 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);
}
}
}
@ -284,14 +319,17 @@ public partial class FormTrainCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RefreshListBoxItems();
}
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,4 +1,10 @@
namespace ProjectMonorail
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ProjectMonorail;
using Serilog;
namespace ProjectAirFighter
{
internal static class Program
{
@ -10,8 +16,30 @@ namespace ProjectMonorail
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection serviceCollection = new();
ConfigureService(serviceCollection);
ApplicationConfiguration.Initialize();
Application.Run(new FormTrainCollection());
using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
}
private static void ConfigureService(ServiceCollection services)
{
services.AddSingleton<FormTrainCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -8,4 +8,17 @@
<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="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</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": "ProjectMonorail"
}
}
}