10 Commits
laba6 ... lab7

Author SHA1 Message Date
6e4f175cd6 зафиксировать 2023-12-25 21:39:51 +04:00
c41e547bab зафиксировать конечное 2023-12-25 00:48:36 +04:00
af1b077f80 зафиксировать 2023-12-25 00:46:05 +04:00
9da7eec2fc зафиксировать 2023-12-25 00:37:34 +04:00
add1290695 зафиксировать 2023-12-11 12:50:33 +04:00
857e61b773 зафиксировать 2023-12-11 12:17:18 +04:00
4025edbc31 зафиксировать 2023-12-11 12:01:36 +04:00
ae34d1e2c2 зафиксировать 2023-12-11 11:41:00 +04:00
95892d4f59 зафиксировать 2023-12-10 21:24:28 +04:00
a17a520267 зафиксировать 2023-12-02 19:40:05 +04:00
18 changed files with 431 additions and 93 deletions

View File

@@ -0,0 +1,121 @@
[*.cs]
# IDE0005: Директива using не нужна.
dotnet_diagnostic.IDE0005.severity = silent
csharp_style_throw_expression = true:suggestion
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_prefer_collection_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
[*.cs]
#### Стили именования ####
# Правила именования
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Спецификации символов
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Стили именования
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
[*.vb]
#### Стили именования ####
# Правила именования
dotnet_naming_rule.interface_should_be_начинается_с_i.severity = suggestion
dotnet_naming_rule.interface_should_be_начинается_с_i.symbols = interface
dotnet_naming_rule.interface_should_be_начинается_с_i.style = начинается_с_i
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.symbols = типы
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.symbols = не_являющиеся_полем_члены
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы
# Спецификации символов
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.типы.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.типы.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.типы.required_modifiers =
dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_kinds = property, event, method
dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.не_являющиеся_полем_члены.required_modifiers =
# Стили именования
dotnet_naming_style.начинается_с_i.required_prefix = I
dotnet_naming_style.начинается_с_i.required_suffix =
dotnet_naming_style.начинается_с_i.word_separator =
dotnet_naming_style.начинается_с_i.capitalization = pascal_case
dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case
dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case

View File

@@ -1,15 +0,0 @@
using ProjectBoat_bae.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae
{
internal class BoatDelegate
{
// Делегат для передачи объекта-автомобиля
public delegate void boatDelegate(Drawningboat boat);
}
}

View File

@@ -74,8 +74,16 @@ namespace ProjectBoat_bae.DrawningObjects
// Установка позиции // Установка позиции
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
_startPosX = Math.Min(x, _pictureWidth - _boatWidth); if (x < 0 || x + _boatWidth > _pictureWidth)
_startPosY = Math.Min(y, _pictureHeight - _boatHeight); {
x = Math.Max(0, _pictureWidth - _boatWidth);
}
if (y < 0 || y + _boatHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _boatHeight);
}
_startPosX = x;
_startPosY = y;
} }
// Прорисовка объекта // Прорисовка объекта
@@ -88,17 +96,17 @@ namespace ProjectBoat_bae.DrawningObjects
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
//корпус //корпус
Brush br = new SolidBrush(EntityBoat.BodyColor); Brush br = new SolidBrush(EntityBoat.BodyColor);
g.FillRectangle(br, _startPosX + 20, _startPosY + 65, 80, 50); g.FillRectangle(br, _startPosX + 50, _startPosY + 85, 80, 50);
//мотор //мотор
Brush brRed = new SolidBrush(EntityBoat.BodyColor); Brush brRed = new SolidBrush(EntityBoat.BodyColor);
g.FillEllipse(brRed, _startPosX + 7, _startPosY + 72, 35, 35); g.FillEllipse(brRed, _startPosX + 30, _startPosY + 92, 35, 35);
//стекла //стекла
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX + 95, _startPosY + 67, 5, 45); g.FillRectangle(brBlue, _startPosX + 125, _startPosY + 87, 5, 45);
g.FillRectangle(brBlue, _startPosX + 45, _startPosY + 67, 55, 2); g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 87, 55, 2);
g.FillRectangle(brBlue, _startPosX + 45, _startPosY + 111, 55, 2); g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 131, 55, 2);
} }
// Проверка, что объект может переместится по указанному направлению // Проверка, что объект может переместится по указанному направлению

View File

@@ -40,9 +40,9 @@ namespace ProjectBoat_bae.DrawningObjects
if (Boat.Wing) if (Boat.Wing)
{ {
//вёсла //вёсла
g.FillRectangle(additionalBrush, _startPosX + 35, _startPosY + 40, 5, 100); g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 60, 5, 100);
g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY + 40, 12, 8); g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 60, 12, 8);
g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY + 135, 12, 8); g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 155, 12, 8);
} }
base.DrawTransport(g); base.DrawTransport(g);
@@ -50,7 +50,7 @@ namespace ProjectBoat_bae.DrawningObjects
//кресла //кресла
if (Boat.Body) if (Boat.Body)
{ {
g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 70, 25, 40); g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 90, 25, 40);
} }
} }
} }

