5 Commits
lab5 ... 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
Marselchi
8b75e1f20b А нет, косяк есть 2023-12-03 15:17:28 +04:00
Marselchi
feeb709fd2 Фулл 6 лаба(надеюсь без косяков) 2023-12-03 15:14:23 +04:00
16 changed files with 760 additions and 68 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,69 @@
using Liner.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Liner.Drawing
{
/// <summary>
/// Расширение для класса EntityLiner
/// </summary>
public static class ExtentionDrawningLiner
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingLiner? CreateDrawingLiner(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingLiner(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingBigLiner(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingLiner">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingLiner drawingLiner,
char separatorForObject)
{
var liner = drawingLiner.EntityLiner;
if (liner == null)
{
return string.Empty;
}
var str =
$"{liner.Speed}{separatorForObject}{liner.Weight}{separatorForObject}{liner.BottomColor.Name}";
if (liner is not EntityBigLiner bigLiner)
{
return str;
}
return
$"{str}{separatorForObject}{bigLiner.BodyColor.Name}{separatorForObject}{bigLiner.SwimmingPool}{separatorForObject}" +
$"{bigLiner.Deck}";
}
}
}

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() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
buttonSortByType = new Button();
buttonSortByColor = new Button();
Storages = new GroupBox(); Storages = new GroupBox();
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
buttonDeleteSet = new Button(); buttonDeleteSet = new Button();
@@ -39,34 +41,69 @@
textBoxNumber = new TextBox(); textBoxNumber = new TextBox();
buttonAddLiner = new Button(); buttonAddLiner = new Button();
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
FileMenuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
Storages.SuspendLayout(); Storages.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
FileMenuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
// //
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(Storages); groupBoxTools.Controls.Add(Storages);
groupBoxTools.Controls.Add(buttonRefreshCollection); groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(buttonDeleteLiner); groupBoxTools.Controls.Add(buttonDeleteLiner);
groupBoxTools.Controls.Add(textBoxNumber); groupBoxTools.Controls.Add(textBoxNumber);
groupBoxTools.Controls.Add(buttonAddLiner); 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.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.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Tools"; 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
// //
Storages.Controls.Add(listBoxStorages); Storages.Controls.Add(listBoxStorages);
Storages.Controls.Add(buttonDeleteSet); Storages.Controls.Add(buttonDeleteSet);
Storages.Controls.Add(textBoxStorageName); Storages.Controls.Add(textBoxStorageName);
Storages.Controls.Add(buttonAddStorage); Storages.Controls.Add(buttonAddStorage);
Storages.Location = new Point(7, 19); Storages.Location = new Point(8, 29);
Storages.Margin = new Padding(3, 4, 3, 4);
Storages.Name = "Storages"; Storages.Name = "Storages";
Storages.Size = new Size(200, 276); Storages.Padding = new Padding(3, 4, 3, 4);
Storages.Size = new Size(229, 364);
Storages.TabIndex = 4; Storages.TabIndex = 4;
Storages.TabStop = false; Storages.TabStop = false;
Storages.Text = "Sets"; Storages.Text = "Sets";
@@ -74,18 +111,20 @@
// listBoxStorages // listBoxStorages
// //
listBoxStorages.FormattingEnabled = true; listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15; listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(6, 113); listBoxStorages.Location = new Point(7, 151);
listBoxStorages.Margin = new Padding(3, 4, 3, 4);
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(187, 109); listBoxStorages.Size = new Size(213, 144);
listBoxStorages.TabIndex = 4; listBoxStorages.TabIndex = 4;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged; listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
// //
// buttonDeleteSet // 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.Name = "buttonDeleteSet";
buttonDeleteSet.Size = new Size(184, 30); buttonDeleteSet.Size = new Size(210, 40);
buttonDeleteSet.TabIndex = 3; buttonDeleteSet.TabIndex = 3;
buttonDeleteSet.Text = "Delete Set"; buttonDeleteSet.Text = "Delete Set";
buttonDeleteSet.UseVisualStyleBackColor = true; buttonDeleteSet.UseVisualStyleBackColor = true;
@@ -93,16 +132,18 @@
// //
// textBoxStorageName // 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.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(139, 23); textBoxStorageName.Size = new Size(158, 27);
textBoxStorageName.TabIndex = 2; textBoxStorageName.TabIndex = 2;
// //
// buttonAddStorage // 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.Name = "buttonAddStorage";
buttonAddStorage.Size = new Size(184, 30); buttonAddStorage.Size = new Size(210, 40);
buttonAddStorage.TabIndex = 1; buttonAddStorage.TabIndex = 1;
buttonAddStorage.Text = "Add Set"; buttonAddStorage.Text = "Add Set";
buttonAddStorage.UseVisualStyleBackColor = true; buttonAddStorage.UseVisualStyleBackColor = true;
@@ -110,9 +151,10 @@
// //
// buttonRefreshCollection // 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.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(194, 40); buttonRefreshCollection.Size = new Size(222, 53);
buttonRefreshCollection.TabIndex = 3; buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Refresh Collection"; buttonRefreshCollection.Text = "Refresh Collection";
buttonRefreshCollection.UseVisualStyleBackColor = true; buttonRefreshCollection.UseVisualStyleBackColor = true;
@@ -120,9 +162,10 @@
// //
// buttonDeleteLiner // 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.Name = "buttonDeleteLiner";
buttonDeleteLiner.Size = new Size(194, 40); buttonDeleteLiner.Size = new Size(222, 53);
buttonDeleteLiner.TabIndex = 2; buttonDeleteLiner.TabIndex = 2;
buttonDeleteLiner.Text = "Delete Liner"; buttonDeleteLiner.Text = "Delete Liner";
buttonDeleteLiner.UseVisualStyleBackColor = true; buttonDeleteLiner.UseVisualStyleBackColor = true;
@@ -130,16 +173,18 @@
// //
// textBoxNumber // 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.Name = "textBoxNumber";
textBoxNumber.Size = new Size(139, 23); textBoxNumber.Size = new Size(158, 27);
textBoxNumber.TabIndex = 1; textBoxNumber.TabIndex = 1;
// //
// buttonAddLiner // 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.Name = "buttonAddLiner";
buttonAddLiner.Size = new Size(194, 40); buttonAddLiner.Size = new Size(222, 53);
buttonAddLiner.TabIndex = 0; buttonAddLiner.TabIndex = 0;
buttonAddLiner.Text = "Add Liner"; buttonAddLiner.Text = "Add Liner";
buttonAddLiner.UseVisualStyleBackColor = true; buttonAddLiner.UseVisualStyleBackColor = true;
@@ -147,19 +192,64 @@
// //
// pictureBoxCollection // pictureBoxCollection
// //
pictureBoxCollection.Location = new Point(2, 0); pictureBoxCollection.Location = new Point(2, 36);
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(731, 565); pictureBoxCollection.Size = new Size(835, 717);
pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false; 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.Padding = new Padding(7, 3, 0, 3);
FileMenuStrip.Size = new Size(1087, 30);
FileMenuStrip.TabIndex = 2;
FileMenuStrip.Text = "FileMenuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(49, 24);
FileToolStripMenuItem.Text = "FILE";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(130, 26);
SaveToolStripMenuItem.Text = "SAVE";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(130, 26);
LoadToolStripMenuItem.Text = "LOAD";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.FileName = "saveFile";
saveFileDialog.Filter = "txt file | *.txt";
//
// FormLinerCollection // FormLinerCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(951, 568); ClientSize = new Size(1087, 757);
Controls.Add(FileMenuStrip);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
MainMenuStrip = FileMenuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormLinerCollection"; Name = "FormLinerCollection";
Text = "Liner Collection"; Text = "Liner Collection";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -167,7 +257,10 @@
Storages.ResumeLayout(false); Storages.ResumeLayout(false);
Storages.PerformLayout(); Storages.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
FileMenuStrip.ResumeLayout(false);
FileMenuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -183,5 +276,13 @@
private Button buttonDeleteSet; private Button buttonDeleteSet;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private Button buttonAddStorage; private Button buttonAddStorage;
private MenuStrip FileMenuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
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.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using Liner.Exceptions;
using System.Xml.Linq;
namespace Liner namespace Liner
{ {
/// <summary> /// <summary>
@@ -23,12 +25,17 @@ namespace Liner
/// </summary> /// </summary>
private readonly LinersGenericStorage _storage; private readonly LinersGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormLinerCollection() public FormLinerCollection(ILogger<FormLinerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new LinersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new LinersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
@@ -39,6 +46,7 @@ namespace Liner
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
return; return;
} }
var formLinerConfig = new FormLinerConfig(); var formLinerConfig = new FormLinerConfig();
@@ -50,21 +58,37 @@ namespace Liner
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Добавление лайнера не удалось (нет хранилища)");
return; return;
} }
if ((obj + liner) != -1) try
{ {
MessageBox.Show("Объект добавлен"); if ((obj + liner) != -1)
pictureBoxCollection.Image = obj.ShowLiners(); {
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> /// <summary>
@@ -74,39 +98,56 @@ namespace Liner
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveLiner_Click(object sender, EventArgs e) private void ButtonRemoveLiner_Click(object sender, EventArgs e)
{ {
int pos; int pos = 0; //фикс недосмотра
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Удаление лайнера не удалось (индекс вне границ)");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Удаление лайнера не удалось (нет хранилища)");
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
_logger.LogWarning($"Удаление лайнера не удалось (выбран вариант 'Нет')");
return; return;
} }
if (textBoxNumber.Text != "") if (textBoxNumber.Text != "") //улучшил проверку
{ {
pos = Convert.ToInt32(textBoxNumber.Text); if(!int.TryParse(textBoxNumber.Text, out pos))
{
_logger.LogWarning($"Удаление лайнера не удалось (неверный формат)");
return;
}
} }
else else
{ {
_logger.LogWarning($"Удаление лайнера не удалось (пустое поле ввода)");
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
return; return;
} }
pos = 0; try
if (obj - pos)
{ {
MessageBox.Show("Объект удален"); if (obj - pos)
pictureBoxCollection.Image = obj.ShowLiners(); {
_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> /// <summary>
@@ -118,11 +159,13 @@ namespace Liner
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
_logger.LogWarning($"Обновление набора не удалось (не все данные заполнены)");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text} ");
ReloadObjects(); ReloadObjects();
} }
/// <summary> /// <summary>
@@ -144,12 +187,15 @@ namespace Liner
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Удаление набора не удалось (индекс вне границ)");
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 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(); ReloadObjects();
} }
} }
@@ -162,13 +208,16 @@ namespace Liner
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Обновление объектов не удалось (индекс вне границ)");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Обновление объектов не удалось (нет хранилища)");
return; return;
} }
_logger.LogInformation($"Обновление объектов успешно");
pictureBoxCollection.Image = obj.ShowLiners(); pictureBoxCollection.Image = obj.ShowLiners();
} }
/// <summary> /// <summary>
@@ -180,7 +229,7 @@ namespace Liner
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) 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)) if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{ {
@@ -191,5 +240,72 @@ namespace Liner
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
} }
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Cохранение успешно");
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение не удалось {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Загрузка успешна");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
catch (Exception ex)
{
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="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, 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="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"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
@@ -117,4 +117,13 @@
<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="FileMenuStrip.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>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>284, 17</value>
</metadata>
</root> </root>

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

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

View File

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

View File

@@ -1,4 +1,5 @@
using System; using Liner.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -39,14 +40,15 @@ namespace Liner.Generics
/// </summary> /// </summary>
/// <param name="liner">Добавляемый лайнер</param> /// <param name="liner">Добавляемый лайнер</param>
/// <returns></returns> /// <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); throw new StorageOverflowException(_places.Count);
return 0;
} }
return -1; return Insert(liner,0, equal);
return 0;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@@ -54,14 +56,22 @@ namespace Liner.Generics
/// <param name="liner">Добавляемый лайнер</param> /// <param name="liner">Добавляемый лайнер</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <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); throw new StorageOverflowException(_places.Count);
return position;
} }
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> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@@ -75,8 +85,9 @@ namespace Liner.Generics
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }
return false; throw new LinerNotFoundException(position);
} }
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Получение объекта из набора по позиции /// Получение объекта из набора по позиции
/// </summary> /// </summary>
@@ -94,9 +105,13 @@ namespace Liner.Generics
} }
set 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\**" /> <None Remove="MovingStrategy\**" />
</ItemGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <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 namespace Liner
{ {
internal static class Program internal static class Program
@@ -11,7 +18,28 @@ namespace Liner
// 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 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);
});
} }
} }
} }