PIbd-11 Kudrinsky O.S. LabWork07 Simple #11

Closed
8floom wants to merge 6 commits from LabWork07 into LabWork06
14 changed files with 328 additions and 120 deletions

View File

@ -1,4 +1,5 @@
using ProjectContainerShip.Drawings;
using System.Linq.Expressions;
namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary>
@ -14,7 +15,7 @@ namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 80;
protected readonly int _placeSizeHeight = 82;
/// <summary>
/// Ширина окна
@ -94,8 +95,12 @@ namespace ProjectContainerShip.CollectionGenericObjects;
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Exceptions;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -40,14 +41,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
@ -56,8 +57,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
@ -65,7 +66,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;

View File

@ -1,4 +1,6 @@

using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip.CollectionGenericObjects
{
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -45,7 +47,8 @@ namespace ProjectContainerShip.CollectionGenericObjects
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0) return null;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
@ -61,7 +64,7 @@ namespace ProjectContainerShip.CollectionGenericObjects
}
++index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
@ -70,8 +73,8 @@ namespace ProjectContainerShip.CollectionGenericObjects
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
return -1;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
@ -97,16 +100,15 @@ namespace ProjectContainerShip.CollectionGenericObjects
}
--index;
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0) {
return null;
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;

View File

@ -32,11 +32,15 @@ public class ShipPortService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20);
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20);
}
}
catch (Exception) { }
if (curWidth > 0)
curWidth--;
else

View File

@ -1,4 +1,6 @@
using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
using System.Numerics;
using System.Text;
namespace ProjectContainerShip.CollectionGenericObjects;
@ -96,12 +98,11 @@ where T : DrawningShip
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
if (File.Exists(filename))
{
@ -139,14 +140,11 @@ where T : DrawningShip
}
}
return true;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
@ -196,6 +194,7 @@ where T : DrawningShip
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>

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 ProjectContainerShip.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -67,9 +67,11 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.ForeColor = Color.Black;
groupBoxTools.Location = new Point(1601, 40);
groupBoxTools.Location = new Point(722, 24);
groupBoxTools.Margin = new Padding(2, 1, 2, 1);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(388, 1072);
groupBoxTools.Padding = new Padding(2, 1, 2, 1);
groupBoxTools.Size = new Size(209, 497);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -83,17 +85,19 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 598);
panelCompanyTools.Location = new Point(2, 275);
panelCompanyTools.Margin = new Padding(2, 1, 2, 1);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(382, 471);
panelCompanyTools.Size = new Size(205, 221);
panelCompanyTools.TabIndex = 10;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(3, 70);
buttonAddShip.Location = new Point(2, 33);
buttonAddShip.Margin = new Padding(2, 1, 2, 1);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(370, 77);
buttonAddShip.Size = new Size(198, 36);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true;
@ -101,19 +105,21 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 201);
maskedTextBox.Location = new Point(2, 94);
maskedTextBox.Margin = new Padding(2, 1, 2, 1);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(370, 39);
maskedTextBox.Size = new Size(201, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(3, 246);
buttonRemoveShip.Location = new Point(2, 115);
buttonRemoveShip.Margin = new Padding(2, 1, 2, 1);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(370, 77);
buttonRemoveShip.Size = new Size(198, 36);
buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true;
@ -122,9 +128,10 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 329);
buttonGoToCheck.Location = new Point(2, 154);
buttonGoToCheck.Margin = new Padding(2, 1, 2, 1);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(370, 77);
buttonGoToCheck.Size = new Size(198, 36);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -133,9 +140,10 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 412);
buttonRefresh.Location = new Point(2, 193);
buttonRefresh.Margin = new Padding(2, 1, 2, 1);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(370, 77);
buttonRefresh.Size = new Size(198, 36);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -143,9 +151,10 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 546);
buttonCreateCompany.Location = new Point(3, 256);
buttonCreateCompany.Margin = new Padding(2, 1, 2, 1);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(370, 46);
buttonCreateCompany.Size = new Size(199, 22);
buttonCreateCompany.TabIndex = 9;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -161,17 +170,19 @@
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 35);
panelStorage.Location = new Point(2, 17);
panelStorage.Margin = new Padding(2, 1, 2, 1);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(382, 459);
panelStorage.Size = new Size(205, 215);
panelStorage.TabIndex = 8;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(39, 91);
radioButtonMassive.Location = new Point(21, 43);
radioButtonMassive.Margin = new Padding(2, 1, 2, 1);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(128, 36);
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 7;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@ -179,9 +190,10 @@
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 387);
buttonCollectionDel.Location = new Point(2, 181);
buttonCollectionDel.Margin = new Padding(2, 1, 2, 1);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(370, 46);
buttonCollectionDel.Size = new Size(199, 22);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
@ -190,16 +202,19 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.Location = new Point(3, 185);
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(2, 87);
listBoxCollection.Margin = new Padding(2, 1, 2, 1);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(370, 196);
listBoxCollection.Size = new Size(201, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 133);
buttonCollectionAdd.Location = new Point(2, 62);
buttonCollectionAdd.Margin = new Padding(2, 1, 2, 1);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(370, 46);
buttonCollectionAdd.Size = new Size(199, 22);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
@ -208,9 +223,10 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(215, 91);
radioButtonList.Location = new Point(116, 43);
radioButtonList.Margin = new Padding(2, 1, 2, 1);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(125, 36);
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@ -218,17 +234,19 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 46);
textBoxCollectionName.Location = new Point(2, 22);
textBoxCollectionName.Margin = new Padding(2, 1, 2, 1);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(370, 39);
textBoxCollectionName.Size = new Size(201, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(69, 11);
labelCollectionName.Location = new Point(37, 5);
labelCollectionName.Margin = new Padding(2, 0, 2, 0);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(251, 32);
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
@ -238,18 +256,20 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 500);
comboBoxSelectorCompany.Location = new Point(3, 234);
comboBoxSelectorCompany.Margin = new Padding(2, 1, 2, 1);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(370, 40);
comboBoxSelectorCompany.Size = new Size(201, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 40);
pictureBox.Location = new Point(0, 24);
pictureBox.Margin = new Padding(2, 1, 2, 1);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1601, 1072);
pictureBox.Size = new Size(722, 497);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -259,7 +279,8 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1989, 40);
menuStrip.Padding = new Padding(3, 1, 0, 1);
menuStrip.Size = new Size(931, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -267,14 +288,14 @@
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(90, 36);
файлToolStripMenuItem.Size = new Size(48, 22);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(361, 44);
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
@ -282,7 +303,7 @@
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(361, 44);
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -296,13 +317,14 @@
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1989, 1112);
ClientSize = new Size(931, 521);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(2, 1, 2, 1);
Name = "FormShipCollection";
Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false);