View File

@@ -16,7 +16,7 @@ namespace ProjectBoat_bae.Entities
public int Speed { get; private set; } public int Speed { get; private set; }
public double Weight { get; private set; } public double Weight { get; private set; }
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight; public double Step => (double)Speed * 200 / Weight;
public EntityBoat(int speed, double weight, Color bodyColor) public EntityBoat(int speed, double weight, Color bodyColor)
{ {

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Exceptions
{
[Serializable]
internal class BoatNotFoundException : ApplicationException
{
public BoatNotFoundException(int i)
: base($"Не найден объект по позиции {i}")
{ }
public BoatNotFoundException()
: base()
{ }
public BoatNotFoundException(string Message)
: base(Message)
{ }
public BoatNotFoundException(string Message, Exception Exception)
: base(Message, Exception)
{ }
public BoatNotFoundException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int Count)
: base($"В наборе превышено допустимое количество {Count}")
{ }
public StorageOverflowException()
: base()
{ }
public StorageOverflowException(string Message)
: base(Message)
{ }
public StorageOverflowException(string Message, Exception Exception)
: base(Message, Exception)
{ }
public StorageOverflowException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@@ -10,7 +10,7 @@ using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae namespace ProjectBoat_bae
{ {
internal static class ExtentionCar internal static class ExtentionBoat
{ {
// Разделитель для записи информации по объекту в файл // Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':'; private static readonly char _separatorForObject = ':';

View File

@@ -51,7 +51,7 @@
// //
pictureBoxCollection.Location = new Point(0, 0); pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(929, 647); pictureBoxCollection.Size = new Size(784, 647);
pictureBoxCollection.TabIndex = 0; pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
@@ -154,14 +154,14 @@
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(212, 34); SaveToolStripMenuItem.Size = new Size(270, 34);
SaveToolStripMenuItem.Text = "Сохранение"; SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenu_Click; SaveToolStripMenuItem.Click += SaveToolStripMenu_Click;
// //
// LoadToolStripMenuItem // LoadToolStripMenuItem
// //
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(212, 34); LoadToolStripMenuItem.Size = new Size(270, 34);
LoadToolStripMenuItem.Text = "Загрузка"; LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenu_Click; LoadToolStripMenuItem.Click += LoadToolStripMenu_Click;
// //

View File

@@ -1,4 +1,6 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -10,7 +12,9 @@ using System.Windows.Forms;
using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Generics; using ProjectBoat_bae.Generics;
using ProjectBoat_bae.Exceptions;
using ProjectBoat_bae.MovementStrategy; using ProjectBoat_bae.MovementStrategy;
using NLog;
namespace ProjectBoat_bae namespace ProjectBoat_bae
{ {
@@ -19,10 +23,15 @@ namespace ProjectBoat_bae
// Набор объектов // Набор объектов
private readonly BoatsGenericStorage _storage; private readonly BoatsGenericStorage _storage;
public FormBoatCollection() // Логер
private readonly
Microsoft.Extensions.Logging.ILogger? _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
// Заполнение listBoxObjects // Заполнение listBoxObjects
@@ -49,6 +58,7 @@ namespace ProjectBoat_bae
// Добавление набора в коллекцию // Добавление набора в коллекцию
private void ButtonAddObject_Click_1(object sender, EventArgs e) private void ButtonAddObject_Click_1(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
@@ -57,6 +67,7 @@ namespace ProjectBoat_bae
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
} }
// Удаление набора // Удаление набора
@@ -66,26 +77,26 @@ namespace ProjectBoat_bae
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
?? string.Empty); _logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены");
ReloadObjects(); return;
} }
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
// Добавление объекта в набор // Добавление объекта в набор
private void ButtonAddBoat_Click(object sender, EventArgs e) private void ButtonAddBoat_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
FormBoatConfig form = new FormBoatConfig(); FormBoatConfig formPlaneConfig = new FormBoatConfig();
formPlaneConfig.AddEvent(AddBoat);
form.AddEvent(AddBoat); formPlaneConfig.Show();
form.Show();
} }
private void AddBoat(Drawningboat boat) private void AddBoat(Drawningboat boat)
@@ -100,42 +111,57 @@ namespace ProjectBoat_bae
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats(); pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Добавлен объект {obj}");
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
//удаление объекта //удаление объекта
private void ButtonRemoveBoat_Click(object sender, EventArgs e) private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo,
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = 0; try
if (textBoxBoat != null)
pos = Convert.ToInt32(textBoxBoat.Text);
if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); int pos = Convert.ToInt32(textBoxBoat.Text);
pictureBoxCollection.Image = obj.ShowBoats(); if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Объект не удален");
_logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
} }
else catch (BoatNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Объекта нет");
_logger.LogWarning("Not input");
} }
} }
@@ -165,17 +191,20 @@ namespace ProjectBoat_bae
//сохранение //сохранение
private void SaveToolStripMenu_Click(object sender, EventArgs e) private void SaveToolStripMenu_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", "Результат", _storage.SaveData(saveFileDialog.FileName);
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", _logger.LogWarning("Не удалось сохранить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@@ -183,15 +212,22 @@ namespace ProjectBoat_bae
//загрузка //загрузка
private void LoadToolStripMenu_Click(object sender, EventArgs args) private void LoadToolStripMenu_Click(object sender, EventArgs args)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); {
else _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
} }
ReloadObjects();
} }
} }
} }

