21 Commits
laba5 ... lab8

Author SHA1 Message Date
fe747801b0 зафиксировать 2023-12-28 21:03:30 +04:00
9f19a61ae6 зафиксировать 2023-12-25 21:44:25 +04:00
646780ae8a зафиксировать 2023-12-25 18:55:31 +04:00
7c4cf25b53 зафиксировать 2023-12-25 16:59:01 +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
Учебный
6c6d67d02d зафиксировать 2023-11-27 22:11:05 +04:00
Учебный
5b78e69ae5 зафиксировать 2023-11-27 12:32:34 +04:00
Учебный
d37961cec2 зафиксировать 2023-11-27 10:39:35 +04:00
Учебный
8e894ae31a зафиксировать 2023-11-26 21:29:24 +04:00
Учебный
e90db55dcc зафиксировать 2023-11-26 17:32:02 +04:00
Учебный
a59a70a69b зафиксировать 2023-11-26 14:11:41 +04:00
Учебный
e085b87859 зафиксировать 2023-11-26 12:43:34 +04:00
Учебный
41542e271d зафиксировать всё 2023-11-25 19:58:19 +04:00
25 changed files with 934 additions and 116 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

@@ -33,10 +33,10 @@ namespace ProjectBoat_bae.DrawningObjects
protected int _startPosY; protected int _startPosY;
// Ширина прорисовки // Ширина прорисовки
protected readonly int _boatWidth = 80; protected readonly int _boatWidth = 70;
// Высота прорисовки // Высота прорисовки
protected readonly int _boatHeight = 50; protected readonly int _boatHeight = 40;
public int GetPosX => _startPosX; public int GetPosX => _startPosX;
public int GetPosY => _startPosY; public int GetPosY => _startPosY;
@@ -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,18 +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 + 5, 100, 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 + 12, 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 + 115, _startPosY + 10, 5, g.FillRectangle(brBlue, _startPosX + 125, _startPosY + 87, 5, 45);
40); g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 87, 55, 2);
g.FillRectangle(brBlue, _startPosX + 65, _startPosY + 8, 55, 2); g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 131, 55, 2);
g.FillRectangle(brBlue, _startPosX + 65, _startPosY + 51, 55, 2);
} }
// Проверка, что объект может переместится по указанному направлению // Проверка, что объект может переместится по указанному направлению

View File

@@ -22,7 +22,6 @@ namespace ProjectBoat_bae.DrawningObjects
{ {
EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, EntityBoat = new EntityMotorBoat(speed, weight, bodyColor,
additionalColor, body, wing); additionalColor, body, wing);
} }
} }
@@ -32,6 +31,7 @@ namespace ProjectBoat_bae.DrawningObjects
{ {
return; return;
} }
Point[] points;
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(Boat.AdditionalColor); Brush additionalBrush = new SolidBrush(Boat.AdditionalColor);
Brush brr = new SolidBrush(EntityBoat.BodyColor); Brush brr = new SolidBrush(EntityBoat.BodyColor);
@@ -39,26 +39,18 @@ namespace ProjectBoat_bae.DrawningObjects
if (Boat.Wing) if (Boat.Wing)
{ {
//вёсла //вёсла
g.FillRectangle(additionalBrush, _startPosX + 35, _startPosY - 5, 5, 65); g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 60, 5, 100);
g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY + 60, 12, 8); g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 60, 12, 8);
g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY - 5, 12, 8); g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 155, 12, 8);
} }
//флажок base.DrawTransport(g);
Point[] points;
//кресла
if (Boat.Body) if (Boat.Body)
{ {
points = new Point[] g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 90, 25, 40);
{ }
new Point(Convert.ToInt32(_startPosX+70),Convert.ToInt32(_startPosY-20)),
new Point(Convert.ToInt32(_startPosX+70),Convert.ToInt32(_startPosY+10)),
new Point(Convert.ToInt32(_startPosX+90),Convert.ToInt32(_startPosY)),
new Point(Convert.ToInt32(_startPosX+90),Convert.ToInt32(_startPosY-20)),
};
g.FillPolygon(additionalBrush, points);
g.DrawPolygon(pen, points);
}
base.DrawTransport(g);
} }
} }
} }

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

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae
{
internal static class ExtentionBoat
{
// Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':';
// Создание объекта из строки
public static Drawningboat? CreateDrawningBoat(this string info, char _separatorForObject, int _pictureWidth, int _pictureHeight)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new Drawningboat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), _pictureWidth, _pictureHeight);
}
if (strs.Length == 7)
{
return new DrawningMotorBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), _pictureWidth, _pictureHeight);
}
return null;
}
// Получение данных для сохранения в файл
public static string GetDataForSave(this Drawningboat drawningBoat, char _separatorForObject)
{
var boat = drawningBoat.EntityBoat;
var str =
$"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntityMotorBoat motorBoat)
{
return str;
}
return
$"{str}{_separatorForObject}{motorBoat.AdditionalColor.Name}{_separatorForObject}{motorBoat.Body}{_separatorForObject}{motorBoat.Wing}{_separatorForObject}";
}
}
}

