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

This commit is contained in:
Aidar 2024-05-25 21:00:33 +04:00
parent 84fb3e45a2
commit ba1621ee9f
12 changed files with 276 additions and 91 deletions

View File

@ -1,4 +1,5 @@
using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects;
@ -102,10 +103,17 @@ public abstract class AbstractCompany
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception)
{
continue;
}
}
return bitmap;
}

View File

@ -1,4 +1,5 @@

using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
@ -20,7 +21,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int MaxCount {
public int MaxCount
{
get
{
return _maxCount;
@ -44,42 +46,53 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position > _collection.Count)
try
{
return null;
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public int Insert(T obj)
{
return Insert(obj, _collection.Count);
return Insert(obj, Count);
}
public int Insert(T obj, int position)
{
if (_maxCount == _collection.Count || position < 0 || position > _collection.Count)
if (Count >= _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
_collection.Insert(position, obj);
return _collection.Count;
return Count;
}
public T? Remove(int position)
{
if (position < 0 || position > _collection.Count)
try
{
return null;
}
T? obj = _collection[position];
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}

View File

@ -1,4 +1,4 @@

using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects;
@ -50,8 +50,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count) return _collection[position];
else return null;
try
{
if (_collection[position] == null)
{
throw new ObjectNotFoundException();
}
return _collection[position];
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public int Insert(T obj)
@ -61,16 +71,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
if (position < 0 || position > _collection.Length - 1)
{
return -1;
throw new PositionOutOfCollectionException();
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
@ -87,23 +91,25 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= _collection.Count())
{
return null;
}
if (_collection[position] != null)
try
{
T obj = _collection[position];
if (obj == null)
{
throw new ObjectNotFoundException(position);
}
_collection[position] = null;
return obj;
}
return null;
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public IEnumerable<T?> GetItems()

View File

@ -52,14 +52,20 @@ public class ShipSharingService : AbstractCompany
}
int row = 1, col = 1;
for (int i = 0; i < _collection?.Count; i++, col++)
{
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5);
if (col == countInRow)
{
col = 0;
row++
;
row++;
}
}
catch (Exception)
{
continue;
}
}
}

View File

@ -1,7 +1,9 @@
using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
@ -9,16 +11,6 @@ namespace ProjectLiner.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningShip
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
@ -34,7 +26,15 @@ public class StorageCollection<T>
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
@ -106,57 +106,58 @@ 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))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (!string.IsNullOrEmpty(data))
{
writer.Write(data + _separatorItems);
writer.WriteLine(data);
}
}
writer.WriteLine();
}
}
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 (StreamReader reader = new StreamReader(filename))
{
string line = reader.ReadLine();
if (line == null || !line.Equals(_collectionKey))
if (line == null)
{
return false;
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
@ -174,7 +175,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]);
@ -185,17 +186,21 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningShip() is T ship)
{
if (collection.Insert(ship) == -1)
try
{
return false;
collection.Insert(ship);
}
catch (Exception ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
line = reader.ReadLine();
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectLiner.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,20 @@
using System.Runtime.Serialization;
namespace ProjectLiner.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,20 @@
using System.Runtime.Serialization;
namespace ProjectLiner.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 ProjectLiner.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings;
using System.Windows.Forms;
namespace ProjectLiner;
@ -19,13 +19,19 @@ public partial class FormShipCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -60,14 +66,19 @@ public partial class FormShipCollection : Form
{
return;
}
if (_company + ship != -1)
try
{
if ((_company + ship) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект: {entity}", ship.GetDataForSave());
pictureBox.Image = _company.Show();
}
else
}
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -87,14 +98,17 @@ public partial class FormShipCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
DrawningShip ship = _company - pos;
_logger.LogInformation("Объект по позиции {pos} удаден", pos);
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -168,6 +182,7 @@ public partial class FormShipCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType);
}
/// <summary>
@ -179,13 +194,14 @@ public partial class FormShipCollection : Form
{
if (listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Сначала выберите коллекцию");
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString());
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty);
RefreshListBoxItems();
}
@ -224,6 +240,7 @@ public partial class FormShipCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogInformation("Коллекция не проиннициализирована");
return;
}
@ -231,8 +248,10 @@ public partial class FormShipCollection : Form
{
case "Хранилище":
_company = new ShipSharingService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Создана компания типа шипшейринг, коллекция: {CollectionName}", listBoxCollection.SelectedItem);
break;
}
_logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem);
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
@ -246,13 +265,16 @@ public partial class FormShipCollection : 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);
}
}
}
@ -266,15 +288,18 @@ public partial class FormShipCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
RefreshListBoxItems();
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка {Message}", ex.Message);
}
RefreshListBoxItems();
}
}
}

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.File;
using Serilog.Configuration;
using Microsoft.Extensions.Configuration;
namespace ProjectLiner
{
internal static class Program
@ -11,7 +19,26 @@ namespace ProjectLiner
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Settings.json").Build();
services.AddSingleton<FormShipCollection>()
.AddLogging(builder =>
{
builder.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger());
});
}
}
}

View File

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

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "shipLog.log",
"outputTemplate": "[{Timestamp:dd.MM.yyyy_HH:mm:ss.fff zzz}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}