PIBD-13_Baryshev_D.A._LabWork07_Base #7

Closed
xysiboi wants to merge 6 commits from LabWork07 into LabWork06
12 changed files with 295 additions and 67 deletions

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@ -13,26 +14,32 @@ public abstract class AbstractCompany
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 310;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 125;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция грузовиков
/// </summary>
protected ICollectionGenericObject<DrawningTruck>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -55,7 +62,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTruck truck)
{
return company._collection.Insert(truck);
return company._collection.Insert(truck,0);
}
/// <summary>
@ -66,7 +73,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static DrawningTruck? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position-1);
return company._collection?.Remove(position);
}
/// <summary>
@ -76,7 +83,14 @@ public abstract class AbstractCompany
public DrawningTruck? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
try
{
return _collection?.Get(rnd.Next(GetMaxCount));
}
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary>
@ -92,8 +106,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTruck? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningTruck? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@ -42,25 +43,29 @@ public class Autopark : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
try
{
int x = 20 + _placeSizeWidth * n;
int y = 10 + _placeSizeHeight * m;
if (_collection?.Get(i) != null)
{
int x = 20 + _placeSizeWidth * n;
int y = 10 + _placeSizeHeight * m;
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
}
if (n < _pictureWidth / _placeSizeWidth) n++;
else
{
n = 0;
m++;
}
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
catch (ObjectNotFoundException)
{
n = 0;
m++;
break;
}
}
}
}

View File

@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@ -50,7 +52,7 @@ public class ListGenericObjects<T> : ICollectionGenericObject<T>
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
@ -60,7 +62,7 @@ public class ListGenericObjects<T> : ICollectionGenericObject<T>
{
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
@ -69,9 +71,13 @@ public class ListGenericObjects<T> : ICollectionGenericObject<T>
public int Insert(T obj, int position)
{
if (Count == _maxCount || position < 0 || position > Count)
if (position < 0 || position > Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
@ -82,7 +88,7 @@ public class ListGenericObjects<T> : ICollectionGenericObject<T>
{
if (position < 0 || position > Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
@ -91,7 +97,7 @@ public class ListGenericObjects<T> : ICollectionGenericObject<T>
return obj;
}
public IEnumerable<T> GetItems()
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++) yield return _collection[i];
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@ -52,6 +53,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObject<T>
public T? Get(int position)
{
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
// TODO проверка позиции
if (position < 0 || position >= Count)
{
@ -71,14 +80,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObject<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@ -105,17 +115,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObject<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) return null;
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T? temp = _collection[position];
_collection[position] = null;

View File

@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -102,7 +103,7 @@ public class StorageCollection<T>
{
if (File.Exists(filename)) File.Delete(filename);
if (_storages.Count == 0) return false;
if (_storages.Count == 0) throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
using (StreamWriter sw = new StreamWriter(filename))
{
@ -143,19 +144,16 @@ public class StorageCollection<T>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename)) return false;
if (!File.Exists(filename)) throw new FileNotFoundException("Файл не существует");
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0) return false;
if (line == null || line.Length == 0) throw new FileFormatException("В файле нет данных"); ;
if (!line.Equals(_collectionKey)) throw new FileFormatException("В файле неверные данные");
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
@ -168,10 +166,8 @@ public class StorageCollection<T>
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObject<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
if (collection == null) throw new InvalidOperationException("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -179,9 +175,16 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningTruck() is T truck)
{
if (collection.Insert(truck) == -1)
try
{
return false;
if (collection.Insert(truck) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.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 ProjectDumpTruck.CollectionGenericObject;
using Microsoft.Extensions.Logging;
using ProjectDumpTruck.CollectionGenericObject;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -30,13 +32,16 @@ public partial class FormTruckCollection : Form
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTruckCollection()
public FormTruckCollection(ILogger <FormTruckCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -67,19 +72,24 @@ public partial class FormTruckCollection : Form
/// <param name="truck"></param>
private void SetTruck(DrawningTruck truck)
{
if (_company == null || truck == null)
try
{
return;
}
if (_company == null || truck == null)
{
return;
}
if (_company + truck != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + truck != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {truck.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
@ -100,15 +110,25 @@ public partial class FormTruckCollection : 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("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
}
@ -168,6 +188,7 @@ public partial class FormTruckCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@ -182,6 +203,7 @@ public partial class FormTruckCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RefreshListBoxItems();
}
@ -211,6 +233,7 @@ public partial class FormTruckCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RefreshListBoxItems();
}
@ -248,13 +271,16 @@ public partial class FormTruckCollection : 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);
}
}
}
@ -268,14 +294,17 @@ public partial class FormTruckCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из фала: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System;
namespace ProjectDumpTruck
{
internal static class Program
@ -11,7 +18,30 @@ namespace ProjectDumpTruck
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTruckCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services
.AddSingleton<FormTruckCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.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.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<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 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Users\\dimoo\\OneDrive\\Рабочий стол\\Лабы\\log.txt",
Review

Путь до файла логов не должен быть абсолютным

Путь до файла логов не должен быть абсолютным
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}