View File

@@ -37,14 +37,23 @@
ButtonRemoveBoat = new Button(); ButtonRemoveBoat = new Button();
ButtonRefreshCollection = new Button(); ButtonRefreshCollection = new Button();
textBoxBoat = new TextBox(); textBoxBoat = new TextBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
// //
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;
// //
@@ -52,16 +61,16 @@
// //
listBoxStorages.FormattingEnabled = true; listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 25; listBoxStorages.ItemHeight = 25;
listBoxStorages.Location = new Point(935, 146); listBoxStorages.Location = new Point(935, 130);
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(231, 129); listBoxStorages.Size = new Size(231, 79);
listBoxStorages.TabIndex = 1; listBoxStorages.TabIndex = 1;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged; listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
// //
// ButtonAddObject // ButtonAddObject
// //
ButtonAddObject.BackColor = SystemColors.ButtonHighlight; ButtonAddObject.BackColor = SystemColors.ButtonHighlight;
ButtonAddObject.Location = new Point(935, 102); ButtonAddObject.Location = new Point(935, 86);
ButtonAddObject.Name = "ButtonAddObject"; ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(231, 38); ButtonAddObject.Size = new Size(231, 38);
ButtonAddObject.TabIndex = 2; ButtonAddObject.TabIndex = 2;
@@ -71,7 +80,7 @@
// //
// textBoxStorageName // textBoxStorageName
// //
textBoxStorageName.Location = new Point(935, 65); textBoxStorageName.Location = new Point(935, 49);
textBoxStorageName.Name = "textBoxStorageName"; textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(231, 31); textBoxStorageName.Size = new Size(231, 31);
textBoxStorageName.TabIndex = 3; textBoxStorageName.TabIndex = 3;
@@ -79,7 +88,7 @@
// ButtonDelObject // ButtonDelObject
// //
ButtonDelObject.BackColor = SystemColors.ButtonHighlight; ButtonDelObject.BackColor = SystemColors.ButtonHighlight;
ButtonDelObject.Location = new Point(935, 281); ButtonDelObject.Location = new Point(935, 215);
ButtonDelObject.Name = "ButtonDelObject"; ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(231, 34); ButtonDelObject.Size = new Size(231, 34);
ButtonDelObject.TabIndex = 4; ButtonDelObject.TabIndex = 4;
@@ -127,11 +136,76 @@
textBoxBoat.Size = new Size(173, 31); textBoxBoat.Size = new Size(173, 31);
textBoxBoat.TabIndex = 8; textBoxBoat.TabIndex = 8;
// //
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(24, 24);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1178, 33);
menuStrip1.TabIndex = 9;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(69, 29);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(212, 34);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenu_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(212, 34);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenu_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByType
//
ButtonSortByType.BackColor = SystemColors.ButtonHighlight;
ButtonSortByType.Location = new Point(935, 284);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(231, 34);
ButtonSortByType.TabIndex = 10;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = false;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.BackColor = SystemColors.ButtonHighlight;
ButtonSortByColor.Location = new Point(935, 329);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(231, 34);
ButtonSortByColor.TabIndex = 11;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = false;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormBoatCollection // FormBoatCollection
// //
AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1178, 644); ClientSize = new Size(1178, 644);
Controls.Add(ButtonSortByColor);
Controls.Add(ButtonSortByType);
Controls.Add(menuStrip1);
Controls.Add(textBoxBoat); Controls.Add(textBoxBoat);
Controls.Add(ButtonRefreshCollection); Controls.Add(ButtonRefreshCollection);
Controls.Add(ButtonRemoveBoat); Controls.Add(ButtonRemoveBoat);
@@ -141,9 +215,12 @@
Controls.Add(ButtonAddObject); Controls.Add(ButtonAddObject);
Controls.Add(listBoxStorages); Controls.Add(listBoxStorages);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip1;
Name = "FormBoatCollection"; Name = "FormBoatCollection";
Text = "FormBoatCollection"; Text = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@@ -159,5 +236,13 @@
private Button ButtonRemoveBoat; private Button ButtonRemoveBoat;
private Button ButtonRefreshCollection; private Button ButtonRefreshCollection;
private TextBox textBoxBoat; private TextBox textBoxBoat;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
} }
} }

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,10 @@ 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;
using System.Numerics;
namespace ProjectBoat_bae namespace ProjectBoat_bae
{ {
@@ -19,10 +24,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,105 +59,135 @@ 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("Input not complete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text.ToString());
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
} }
// Удаление набора // Удаление набора
private void ButtonDelObject_Click(object sender, EventArgs e) private void ButtonDelObject_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Delete Object {name}?", "Deleting",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(name);
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
} }
} }
// Добавление объекта в набор // Добавление объекта в набор
private void ButtonAddBoat_Click(object sender, EventArgs e) private void ButtonAddBoat_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) return;
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return; if (obj == null)
{
FormBoatConfig form = new FormBoatConfig(); return;
}
form.AddEvent(AddBoat); FormBoatConfig formPlaneConfig = new FormBoatConfig();
form.Show(); formPlaneConfig.AddEvent(AddBoat);
formPlaneConfig.Show();
} }
private void AddBoat(Drawningboat boat) private void AddBoat(Drawningboat boat)
{ {
boat._pictureWidth = pictureBoxCollection.Width;
boat._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
if (obj + boat) if (listBoxStorages.SelectedIndex == -1)
{ {
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + boat;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats(); pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"plane added in set {listBoxStorages.SelectedItem.ToString()}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"plane not added in set {listBoxStorages.SelectedItem.ToString()}");
} }
} }
//удаление объекта //удаление объекта
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("Delete Object?", "Delete", 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); int pos = Convert.ToInt32(textBoxBoat.Text);
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Object deleted");
pictureBoxCollection.Image = obj.ShowBoats(); pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"plane deleted in set {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Object not deleted");
_logger.LogWarning($"plane not deleted in set {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (BoatNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"PlaneNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Not input");
_logger.LogWarning("Not input");
} }
} }
// Обновление // Обновление
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_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;
@@ -161,5 +201,63 @@ namespace ProjectBoat_bae
pictureBoxCollection.Image = pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats(); _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
} }
//сохранение
private void SaveToolStripMenu_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//загрузка
private void LoadToolStripMenu_Click(object sender, EventArgs args)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
public void CompareBoats(IComparer<Drawningboat?> comparer)
{
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
} }
} }