View File

@@ -10,6 +10,10 @@ using System.Windows.Forms;
using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities; using ProjectBoat_bae.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ProjectBoat_bae namespace ProjectBoat_bae
{ {
public partial class FormBoatConfig : Form public partial class FormBoatConfig : Form
@@ -83,18 +87,17 @@ namespace ProjectBoat_bae
// Действия при приеме перетаскиваемой информации // Действия при приеме перетаскиваемой информации
private void PanelObject_DragDrop(object sender, DragEventArgs e) private void PanelObject_DragDrop(object sender, DragEventArgs e)
{ {
ILogger<FormBoatCollection> logger = new NullLogger<FormBoatCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString()) switch (e.Data?.GetData(DataFormats.Text).ToString())
{ {
case "labelSimpleObject": case "labelSimpleObject":
_boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height); _boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break; break;
case "labelModifiedObject": case "labelModifiedObject":
_boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, _boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break; break;
} }
LabelColor.BackColor = Color.Empty;
LabelAdditionalColor.BackColor = Color.Empty;
DrawBoat(); DrawBoat();
} }

View File

@@ -20,10 +20,10 @@ namespace ProjectBoat_bae.Generics
/// <summary> /// <summary>
/// Размер занимаемого объектом места (ширина) /// Размер занимаемого объектом места (ширина)
/// </summary> /// </summary>
private readonly int _placeSizeWidth = 150; private readonly int _placeSizeWidth = 200;
// Размер занимаемого объектом места (высота) // Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 150; private readonly int _placeSizeHeight = 200;
// Набор объектов // Набор объектов
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -7,6 +8,7 @@ using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.MovementStrategy; using ProjectBoat_bae.MovementStrategy;
using ProjectBoat_bae.Entities; using ProjectBoat_bae.Entities;
using ProjectBoat_bae.Exceptions;
namespace ProjectBoat_bae.Generics namespace ProjectBoat_bae.Generics
{ {
@@ -49,14 +51,16 @@ namespace ProjectBoat_bae.Generics
private readonly char _separatorRecords = ';'; private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':'; private static readonly char _separatorForObject = ':';
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages) foreach (KeyValuePair<string,
BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (Drawningboat? elem in record.Value.GetBoats) foreach (Drawningboat? elem in record.Value.GetBoats)
@@ -67,20 +71,22 @@ namespace ProjectBoat_bae.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using FileStream fs = new(filename, FileMode.Create);
{ byte[] info = new
writer.Write($"PlaneStorage{Environment.NewLine}{data}"); UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}");
} fs.Write(info, 0, info.Length);
return true; return;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@@ -88,11 +94,11 @@ namespace ProjectBoat_bae.Generics
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new ArgumentException("Нет объекта для добавления");
} }
if (!str.StartsWith("BoatStorage")) if (str.StartsWith("BoatsStorage"))
{ {
return false; throw new InvalidDataException("Неверный формат данных");
} }
_boatStorages.Clear(); _boatStorages.Clear();
@@ -102,7 +108,7 @@ namespace ProjectBoat_bae.Generics
{ {
if (strs == null) if (strs == null)
{ {
return false; return;
} }
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@@ -119,13 +125,23 @@ namespace ProjectBoat_bae.Generics
{ {
if (!(collection + boat)) if (!(collection + boat))
{ {
return false; try
{
_ = collection + boat;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
} }
} }
} }
_boatStorages.Add(record[0], collection); _boatStorages.Add(record[0], collection);
} }
return true;
} }
} }
} }

View File

@@ -1,3 +1,12 @@
//using NLog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.ApplicationServices;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectBoat_bae namespace ProjectBoat_bae
{ {
internal static class Program internal static class Program
@@ -11,7 +20,34 @@ namespace ProjectBoat_bae
// 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 FormBoatCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run((serviceProvider.GetRequiredService<FormBoatCollection>()));
}
}
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] + "\\";
}
//используется для создания исходных текстов конфигурации для приложени
//SetBasePath Задает базовый путь для файла конфигурации к текущему каталогу приложения.
// файл JSON в качестве источника конфигурации.
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
//настроить формат записи логов
//используется для настройки регистратора Serilog.
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@@ -8,6 +8,28 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="appSettings.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Resource Include="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +45,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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

View File

@@ -0,0 +1,14 @@
<?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="boatlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@@ -3,7 +3,12 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279 VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9D03BD00-51B0-4389-84FD-8FF17153F0BE}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution