LabWork07

This commit is contained in:
Osyagina_Anna 2024-05-02 11:23:05 +04:00
parent 246c2ee2c2
commit 1597553ddc
13 changed files with 197 additions and 174 deletions

View File

@ -1,5 +1,6 @@
using ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
@ -16,9 +17,8 @@ public abstract class AbstractCompany
protected ICollectionGenericObjects<DrawningBoat>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBoat> collection)
{
_pictureWidth = picWidth;
@ -49,8 +49,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningBoat? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap;

View File

@ -1,5 +1,5 @@
using ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
@ -36,12 +36,13 @@ public class HarborService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * boatWidth + 20, boatHeight * _placeSizeHeight + 20);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (boatWidth < width - 1)
boatWidth++;
else

View File

@ -48,7 +48,7 @@ where T : class
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
//TODO выброс ошибки если выход за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
@ -56,7 +56,6 @@ where T : class
}
public int Insert(T obj)
{
// TODO выброс ошибки если переполнение
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
@ -76,7 +75,8 @@ where T : class
public T Remove(int position)
{
// TODO если выброс за границу
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;

View File

@ -40,68 +40,76 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>();
}
public T Get(int position)
public T? Get(int position)
{
// TODO выброс ошибки если выход за границу
// TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO выброс ошибки если переполнение
int index = 0;
while (index < _collection.Length)
for (int i = 0; i < Count; i++)
{
if (_collection[index] == null)
if (_collection[i] == null)
{
_collection[index] = obj;
return index;
_collection[i] = obj;
return i;
}
++index;
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
int index = position + 1;
while (index < _collection.Length)
{
if (_collection[index] == null)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
_collection[index] = obj;
return index;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
index++;
}
index = position - 1;
while (index >= 0)
{
if (_collection[index] == null)
if (!pushed)
{
_collection[index] = obj;
return index;
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
index--;
}
throw new CollectionOverflowException(Count);
// вставка
_collection[position] = obj;
return position;
}
public T Remove(int position)
{
// TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T removeObj = _collection[position];
T? temp = _collection[position];
_collection[position] = null;
return removeObj;
return temp;
}
public IEnumerable<T> GetItems()
@ -115,3 +123,4 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>

View File

@ -1,16 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;

using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count" + count) { }
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество" + count) { }
public CollectionOverflowException() : base() { }

View File

@ -9,7 +9,7 @@ namespace ProjectMotorboat.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("В коллекции превышено допустимое количество count" + i) { }
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }

View File

@ -10,7 +10,7 @@ namespace ProjectMotorboat.Exceptions;
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("В коллекции превышено допустимое количество count" + i) { }
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }

View File

@ -14,7 +14,7 @@ public partial class FormBoatCollection : Form
private AbstractCompany? _company = null;
private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
@ -23,13 +23,13 @@ public partial class FormBoatCollection : Form
_logger.LogInformation("Форма загрузилась");
}
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfig form = new();
@ -37,30 +37,28 @@ public partial class FormBoatCollection : Form
form.AddEvent(SetBoat);
}
private void SetBoat(DrawningBoat? boat)
private void SetBoat(DrawningBoat boat)
{
if (_company == null || boat == null)
{
return;
}
try
{
if (_company == null || boat == null)
{
return;
}
if (_company + boat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + boat.GetDataForSave());
}
var res = _company + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
@ -68,7 +66,8 @@ public partial class FormBoatCollection : Form
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
@ -76,21 +75,21 @@ public partial class FormBoatCollection : Form
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
@ -100,31 +99,27 @@ public partial class FormBoatCollection : Form
DrawningBoat? boat = null;
int counter = 100;
try
while (boat == null)
{
while (boat == null)
boat = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
boat = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
break;
}
FormMotorboat Form = new()
{
SetBoat = boat
};
Form.ShowDialog();
}
catch (Exception ex)
if (boat == null)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
FormMotorboat form = new()
{
SetBoat = boat
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
@ -137,59 +132,54 @@ public partial class FormBoatCollection : Form
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
RerfreshListBoxItems();
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
@ -213,7 +203,8 @@ public partial class FormBoatCollection : Form
return;
}
ICollectionGenericObjects<DrawningBoat>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningBoat>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -224,13 +215,13 @@ public partial class FormBoatCollection : Form
{
case "Хранилище":
_company = new HarborService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
@ -243,7 +234,7 @@ public partial class FormBoatCollection : Form
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -256,17 +247,16 @@ public partial class FormBoatCollection : Form
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@ -126,4 +126,7 @@
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>51</value>
</metadata>
</root>

View File

@ -1,34 +1,44 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectMotorboat
namespace ProjectMotorboat;
internal static class Program
{
internal static class Program
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection services = new();
ApplicationConfiguration.Initialize();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}

View File

@ -13,10 +13,12 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

View File

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

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": "Motorboat"
}
}
}