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

This commit is contained in:
grishazagidulin 2024-04-28 16:37:35 +04:00
parent 786492d756
commit 3cac227c53
10 changed files with 195 additions and 73 deletions

View File

@ -8,4 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -9,7 +9,7 @@ public abstract class AbstractCompany
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
protected readonly int _placeSizeWidth = 260;
/// <summary>
/// Размер места (высота)

View File

@ -1,4 +1,6 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -40,7 +42,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= _collection.Count)
return null;
throw new PositionOutOfCollectionException(position);
return _collection[position];
}
@ -51,13 +53,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.Add(obj);
return _collection.Count - 1;
}
return -1;
throw new CollectionOverflowException(MaxCount);
}
public bool Insert(T obj, int position)
{
if (_collection.Count + 1 > _maxCount || position < 0 || position >= _collection.Count)
return false;
if (_collection.Count + 1 > MaxCount)
throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return true;
}
@ -65,7 +69,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position)
{
if (position < 0 || position >= _collection.Count)
return null;
throw new PositionOutOfCollectionException(position);
T temp = _collection[position];
_collection.RemoveAt(position);
return temp;

View File

@ -1,4 +1,6 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
@ -53,10 +55,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length)
return null;
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj) //??? Уточнить реализацию
public int Insert(T obj)
{
for (int i = 0; i < _collection.Length; i++)
{
@ -66,12 +70,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(_collection.Length);
}
public bool Insert(T obj, int position)
{
if (position < 0 || position >= _collection.Length) // проверка позиции
return false;
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) // Попытка вставить на указанную позицию
{
_collection[position] = obj;
@ -93,16 +97,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return true;
}
}
return false;
throw new CollectionOverflowException(_collection.Length);
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Length || _collection[position]==null) // проверка позиции и наличия объекта
return null;
if (position < 0 || position >= _collection.Length) // проверка позиции
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
throw new ObjectNotFoundException(position);
T temp = _collection[position];
_collection[position] = null;
return temp;
}

View File

@ -31,10 +31,10 @@ public class ShipDocks : AbstractCompany
{
while (x + _placeSizeWidth < _pictureWidth)
{
g.DrawLine(pen, x, y, x + _placeSizeWidth, y);
g.DrawLine(pen, x, y, x + _placeSizeWidth - 50, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight);
g.DrawLine(pen, x, y + _placeSizeHeight, x+_placeSizeWidth, y + _placeSizeHeight);
x += _placeSizeWidth + 50;
g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth - 50, y + _placeSizeHeight);
x += _placeSizeWidth;
}
y += _placeSizeHeight;
x = 0;
@ -46,10 +46,13 @@ public class ShipDocks : AbstractCompany
int count = 0;
for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight)
{
for(int ix = 5; ix + _placeSizeWidth+50 < _pictureWidth; ix += _placeSizeWidth + 50)
for(int ix = 5; ix + _placeSizeWidth <= _pictureWidth; ix += _placeSizeWidth)
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(ix, iy);
if (count < _collection.Count)
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(ix, iy);
}
count++;
}
}

View File

@ -1,4 +1,5 @@
using Battleship.Drawnings;
using Battleship.Exceptions;
using System.Text;
namespace Battleship.CollectionGenericObjects;
@ -97,7 +98,7 @@ public class StorageCollection<T>
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -143,7 +144,7 @@ public class StorageCollection<T>
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
@ -151,7 +152,7 @@ public class StorageCollection<T>
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
throw new FormatException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
@ -164,7 +165,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -174,8 +175,17 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningShip() is T ship)
{
if (collection.Insert(ship) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
try
{
if (collection.Insert(ship) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);

View File

@ -66,9 +66,9 @@
Tools.Controls.Add(panelStorage);
Tools.Controls.Add(comboBoxSelectorCompany);
Tools.Dock = DockStyle.Right;
Tools.Location = new Point(1605, 40);
Tools.Location = new Point(1566, 40);
Tools.Name = "Tools";
Tools.Size = new Size(488, 1224);
Tools.Size = new Size(488, 1209);
Tools.TabIndex = 0;
Tools.TabStop = false;
Tools.Text = "Инструменты";
@ -249,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1605, 1224);
pictureBox.Size = new Size(1566, 1209);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -259,7 +259,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(2093, 40);
menuStrip.Size = new Size(2054, 40);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
@ -298,7 +298,7 @@
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(2093, 1264);
ClientSize = new Size(2054, 1249);
Controls.Add(pictureBox);
Controls.Add(Tools);
Controls.Add(menuStrip);

View File

@ -1,6 +1,7 @@
using Battleship.CollectionGenericObjects;
using Battleship.Drawnings;
using Battleship.Exceptions;
using Microsoft.Extensions.Logging;
namespace Battleship;
@ -11,14 +12,19 @@ public partial class FormShipCollection : Form
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
_storageCollection = new();
}
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
#region Работа с компанией
/// <summary>
/// Выбор компании
@ -30,6 +36,33 @@ public partial class FormShipCollection : Form
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Метод установки корабля в компанию
/// </summary>
private void SetShip(DrawningShip? ship)
{
if (_company == null)
return;
try
{
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавление корабля {ship} в коллекцию", ship);
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship);
}
}
catch(CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Кнопка удаления корабля
/// </summary>
/// <param name="sender"></param>
@ -45,17 +78,32 @@ public partial class FormShipCollection : Form
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление корабля по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos);
}
}
catch(ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Кнопка отправки на тест
@ -118,23 +166,7 @@ public partial class FormShipCollection : Form
form.AddEvent(SetShip);
form.Show();
}
/// <summary>
/// Метод установки корабля в компанию
/// </summary>
private void SetShip(DrawningShip? ship)
{
if (_company == null)
return;
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
#endregion
#region Работа с коллекцией
/// <summary>
@ -147,6 +179,7 @@ public partial class FormShipCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
@ -160,6 +193,7 @@ public partial class FormShipCollection : Form
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
RerfreshListBoxItems();
}
/// <summary>
@ -177,6 +211,7 @@ public partial class FormShipCollection : Form
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@ -220,8 +255,9 @@ public partial class FormShipCollection : Form
case "Доки":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection);
break;
default:
return;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
@ -236,13 +272,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);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -255,14 +294,17 @@ public partial class FormShipCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace Battleship
{
internal static class Program
@ -11,7 +16,30 @@ namespace Battleship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "C:\\Users\\grishazagidulin\\source\\repos\\Pi-12_Zagidulin_GA_Simple\\Battleship\\Battleship\\appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Battleship"
}
}
}