Лабораторная работа №7 (try )

This commit is contained in:
DjonniStorm 2024-04-19 00:58:36 +04:00
parent 2675d1dcd3
commit 1e1053b0af
10 changed files with 161 additions and 38 deletions

View File

@ -1,4 +1,5 @@
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
using Exceptions;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -40,27 +41,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Get(int position) public T Get(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException();
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T temp = _collection[position]; T temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;

View File

@ -1,4 +1,5 @@
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
using Exceptions;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
@ -43,7 +44,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) return null; if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
@ -56,11 +57,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException();
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -86,12 +87,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
--temp; --temp;
} }
return -1; throw new CollectionOverflowException();
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T? myObject = _collection[position]; T? myObject = _collection[position];
if (myObject == null) throw new ObjectNotFoundException();
_collection[position] = null; _collection[position] = null;
return myObject; return myObject;
} }

View File

@ -1,5 +1,7 @@
using ProjectCleaningCar.Drawning; using NLog.LayoutRenderers.Wrappers;
using ProjectCleaningCar.Drawning;
using ProjectCleaningCar.Entities; using ProjectCleaningCar.Entities;
using ProjectCleaningCar.Exceptions;
using System.Text; using System.Text;
namespace ProjectCleaningCar.CollectionGenericObjects; namespace ProjectCleaningCar.CollectionGenericObjects;
@ -96,11 +98,12 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -136,7 +139,6 @@ public class StorageCollection<T>
} }
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -144,23 +146,23 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">>Путь и имя файла</param> /// <param name="filename">>Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException($"{filename} не существует");
} }
using (StreamReader reader = new(filename)) using (StreamReader reader = new(filename))
{ {
string line = reader.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new Exception("Файл не подходит");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
//если нет такой записи, то это не те данные
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)
@ -175,7 +177,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, string[] set = record[3].Split(_separatorItems,
@ -183,17 +185,23 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningCar() is T truck) if (elem?.CreateDrawningCar() is T truck)
{
try
{ {
if (collection.Insert(truck) == -1) if (collection.Insert(truck) == -1)
{ {
return false; throw new Exception("Объект не удалось добавить в коллекцию: ");
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectCleaningCar.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 ProjectCleaningCar.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,15 @@
using System.Runtime.Serialization;
namespace ProjectCleaningCar.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,6 +1,6 @@
using ProjectCleaningCar.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectCleaningCar.CollectionGenericObjects;
using ProjectCleaningCar.Drawning; using ProjectCleaningCar.Drawning;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectCleaningCar; namespace ProjectCleaningCar;
/// <summary> /// <summary>
@ -18,13 +18,16 @@ public partial class FormCleaningCarCollection : Form
/// Компания /// Компания
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormCleaningCarCollection() public FormCleaningCarCollection(ILogger<FormCleaningCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@ -245,15 +248,15 @@ public partial class FormCleaningCarCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storageCollection.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
else } catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -267,14 +270,21 @@ public partial class FormCleaningCarCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storageCollection.Keys)
{
listBoxCollection.Items.Add(collection);
}
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectCleaningCar namespace ProjectCleaningCar
{ {
internal static class Program internal static class Program
@ -11,7 +17,30 @@ namespace ProjectCleaningCar
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCleaningCarCollection()); ServiceCollection services = new();
ConfigureService(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormCleaningCarCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà
/// </summary>
/// <param name="services"></param>
private static void ConfigureService(ServiceCollection services)
{
services
.AddSingleton<FormCleaningCarCollection>()
.AddLogging(option => {
option.SetMinimumLevel(LogLevel.Information);
//option.AddSerilog(new LoggerConfiguration()
// //.WriteTo
// .CreateLogger());
option.AddNLog("serilog.config");
});
} }
} }
} }

View File

@ -8,6 +8,12 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +29,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </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>