3 Commits
lab6 ... lab8

Author SHA1 Message Date
Marselchi
5af581e096 Фулл 8 лаба надеюсь 2023-12-18 16:11:55 +04:00
Marselchi
8c7a4a2c6b Произошел косяк 2023-12-18 15:00:17 +04:00
Marselchi
7e1761c5c8 Фулл лаба 7(надеюсь без косяков) 2023-12-04 18:40:18 +04:00
15 changed files with 522 additions and 102 deletions

20
Liner/AppSettings.json Normal file
View File

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

View File

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

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Liner.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) { }
protected StorageOverflowException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -29,6 +29,8 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
buttonSortByType = new Button();
buttonSortByColor = new Button();
Storages = new GroupBox();
listBoxStorages = new ListBox();
buttonDeleteSet = new Button();
@@ -53,27 +55,55 @@
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(Storages);
groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(buttonDeleteLiner);
groupBoxTools.Controls.Add(textBoxNumber);
groupBoxTools.Controls.Add(buttonAddLiner);
groupBoxTools.Location = new Point(739, 0);
groupBoxTools.Location = new Point(845, 0);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(211, 565);
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(241, 753);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Tools";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(28, 413);
buttonSortByType.Margin = new Padding(3, 4, 3, 4);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(190, 41);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Sort By Type";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(28, 462);
buttonSortByColor.Margin = new Padding(3, 4, 3, 4);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(190, 41);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Sort By Color";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// Storages
//
Storages.Controls.Add(listBoxStorages);
Storages.Controls.Add(buttonDeleteSet);
Storages.Controls.Add(textBoxStorageName);
Storages.Controls.Add(buttonAddStorage);
Storages.Location = new Point(7, 22);
Storages.Location = new Point(8, 29);
Storages.Margin = new Padding(3, 4, 3, 4);
Storages.Name = "Storages";
Storages.Size = new Size(200, 273);
Storages.Padding = new Padding(3, 4, 3, 4);
Storages.Size = new Size(229, 364);
Storages.TabIndex = 4;
Storages.TabStop = false;
Storages.Text = "Sets";
@@ -81,18 +111,20 @@
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(6, 113);
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(7, 151);
listBoxStorages.Margin = new Padding(3, 4, 3, 4);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(187, 109);
listBoxStorages.Size = new Size(213, 144);
listBoxStorages.TabIndex = 4;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// buttonDeleteSet
//
buttonDeleteSet.Location = new Point(10, 228);
buttonDeleteSet.Location = new Point(11, 304);
buttonDeleteSet.Margin = new Padding(3, 4, 3, 4);
buttonDeleteSet.Name = "buttonDeleteSet";
buttonDeleteSet.Size = new Size(184, 30);
buttonDeleteSet.Size = new Size(210, 40);
buttonDeleteSet.TabIndex = 3;
buttonDeleteSet.Text = "Delete Set";
buttonDeleteSet.UseVisualStyleBackColor = true;
@@ -100,16 +132,18 @@
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(34, 39);
textBoxStorageName.Location = new Point(39, 52);
textBoxStorageName.Margin = new Padding(3, 4, 3, 4);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(139, 23);
textBoxStorageName.Size = new Size(158, 27);
textBoxStorageName.TabIndex = 2;
//
// buttonAddStorage
//
buttonAddStorage.Location = new Point(10, 68);
buttonAddStorage.Location = new Point(11, 91);
buttonAddStorage.Margin = new Padding(3, 4, 3, 4);
buttonAddStorage.Name = "buttonAddStorage";
buttonAddStorage.Size = new Size(184, 30);
buttonAddStorage.Size = new Size(210, 40);
buttonAddStorage.TabIndex = 1;
buttonAddStorage.Text = "Add Set";
buttonAddStorage.UseVisualStyleBackColor = true;
@@ -117,9 +151,10 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(11, 501);
buttonRefreshCollection.Location = new Point(13, 691);
buttonRefreshCollection.Margin = new Padding(3, 4, 3, 4);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(194, 40);
buttonRefreshCollection.Size = new Size(222, 53);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Refresh Collection";
buttonRefreshCollection.UseVisualStyleBackColor = true;
@@ -127,9 +162,10 @@
//
// buttonDeleteLiner
//
buttonDeleteLiner.Location = new Point(11, 408);
buttonDeleteLiner.Location = new Point(13, 607);
buttonDeleteLiner.Margin = new Padding(3, 4, 3, 4);
buttonDeleteLiner.Name = "buttonDeleteLiner";
buttonDeleteLiner.Size = new Size(194, 40);
buttonDeleteLiner.Size = new Size(222, 53);
buttonDeleteLiner.TabIndex = 2;
buttonDeleteLiner.Text = "Delete Liner";
buttonDeleteLiner.UseVisualStyleBackColor = true;
@@ -137,16 +173,18 @@
//
// textBoxNumber
//
textBoxNumber.Location = new Point(41, 368);
textBoxNumber.Location = new Point(47, 572);
textBoxNumber.Margin = new Padding(3, 4, 3, 4);
textBoxNumber.Name = "textBoxNumber";
textBoxNumber.Size = new Size(139, 23);
textBoxNumber.Size = new Size(158, 27);
textBoxNumber.TabIndex = 1;
//
// buttonAddLiner
//
buttonAddLiner.Location = new Point(11, 313);
buttonAddLiner.Location = new Point(13, 511);
buttonAddLiner.Margin = new Padding(3, 4, 3, 4);
buttonAddLiner.Name = "buttonAddLiner";
buttonAddLiner.Size = new Size(194, 40);
buttonAddLiner.Size = new Size(222, 53);
buttonAddLiner.TabIndex = 0;
buttonAddLiner.Text = "Add Liner";
buttonAddLiner.UseVisualStyleBackColor = true;
@@ -154,18 +192,21 @@
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(2, 27);
pictureBoxCollection.Location = new Point(2, 36);
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(731, 538);
pictureBoxCollection.Size = new Size(835, 717);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// FileMenuStrip
//
FileMenuStrip.ImageScalingSize = new Size(20, 20);
FileMenuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
FileMenuStrip.Location = new Point(0, 0);
FileMenuStrip.Name = "FileMenuStrip";
FileMenuStrip.Size = new Size(951, 24);
FileMenuStrip.Padding = new Padding(7, 3, 0, 3);
FileMenuStrip.Size = new Size(1087, 30);
FileMenuStrip.TabIndex = 2;
FileMenuStrip.Text = "FileMenuStrip";
//
@@ -173,20 +214,20 @@
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(40, 20);
FileToolStripMenuItem.Size = new Size(49, 24);
FileToolStripMenuItem.Text = "FILE";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(105, 22);
SaveToolStripMenuItem.Size = new Size(130, 26);
SaveToolStripMenuItem.Text = "SAVE";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(105, 22);
LoadToolStripMenuItem.Size = new Size(130, 26);
LoadToolStripMenuItem.Text = "LOAD";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@@ -201,13 +242,14 @@
//
// FormLinerCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(951, 568);
ClientSize = new Size(1087, 757);
Controls.Add(FileMenuStrip);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
MainMenuStrip = FileMenuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormLinerCollection";
Text = "Liner Collection";
groupBoxTools.ResumeLayout(false);
@@ -240,5 +282,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@@ -10,7 +10,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using Liner.Exceptions;
using System.Xml.Linq;
namespace Liner
{
/// <summary>
@@ -23,12 +25,17 @@ namespace Liner
/// </summary>
private readonly LinersGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormLinerCollection()
public FormLinerCollection(ILogger<FormLinerCollection> logger)
{
InitializeComponent();
_storage = new LinersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Добавление объекта в набор
@@ -39,6 +46,7 @@ namespace Liner
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
return;
}
var formLinerConfig = new FormLinerConfig();
@@ -50,21 +58,37 @@ namespace Liner
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Добавление лайнера не удалось (нет хранилища)");
return;
}
if ((obj + liner) != -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowLiners();
if ((obj + liner) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавление лайнера успешно {listBoxStorages.SelectedItem.ToString()}");
pictureBoxCollection.Image = obj.ShowLiners();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (ApplicationException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Добавление лайнера в {listBoxStorages.SelectedItem.ToString()} не удалось (переполнение коллекции)");
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
@@ -74,39 +98,56 @@ namespace Liner
/// <param name="e"></param>
private void ButtonRemoveLiner_Click(object sender, EventArgs e)
{
int pos;
int pos = 0; //фикс недосмотра
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Удаление лайнера не удалось (индекс вне границ)");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Удаление лайнера не удалось (нет хранилища)");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning($"Удаление лайнера не удалось (выбран вариант 'Нет')");
return;
}
if (textBoxNumber.Text != "")
if (textBoxNumber.Text != "") //улучшил проверку
{
pos = Convert.ToInt32(textBoxNumber.Text);
if(!int.TryParse(textBoxNumber.Text, out pos))
{
_logger.LogWarning($"Удаление лайнера не удалось (неверный формат)");
return;
}
}
else
{
_logger.LogWarning($"Удаление лайнера не удалось (пустое поле ввода)");
MessageBox.Show("Не удалось удалить объект");
return;
}
pos = 0;
if (obj - pos)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowLiners();
if (obj - pos)
{
_logger.LogInformation($"Удаление лайнера успешно {listBoxStorages.SelectedItem.ToString()} {pos}");
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowLiners();
}
else
{
_logger.LogWarning($"Удаление лайнера не удалось(обьект не найден)");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (LinerNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Удаление лайнера не удалось {ex.Message}");
MessageBox.Show(ex.Message);
}
}
/// <summary>
@@ -118,11 +159,13 @@ namespace Liner
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
_logger.LogWarning($"Обновление набора не удалось (не все данные заполнены)");
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text} ");
ReloadObjects();
}
/// <summary>
@@ -144,12 +187,15 @@ namespace Liner
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Удаление набора не удалось (индекс вне границ)");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
_storage.DelSet(name);
_logger.LogInformation($"Удаление набора успешно: {name}");
ReloadObjects();
}
}
@@ -162,13 +208,16 @@ namespace Liner
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Обновление объектов не удалось (индекс вне границ)");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Обновление объектов не удалось (нет хранилища)");
return;
}
_logger.LogInformation($"Обновление объектов успешно");
pictureBoxCollection.Image = obj.ShowLiners();
}
/// <summary>
@@ -180,7 +229,7 @@ namespace Liner
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
@@ -195,15 +244,17 @@ namespace Liner
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Cохранение успешно");
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение не удалось {ex.Message}");
}
}
}
@@ -211,18 +262,50 @@ namespace Liner
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Загрузка успешна");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка не удалась {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareLiners(IComparer<DrawingLiner?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowLiners();
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareLiners(new LinerCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareLiners(new LinerCompareByColor());
}
}

