2 Commits

Author SHA1 Message Date
329ebf6e8a Lab07.2 2024-02-12 21:07:25 +04:00
128ee83824 Lab07.1 2024-02-11 21:08:25 +04:00
13 changed files with 319 additions and 111 deletions

View File

@@ -35,7 +35,7 @@ namespace MotorBoat.CollectionGenericObjects
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight * 73/50);
/// <summary>
/// Конструктор

View File

@@ -1,4 +1,6 @@
namespace MotorBoat.CollectionGenericObjects
using MotorBoat.Exceptions;
namespace MotorBoat.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
@@ -45,9 +47,14 @@
/// <returns></returns>
public T? Get(int position)
{
if (position < 0 || position >= _maxCount)
{
return null;
/////////////////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки если выход за границы массива--------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
@@ -56,7 +63,11 @@
{
if (Count == _maxCount)
{
return false;
////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки при переполнении--------------------------//
//////////////////////////////////////////////////////////////////////////////////
throw new CollectionOverflowException(_maxCount);
}
_collection.Add(obj);
return true;
@@ -64,27 +75,36 @@
public bool Insert(T obj, int position)
{
if (position < 0 || position >= _maxCount || Count == _maxCount)
if (position < 0 || position >= _maxCount)
{
return false;
}
if (Count == _maxCount)
{
////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки при переполнении--------------------------//
//////////////////////////////////////////////////////////////////////////////////
throw new CollectionOverflowException(_maxCount);
}
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
if (_collection.Count == 0 || position < 0 || position >= _collection.Count)
if (/*_collection.Count == 0 || position < 0 || */position > _collection.Count)
{
return false;
/////////////////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки если выход за границы массива--------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////
throw new PositionOutOfCollectionException(position);
}
_collection.RemoveAt(position);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//---------------Lab06 - Получение элементов коллекции по одному--------------------------//
///////////////////////////////////////////////////////////////////////////////////////////
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)

View File

@@ -1,4 +1,6 @@

using MotorBoat.Exceptions;
using System.Text;
namespace MotorBoat.CollectionGenericObjects
{
/// <summary>
@@ -49,23 +51,35 @@ namespace MotorBoat.CollectionGenericObjects
public T? Get(int position)
{
if (position >= 0 && position < _collection.Length)
if (position < 0 || position >= _collection.Length)
{
return _collection[position];
/////////////////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки если выход за границы массива--------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////
throw new PositionOutOfCollectionException(position);
}
return null;
return _collection[position];
}
public bool Insert(T obj)
{
if(obj == null)
if (obj == null)
{
return false;
}
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
int result = _collection.Count(s => s == null);
if (result == 0)
{
////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки при переполнении--------------------------//
//////////////////////////////////////////////////////////////////////////////////
throw new CollectionOverflowException(Count);
}
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
@@ -74,38 +88,107 @@ namespace MotorBoat.CollectionGenericObjects
return false;
}
//public bool Insert(T obj)
//{
// try
// {
// if (obj == null)
// {
// return false;
// }
// int result = _collection.Count(s => s == null);
// if (result == 0)
// {
// ////////////////////////////////////////////////////////////////////////////////////
// //---------------Lab07 - Выброс ошибки при переполнении--------------------------//
// //////////////////////////////////////////////////////////////////////////////////
// throw new CollectionOverflowException(Count);
// }
// for (int i = 0; i < _collection.Length; i++)
// {
// if (_collection[i] == null)
// {
// _collection[i] = obj;
// return true;
// }
// }
// return false;
// }
// catch (CollectionOverflowException ex)
// {
// // Обработка исключения при переполнении коллекции
// Console.WriteLine($"Ошибка: {ex.Message}");
// return false;
// }
//}
public bool Insert(T obj, int position)
{
if (position >= 0 && position < _collection.Length)
if (obj == null)
{
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
for (int i = position + 1; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
if (position < 0 || position >= _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
int result = _collection.Count(s => s == null);
if (result == 0)
{
throw new CollectionOverflowException(Count);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
for (int i = ++position; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = --position; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
public bool Remove(int position)
{
if (position >= 0 && position < _collection.Length)
if (position < 0 || position >= _collection.Length)
{
_collection[position] = null;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки если выход за границы массива--------------------------//
///////////////////////////////////////////////////////////////////////////////////////////////
return false;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
//////////////////////////////////////////////////////////////////////////////////////
//---------------Lab07 - Выброс ошибки если объект пустой--------------------------//
////////////////////////////////////////////////////////////////////////////////////
throw new ObjectNotFoundException(position);
}
_collection[position] = null;
return true;
}
public IEnumerable<T?> GetItems()

View File

@@ -1,4 +1,5 @@
using MotorBoat.Drawnings;
using MotorBoat.Exceptions;
using System.Text;
namespace MotorBoat.CollectionGenericObjects
@@ -97,12 +98,11 @@ namespace MotorBoat.CollectionGenericObjects
/// Сохранение информации по автомобилям в хранилище в файл
/// </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 Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -145,19 +145,17 @@ namespace MotorBoat.CollectionGenericObjects
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
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 Exception("Файл не существует");
}
string bufferTextFromFile = "";
@@ -174,13 +172,13 @@ namespace MotorBoat.CollectionGenericObjects
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
@@ -193,30 +191,31 @@ namespace MotorBoat.CollectionGenericObjects
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T car)
if (elem?.CreateDrawningBoat() is T boat)
{
if (!collection.Insert(car))
try
{
return false;
if (!collection.Insert(boat))
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
/// <summary>

View File

@@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace MotorBoat.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,21 @@
using System.Runtime.Serialization;
namespace MotorBoat.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,21 @@
using System.Runtime.Serialization;
namespace MotorBoat.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

@@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(902, 24);
groupBoxTools.Location = new Point(834, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 511);
groupBoxTools.Size = new Size(200, 508);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -81,9 +81,9 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveBoat);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 334);
panelCompanyTools.Location = new Point(3, 362);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 174);
panelCompanyTools.Size = new Size(194, 143);
panelCompanyTools.TabIndex = 9;
//
// buttonAddBoat
@@ -100,7 +100,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(14, 147);
buttonRefresh.Location = new Point(14, 118);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(167, 21);
buttonRefresh.TabIndex = 6;
@@ -111,7 +111,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(14, 62);
maskedTextBoxPosition.Location = new Point(14, 33);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(167, 23);
@@ -121,7 +121,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(14, 118);
buttonGoToCheck.Location = new Point(12, 89);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(167, 23);
buttonGoToCheck.TabIndex = 5;
@@ -132,7 +132,7 @@
// buttonRemoveBoat
//
buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBoat.Location = new Point(14, 91);
buttonRemoveBoat.Location = new Point(14, 62);
buttonRemoveBoat.Name = "buttonRemoveBoat";
buttonRemoveBoat.Size = new Size(167, 21);
buttonRemoveBoat.TabIndex = 4;
@@ -246,10 +246,11 @@
//
// pictureBox
//
pictureBox.Dock = DockStyle.Left;
pictureBox.Enabled = false;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(884, 537);
pictureBox.Size = new Size(830, 508);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -258,7 +259,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1102, 24);
menuStrip.Size = new Size(1034, 24);
menuStrip.TabIndex = 0;
menuStrip.Text = "menuStrip1";
//
@@ -297,7 +298,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1102, 535);
ClientSize = new Size(1034, 532);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);

View File

@@ -1,14 +1,6 @@
using MotorBoat.CollectionGenericObjects;
using MotorBoat.Drawnings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
namespace MotorBoat
{
@@ -27,13 +19,19 @@ namespace MotorBoat
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatCollection()
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@@ -54,36 +52,31 @@ namespace MotorBoat
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfig form = new();
//33 минута
//////////////////////////////////////////////////////////////////
//---------------передать метод в FormBoatConfig---------------//
////////////////////////////////////////////////////////////////
form.AddEvent(SetBoat);
form.Show();
}
/// <summary>
/// Добавление автомобиля в коллекцию
/// Добавление лодки в коллекцию
/// </summary>
/// <param name="boat"></param>
private void SetBoat(DrawningBoat? boat)
private void SetBoat(DrawningBoat boat)
{
if (_company == null || boat == null)
{
return;
}
if (_company + boat)
try
{
bool isSet = _company + boat;
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {boat}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -98,21 +91,22 @@ namespace MotorBoat
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos)
try
{
bool isRemove = _company - pos;
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект с индексом: {pos}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -255,34 +249,35 @@ namespace MotorBoat
{
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);
}
}
}
//////////////////////////////////////////////////////////
//---------------Lab06 - Логика загрузки---------------//
////////////////////////////////////////////////////////
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_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);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
RerfreshListBoxItems();

View File

@@ -127,6 +127,6 @@
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>105</value>
<value>62</value>
</metadata>
</root>

View File

@@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace MotorBoat
{
internal static class Program
@@ -11,8 +15,25 @@ namespace MotorBoat
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
//Application.Run(new FormMotorBoat());
Application.Run(new FormBoatCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

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