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

This commit is contained in:
Anitonchik 2024-05-06 22:44:13 +04:00
parent ebd5940f5a
commit 3719b24ca9
14 changed files with 250 additions and 91 deletions

View File

@ -37,6 +37,7 @@ public abstract class AbstractCompany
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -95,8 +96,12 @@ 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 (Exception) { }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -48,16 +49,18 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= 0 && position < Count && _collection[position] != null)
return _collection[position];
return null;
if (position < 0 || position >= MaxCount)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
if (_collection.Count > _maxCount)
if (_collection.Count >= _maxCount)
{
return -1;
throw new CollectionOverflowException(MaxCount);
}
_collection.Add(obj);
return _collection.Count;
@ -65,40 +68,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position)
{
if (_collection.Count > _maxCount || position < 0 || position > _maxCount)
if (position < 0 || position > _maxCount)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection.Count >= _maxCount)
{
throw new CollectionOverflowException(MaxCount);
}
_collection.Insert(position, obj);
return position;
if (_collection[position] == null)
{
_collection.Insert(position, obj);
return position;
}
for (int i = position + 1; i < _maxCount; ++i)
{
if (_collection[i] == null)
{
_collection.Insert(position, obj);
return position;
}
}
for (int i = 0; i < position; ++i)
{
if (_collection[i] == null)
{
_collection.Insert(position, obj);
return position;
}
}
return -1;
}
public T Remove(int position)
{
if (position < 0 || position > _maxCount)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T temp = _collection[position];
_collection.RemoveAt(position);

View File

@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -52,13 +53,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= 0 && position < Count && _collection[position] != null)
return _collection[position];
return null;
if (position < 0 || position >= MaxCount)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
for (int i = 0; i < _collection.Length; ++i)
for (int i = 0; i < MaxCount; ++i)
{
if (_collection[i] == null)
{
@ -66,13 +74,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position > Count)
if (position < 0 || position >= MaxCount)
{
return -1;
throw new PositionOutOfCollectionException(Count);
}
if (_collection[position] == null)
{
@ -95,17 +103,21 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position >= 0 && position < Count)
if (position < 0 || position >= MaxCount)
{
T remove = _collection[position];
_collection[position]= null;
return remove;
throw new PositionOutOfCollectionException(position);
}
return null;
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T remove = _collection[position];
_collection[position]= null;
return remove;
}
public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -103,12 +104,13 @@ 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))
{
@ -143,27 +145,31 @@ public class StorageCollection<T>
wr.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 Exception("Файл не существует");
}
using StreamReader rd = new StreamReader(filename);
UTF8Encoding temp = new(true);
string str = rd.ReadLine();
if (str == null || !str.StartsWith(_collectionKey))
if (str == null)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
@ -179,7 +185,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекции");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -187,15 +193,22 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningTruck() is T truck)
{
if (collection.Insert(truck) < 0)
try
{
return false;
if (collection.Insert(truck) < 0)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
/// <summary>

View File

@ -68,13 +68,17 @@ public class TruckSharingService : AbstractCompany
x_pos = start_width;
for (int i = 0; i < maxWidth; i++)
{
if (_collection.Get(i_collection) != null)
try
{
_collection.Get(i_collection).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i_collection).SetPosition(x_pos, y_pos);
x_pos += _placeSizeWidth + width_between;
i_collection++;
if (_collection.Get(i_collection) != null)
{
_collection.Get(i_collection).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i_collection).SetPosition(x_pos, y_pos);
x_pos += _placeSizeWidth + width_between;
i_collection++;
}
}
catch (Exception) { }
}
y_pos = y_pos + _placeSizeHeight;
}

View File

@ -103,8 +103,6 @@ public class DrawningTruck
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningTruckWidth > width || _drawningTruckHeight > height)
{
return false;

View File

@ -0,0 +1,21 @@
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]
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 contex) : base(info, contex) { }
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Exceptions;
public 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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Exceptions;
public 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.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectDumpTruck.CollectionGenericObjects;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -24,11 +26,17 @@ public partial class FormTruckCollection : Form
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormTruckCollection()
public FormTruckCollection(ILogger<FormTruckCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -60,19 +68,27 @@ 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 >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен");
}
}
if (_company + truck >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
@ -92,14 +108,17 @@ public partial class FormTruckCollection : 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();
}
}
else
{
catch (Exception ex) {
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -245,13 +264,17 @@ 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);
}
}
}
@ -260,14 +283,16 @@ 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);
RerfreshListBoxItems();
}
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

@ -67,8 +67,8 @@ namespace ProjectDumpTruck
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
/// <param name="e"></paramlabelSimpleObject>
private void LabelObject_MouseDown(object sender, MouseEventArgs elabelSimpleObject)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ??
string.Empty, DragDropEffects.Move | DragDropEffects.Copy);

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using Serilog.Settings.Configuration;
namespace ProjectDumpTruck
{
internal static class Program
@ -10,8 +19,28 @@ namespace ProjectDumpTruck
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection services = new();
ConfigureServices(services);
ApplicationConfiguration.Initialize();
Application.Run(new FormTruckCollection());
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);
option.AddSerilog(new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger());
});
}
}
}

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +34,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
<?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>