View File

@@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Liner.Drawing;
using Liner.Entities;
namespace Liner.Generics
{
internal class DrawingLinerEqutables : IEqualityComparer<DrawingLiner?>
{
public bool Equals(DrawingLiner? x, DrawingLiner? y)
{
if (x == null || x.EntityLiner == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLiner == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLiner.Speed != y.EntityLiner.Speed)
{
return false;
}
if (x.EntityLiner.Weight != y.EntityLiner.Weight)
{
return false;
}
if (x.EntityLiner.BottomColor != y.EntityLiner.BottomColor)
{
return false;
}
if (x is DrawingBigLiner && y is DrawingBigLiner)
{
EntityBigLiner _LinerX = (EntityBigLiner)x.EntityLiner;
EntityBigLiner _LinerY = (EntityBigLiner)y.EntityLiner;
if (_LinerX.SwimmingPool != _LinerY.SwimmingPool)
{
return false;
}
if (_LinerX.Deck != _LinerY.Deck)
{
return false;
}
if (_LinerX.BodyColor != _LinerY.BodyColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingLiner obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Liner.Generics
{
public class LinerCollectionInfo : IEquatable<LinerCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public LinerCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(LinerCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Liner.Entities;
using Liner.Drawing;
namespace Liner.Generics
{
internal class LinerCompareByColor : IComparer<DrawingLiner?>
{
public int Compare(DrawingLiner? x, DrawingLiner? y)
{
if (x == null || x.EntityLiner == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLiner == null)
{
throw new ArgumentNullException(nameof(y));
}
var bottomColorCompare = x.EntityLiner.BottomColor.Name.CompareTo(y.EntityLiner.BottomColor.Name);
if (bottomColorCompare != 0)
{
return bottomColorCompare;
}
if (x.EntityLiner is EntityBigLiner _entityBigLinerX && y.EntityLiner is EntityBigLiner _entityBigLinerY)
{
var bodyColorCompare = _entityBigLinerX.BodyColor.Name.CompareTo(_entityBigLinerY.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
}
var speedCompare = x.EntityLiner.Speed.CompareTo(y.EntityLiner.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLiner.Weight.CompareTo(y.EntityLiner.Weight);
}
}
}

View File

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

View File

@@ -54,7 +54,11 @@ namespace Liner.Generics
/// Получение объектов коллекции
/// <summary>
public IEnumerable<T?> GetLiners => _collection.GetLiners();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
@@ -66,7 +70,7 @@ namespace Liner.Generics
{
return -1;
}
return collect?._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawingLinerEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания

View File

@@ -16,11 +16,11 @@ namespace Liner.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>> _linerStorages;
readonly Dictionary<LinerCollectionInfo, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>> _linerStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _linerStorages.Keys.ToList();
public List<LinerCollectionInfo> Keys => _linerStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@@ -48,7 +48,7 @@ namespace Liner.Generics
/// <param name="pictureHeight"></param>
public LinersGenericStorage(int pictureWidth, int pictureHeight)
{
_linerStorages = new Dictionary<string, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>>();
_linerStorages = new Dictionary<LinerCollectionInfo, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -58,11 +58,11 @@ namespace Liner.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if(_linerStorages.ContainsKey(name))
if(_linerStorages.ContainsKey(new LinerCollectionInfo(name, string.Empty)))
{
return;
}
_linerStorages.Add(name, new LinerGenericCollection<DrawingLiner, DrawingObjectLiner>(_pictureWidth,_pictureHeight));
_linerStorages.Add(new LinerCollectionInfo(name, string.Empty), new LinerGenericCollection<DrawingLiner, DrawingObjectLiner>(_pictureWidth,_pictureHeight));
}
/// <summary>
/// Удаление набора
@@ -70,9 +70,9 @@ namespace Liner.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_linerStorages.ContainsKey(name))
if (_linerStorages.ContainsKey(new LinerCollectionInfo(name, string.Empty)))
{
_linerStorages.Remove(name);
_linerStorages.Remove(new LinerCollectionInfo(name, string.Empty));
}
}
/// <summary>
@@ -84,7 +84,7 @@ namespace Liner.Generics
{
get
{
if (_linerStorages.ContainsKey(ind)) { return _linerStorages[ind]; }
if (_linerStorages.ContainsKey(new LinerCollectionInfo(ind, string.Empty))) { return _linerStorages[new LinerCollectionInfo(ind, string.Empty)]; }
return null;
}
}
@@ -92,15 +92,14 @@ namespace Liner.Generics
/// Сохранение информации по лайнерам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
foreach (KeyValuePair<LinerCollectionInfo,
LinerGenericCollection<DrawingLiner, DrawingObjectLiner>> record in _linerStorages)
{
StringBuilder records = new();
@@ -108,11 +107,11 @@ namespace Liner.Generics
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
string dataStr = data.ToString();
using (StreamWriter writer = new StreamWriter(filename))
@@ -120,42 +119,36 @@ namespace Liner.Generics
writer.WriteLine("LinerStorage");
writer.WriteLine(dataStr);
}
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 FileNotFoundException("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
{
return false;
throw new NullReferenceException("Нет данных для загрузки");
}
if (!checker.StartsWith("LinerStorage"))
{
return false;
throw new FormatException("Неверный формат данных");
}
_linerStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
while ((strs = reader.ReadLine()) != null) //переделал ужасную логику
{
if (strs == null && firstinit)
return false;
if (strs == null)
break;
if (strs == string.Empty)
break;
firstinit = false;
string name = strs.Split('|')[0];
LinerGenericCollection<DrawingLiner, DrawingObjectLiner> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';').Reverse())
@@ -164,16 +157,18 @@ namespace Liner.Generics
data?.CreateDrawingLiner(_separatorForObject, _pictureWidth, _pictureHeight);
if (liner != null)
{
if (collection + liner == -1)
try
{
return false;
int? tmp = collection + liner;
}
catch (ApplicationException ex)
{
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
}
}
}
_linerStorages.Add(name, collection);
_linerStorages.Add(new LinerCollectionInfo(name, string.Empty), collection);
}
return true;
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Liner.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -39,14 +40,15 @@ namespace Liner.Generics
/// </summary>
/// <param name="liner">Добавляемый лайнер</param>
/// <returns></returns>
public int Insert(T liner)
public int Insert(T liner, IEqualityComparer<T?>? equal = null)
{
if (_places.Count + 1 <= _maxCount)
if (_places.Count >= _maxCount)
{
_places.Insert(0, liner);
return 0;
throw new StorageOverflowException(_places.Count);
}
return -1;
return Insert(liner,0, equal);
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@@ -54,14 +56,22 @@ namespace Liner.Generics
/// <param name="liner">Добавляемый лайнер</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T liner, int position)
public int Insert(T liner, int position, IEqualityComparer<T?>? equal = null)
{
if (_places.Count + 1 <= _maxCount && _places.Count >= position)
if(_places.Count >= _maxCount)
{
_places.Insert(position, liner);
return position;
throw new StorageOverflowException(_places.Count);
}
return -1;
if(position < 0 || position > _places.Count)
{
throw new LinerNotFoundException(position);
}
if (equal != null && _places.Contains(liner, equal))
{
throw new ArgumentException("Этот объект уже существует в коллекции");
}
_places.Insert(position, liner);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@@ -75,8 +85,9 @@ namespace Liner.Generics
_places.RemoveAt(position);
return true;
}
return false;
throw new LinerNotFoundException(position);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
@@ -94,9 +105,13 @@ namespace Liner.Generics
}
set
{
if(_places.Count + 1 <= _maxCount && position >= 0 && _places.Count > position)
try
{
_places[position] = value;
Insert(value, position);
}
catch
{
return;
}
}
}

View File

@@ -14,6 +14,23 @@
<None Remove="MovingStrategy\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.EventSource" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<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.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -1,3 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.IO;
using System.Windows.Forms;
namespace Liner
{
internal static class Program
@@ -11,7 +18,28 @@ namespace Liner
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormLinerCollection());
var services = new ServiceCollection();
ConfigureServices(services);
ApplicationConfiguration.Initialize();
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormLinerCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormLinerCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}AppSettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.AddSerilog(logger);
});
}
}
}