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

This commit is contained in:
gettterot 2024-04-20 07:48:17 +04:00
parent 3d5e3f3cdc
commit ba8685e9dc
10 changed files with 185 additions and 51 deletions

View File

@ -1,4 +1,6 @@
using ProjectLiner.CollectionGenericObjects; using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Exceptions;
using System.Collections.Generic;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -10,12 +12,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
private readonly Dictionary<int, T> _collection; private readonly List<T?> _collection;
/// <summary> /// <summary>
/// Максимально допустимое число объектов в списке /// Максимально допустимое число объектов в списке
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count => _collection.Keys.Count; public int Count => _collection.Count;
public int MaxCount public int MaxCount
{ {
get get
@ -43,27 +45,31 @@ 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[Count-1] = 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();
_collection[position] = obj; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
return 1; _collection.Insert(position, obj);
return position;
} }
public T? Remove(int position)
public T Remove(int position)
{ {
if (_collection.ContainsKey(position)) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
T? temp = _collection[position]; T obj = _collection[position];
_collection.Remove(position); _collection.RemoveAt(position);
return temp; return obj;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,6 @@
 
using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects namespace ProjectLiner.CollectionGenericObjects
{ {
/// <summary> /// <summary>
@ -50,8 +52,7 @@ namespace ProjectLiner.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
return null;
return _collection[position]; return _collection[position];
} }
@ -65,12 +66,13 @@ namespace ProjectLiner.CollectionGenericObjects
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;
@ -96,21 +98,16 @@ namespace ProjectLiner.CollectionGenericObjects
} }
--temp; --temp;
} }
return -1; throw new CollectionOverflowException();
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
{ T? myObject = _collection[position];
return null; if (myObject == null) throw new ObjectNotFoundException();
}
//if (_collection[position] == null) return null;
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return myObject;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,5 +1,6 @@
using ProjectLiner.CollectionGenericObjects; using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings; using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
/// <summary> /// <summary>
/// Класс-хранилище коллекций /// Класс-хранилище коллекций
@ -90,10 +91,10 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</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))
File.Delete(filename); File.Delete(filename);
@ -128,7 +129,6 @@ public class StorageCollection<T>
sw.Write(_separatorItems); sw.Write(_separatorItems);
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -136,26 +136,24 @@ 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 (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
{ {
using StreamReader sr = new StreamReader(fs); using StreamReader sr = new StreamReader(fs);
string line = sr.ReadLine();
string str = sr.ReadLine(); if (line == null || line.Length == 0)
if (str == null || str.Length == 0)
{ {
return false; throw new Exception("Файл не подходит");
} }
if (!line.Equals(_collectionKey))
if (!str.Equals(_collectionKey))
{ {
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
@ -171,7 +169,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]);
@ -180,15 +178,23 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningCommonLiner() is T commonLiner) if (elem?.CreateDrawningCommonLiner() is T commonLiner)
{
try
{ {
if (collection.Insert(commonLiner) == -1) if (collection.Insert(commonLiner) == -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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLiner.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLiner.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLiner.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
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,4 +1,5 @@
 
using Microsoft.Extensions.Logging;
using ProjectLiner.CollectionGenericObjects; using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings; using ProjectLiner.Drawnings;
using System.Windows.Forms; using System.Windows.Forms;
@ -18,12 +19,17 @@ public partial class FormLinerCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary> /// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormLinerCollection() public FormLinerCollection(ILogger<FormLinerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@ -233,13 +239,16 @@ public partial class FormLinerCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -253,14 +262,19 @@ public partial class FormLinerCollection : 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,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace ProjectLiner namespace ProjectLiner
{ {
internal static class Program internal static class Program
@ -11,7 +16,27 @@ namespace ProjectLiner
// 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 FormLinerCollection());
ServiceCollection services = new();
ConfigureService(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormLinerCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ Ñåðâåñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureService(ServiceCollection services)
{
services
.AddSingleton<FormLinerCollection>()
.AddLogging(option => {
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("serilog.config");
});
} }
} }
} }

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +28,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>