View File

@ -1,5 +1,8 @@
using ProjectContainerShip.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
using System.Numerics;
namespace ProjectContainerShip;
/// <summary>
@ -17,13 +20,20 @@ public partial class FormShipCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -54,19 +64,25 @@ public partial class FormShipCollection : Form
/// <param name="ship"></param>
private void SetShip(DrawningShip ship)
{
if (_company == null || ship == null)
try
{
return;
}
if (_company == null || ship == null)
{
return;
}
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
}
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка : {Messsage}", ex.Message);
}
}
@ -88,15 +104,19 @@ public partial class FormShipCollection : Form
}
int position = Convert.ToInt32(maskedTextBox.Text);
if (_company - position != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - position != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + position);
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -114,26 +134,33 @@ public partial class FormShipCollection : Form
DrawningShip? ship = null;
int counter = 100;
while (ship == null)
{
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
try
{
while (ship == null)
{
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
FormContainerShip form = new()
{
SetShip = ship
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (ship == null)
{
return;
}
FormContainerShip form = new()
{
SetShip = ship
};
form.ShowDialog();
}
/// <summary>
@ -164,17 +191,26 @@ public partial class FormShipCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
collectionType = CollectionType.Massive;
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
@ -209,12 +245,20 @@ public partial class FormShipCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@ -255,15 +299,16 @@ public partial class FormShipCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -278,16 +323,17 @@ public partial class FormShipCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -64,7 +64,7 @@ public partial class FormShipConfig : Form
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_ship?.SetPosition(110, 75);
_ship?.SetPosition(40, 25);
_ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectContainerShip
{
internal static class Program
@ -11,7 +16,35 @@ namespace ProjectContainerShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
/// <summary>
/// Конфигурация сервиса DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormShipCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@ -8,6 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<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.Configuration" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<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>
@ -23,4 +38,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}