View File

@@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>176, 16</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>363, 21</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>91</value>
</metadata>
</root> </root>

View File

@@ -64,9 +64,9 @@
// //
// pictureBoxObject // pictureBoxObject
// //
pictureBoxObject.Location = new Point(38, 76); pictureBoxObject.Location = new Point(38, 30);
pictureBoxObject.Name = "pictureBoxObject"; pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(388, 282); pictureBoxObject.Size = new Size(388, 328);
pictureBoxObject.TabIndex = 0; pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false; pictureBoxObject.TabStop = false;
// //
@@ -237,9 +237,9 @@
checkBoxBoat.AutoSize = true; checkBoxBoat.AutoSize = true;
checkBoxBoat.Location = new Point(21, 176); checkBoxBoat.Location = new Point(21, 176);
checkBoxBoat.Name = "checkBoxBoat"; checkBoxBoat.Name = "checkBoxBoat";
checkBoxBoat.Size = new Size(246, 29); checkBoxBoat.Size = new Size(240, 29);
checkBoxBoat.TabIndex = 6; checkBoxBoat.TabIndex = 6;
checkBoxBoat.Text = "Признак наличия флажка"; checkBoxBoat.Text = "Признак наличия кресел";
checkBoxBoat.UseVisualStyleBackColor = true; checkBoxBoat.UseVisualStyleBackColor = true;
// //
// Weight // Weight
@@ -279,7 +279,7 @@
LabelAdditionalColor.AllowDrop = true; LabelAdditionalColor.AllowDrop = true;
LabelAdditionalColor.AutoSize = true; LabelAdditionalColor.AutoSize = true;
LabelAdditionalColor.BorderStyle = BorderStyle.FixedSingle; LabelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
LabelAdditionalColor.Location = new Point(333, 38); LabelAdditionalColor.Location = new Point(333, 0);
LabelAdditionalColor.Name = "LabelAdditionalColor"; LabelAdditionalColor.Name = "LabelAdditionalColor";
LabelAdditionalColor.Size = new Size(93, 27); LabelAdditionalColor.Size = new Size(93, 27);
LabelAdditionalColor.TabIndex = 1; LabelAdditionalColor.TabIndex = 1;
@@ -292,7 +292,7 @@
LabelColor.AllowDrop = true; LabelColor.AllowDrop = true;
LabelColor.AutoSize = true; LabelColor.AutoSize = true;
LabelColor.BorderStyle = BorderStyle.FixedSingle; LabelColor.BorderStyle = BorderStyle.FixedSingle;
LabelColor.Location = new Point(38, 38); LabelColor.Location = new Point(38, 0);
LabelColor.Name = "LabelColor"; LabelColor.Name = "LabelColor";
LabelColor.Size = new Size(53, 27); LabelColor.Size = new Size(53, 27);
LabelColor.TabIndex = 0; LabelColor.TabIndex = 0;

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

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae.Generics
{
internal class BoatCompareByColor : IComparer<Drawningboat?>
{
public int Compare(Drawningboat? x, Drawningboat? y)
{
if (x == null || x.EntityBoat == null)
throw new NotImplementedException(nameof(x));
if (y == null || y.EntityBoat == null)
throw new NotImplementedException(nameof(y));
var bodyColor = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodyColor != 0) return bodyColor;
if (x.EntityBoat is EntityMotorBoat &&
y.EntityBoat is EntityMotorBoat)
{
var addcolor = (x.EntityBoat as EntityMotorBoat).AdditionalColor.Name.CompareTo((y.EntityBoat
as EntityMotorBoat).AdditionalColor.Name);
if (addcolor != 0) return addcolor;
}
return 1;
}
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
namespace ProjectBoat_bae.Generics
{
internal class BoatCompareByType : IComparer<Drawningboat?>
{
public int Compare(Drawningboat? x, Drawningboat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Generics
{
internal class BoatsCollectionInfo : IEquatable<BoatsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public BoatsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(BoatsCollectionInfo other)
{
if (Name != other?.Name)
throw new NotImplementedException(nameof(Name));
return true;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override string ToString()
{
return Name;
}
}
}

View File

@@ -20,10 +20,10 @@ namespace ProjectBoat_bae.Generics
/// <summary> /// <summary>
/// Размер занимаемого объектом места (ширина) /// Размер занимаемого объектом места (ширина)
/// </summary> /// </summary>
private readonly int _placeSizeWidth = 100; private readonly int _placeSizeWidth = 200;
// Размер занимаемого объектом места (высота) // Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 70; private readonly int _placeSizeHeight = 200;
// Набор объектов // Набор объектов
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
@@ -45,7 +45,7 @@ namespace ProjectBoat_bae.Generics
{ {
return false; return false;
} }
return (bool)collect._collection.Insert(obj); return collect._collection.Insert(obj, new DrawingBoatEqutables());
} }
// Перегрузка оператора вычитания // Перегрузка оператора вычитания
@@ -108,5 +108,9 @@ namespace ProjectBoat_bae.Generics
} }
} }
} }
// Получение объектов коллекции
public IEnumerable<T?> GetBoats => _collection.GetBoats();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
} }
} }

View File

@@ -1,17 +1,21 @@
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;
using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.MovementStrategy; using ProjectBoat_bae.MovementStrategy;
using ProjectBoat_bae.Entities;
using ProjectBoat_bae.Exceptions;
namespace ProjectBoat_bae.Generics namespace ProjectBoat_bae.Generics
{ {
internal class BoatsGenericStorage internal class BoatsGenericStorage
{ {
readonly Dictionary<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> _boatStorages; readonly Dictionary<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> _boatStorages;
public List<string> Keys => _boatStorages.Keys.ToList(); public List<string> Keys => _boatStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
@@ -24,6 +28,7 @@ namespace ProjectBoat_bae.Generics
} }
public void AddSet(string name) public void AddSet(string name)
{ {
if (_boatStorages.ContainsKey(name)) return; if (_boatStorages.ContainsKey(name)) return;
_boatStorages[name] = new BoatsGenericCollection<Drawningboat, DrawningObjectBoat>(_pictureWidth, _pictureHeight); _boatStorages[name] = new BoatsGenericCollection<Drawningboat, DrawningObjectBoat>(_pictureWidth, _pictureHeight);
} }
@@ -43,5 +48,103 @@ namespace ProjectBoat_bae.Generics
return null; return null;
} }
} }
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (Drawningboat? elem in record.Value.GetBoats)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new ArgumentException("Нет объекта для добавления");
}
if (str.StartsWith("BoatsStorage"))
{
throw new InvalidDataException("Неверный формат данных");
}
_boatStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
return;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<Drawningboat, DrawningObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
if (!(collection + boat))
{
try
{
_ = collection + boat;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
}
_boatStorages.Add(record[0], collection);
}
}
}
} }
} }

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae.Generics
{
internal class DrawingBoatEqutables : IEqualityComparer<Drawningboat?>
{
public bool Equals(Drawningboat? x, Drawningboat? y)
{
if (x == null || x.EntityBoat == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityBoat == null)
throw new ArgumentNullException(nameof(y));
if (x.GetType().Name != y.GetType().Name)
return false;
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
return false;
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
return false;
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
return false;
// to do logic for "сравнения" additional parameters :)
if (x is DrawningMotorBoat && y is DrawningMotorBoat)
{
if ((x.EntityBoat as EntityMotorBoat).AdditionalColor != (y.EntityBoat as EntityMotorBoat).AdditionalColor)
{
return false;
}
if ((x.EntityBoat as EntityMotorBoat).Body != (y.EntityBoat as EntityMotorBoat).Body)
{
return false;
}
if ((x.EntityBoat as EntityMotorBoat).Wing != (y.EntityBoat as EntityMotorBoat).Wing)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] Drawningboat obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -4,6 +4,8 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectBoat_bae.Exceptions;
namespace ProjectBoat_bae.Generics namespace ProjectBoat_bae.Generics
{ {
internal class SetGeneric<T> where T : class internal class SetGeneric<T> where T : class
@@ -14,6 +16,8 @@ namespace ProjectBoat_bae.Generics
// Максимальное количество объектов в списке // Максимальное количество объектов в списке
private readonly int _maxCount; private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
// Конструктор // Конструктор
public SetGeneric(int count) public SetGeneric(int count)
{ {
@@ -21,27 +25,47 @@ namespace ProjectBoat_bae.Generics
_places = new List<T?>(_maxCount); _places = new List<T?>(_maxCount);
} }
public bool Insert(T boat) public bool Insert(T boat, IEqualityComparer<T?>? equal = null)
{ {
if (equal != null)
{
foreach (var secondBoat in _places)
{
if (equal.Equals(boat, secondBoat))
{
throw new Exception("Такой объект уже есть в коллекции");
}
}
}
return Insert(boat, 0); return Insert(boat, 0);
} }
public bool Insert(T boat, int position) public bool Insert(T boat, int position, IEqualityComparer<T?>? equal = null)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return false; throw new StorageOverflowException("Impossible to insert");
if (Count >= _maxCount) if (Count >= _maxCount)
return false; throw new StorageOverflowException(_maxCount);
_places.Insert(0, boat); if (equal != null)
{
foreach (var secondBoat in _places)
{
if (equal.Equals(boat, secondBoat))
{
throw new ApplicationException("Такой объект уже есть в коллекции");
}
}
}
_places.Insert(position, boat);
return true; return true;
} }
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position > _maxCount) if (position >= Count || position < 0)
return false; throw new BoatNotFoundException("Invalid operation");
if (position >= Count) if (_places[position] == null)
return false; throw new BoatNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; 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