Лабораторная работа №7

This commit is contained in:
sheymuh 2024-05-01 15:16:31 +04:00
parent 2025901f29
commit 9ddfd8be3e
13 changed files with 296 additions and 82 deletions

View File

@ -1,4 +1,5 @@
using ProjectAircraftCarrier_.Drawnings; using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects; namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@ -80,8 +81,15 @@ public abstract class AbstractCompany
public DrawningWarship? GetRandomObject() public DrawningWarship? GetRandomObject()
{ {
Random rnd = new(); Random rnd = new();
try
{
return _collection?.Get(rnd.Next(GetMaxCount)); return _collection?.Get(rnd.Next(GetMaxCount));
} }
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary> /// <summary>
/// Вывод всей коллекции /// Вывод всей коллекции
@ -95,10 +103,17 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningWarship? obj = _collection?.Get(i); DrawningWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap; return bitmap;
} }

View File

@ -1,5 +1,6 @@
 
using ProjectAircraftCarrier_.Drawnings; using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects; namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@ -39,6 +40,8 @@ public class Docks : AbstractCompany
int m = 0; int m = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
{ {
if (_collection?.Get(i) != null) if (_collection?.Get(i) != null)
{ {
@ -49,13 +52,18 @@ public class Docks : AbstractCompany
_collection?.Get(i)?.SetPosition(x, y); _collection?.Get(i)?.SetPosition(x, y);
} }
if (n < _pictureWidth / _placeSizeWidth) if (n < _pictureWidth / _placeSizeWidth) n++;
n++;
else else
{ {
n = 0; n = 0;
m++; m++;
} }
} }
catch (ObjectNotFoundException)
{
break;
}
}
} }
} }

View File

@ -1,4 +1,4 @@
using System.CodeDom.Compiler; using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects; namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@ -35,9 +35,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
@ -45,9 +46,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO выброс ошибки, если переполнение
if (Count == _maxCount) if (Count == _maxCount)
{ {
return -1; throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); _collection.Add(obj);
@ -56,9 +58,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount || position < 0 || position > Count) // TODO выброс ошибки, если выход за границы списка
// TODO выброс ошибки, если переполнение
if (position < 0 || position > Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
} }
_collection.Insert(position, obj); _collection.Insert(position, obj);
@ -67,14 +75,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Remove(int position) public T? Remove(int position)
{ {
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position > Count) if (position < 0 || position > Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
T? obj = _collection[position]; T? obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }

View File

@ -1,4 +1,5 @@
 using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects; namespace ProjectAircraftCarrier_.CollectionGenericObjects;
/// <summary> /// <summary>
@ -49,15 +50,23 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO выброс ошибки, если переполнение
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -66,14 +75,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1;
throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если переполнение
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) if (_collection[position] == null)
@ -100,14 +112,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count || _collection[position] == null) // TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
} }
T? obj = _collection[position]; T? obj = _collection[position];

View File

@ -1,4 +1,5 @@
using ProjectAircraftCarrier_.Drawnings; using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
using System.Text; using System.Text;
namespace ProjectAircraftCarrier_.CollectionGenericObjects; namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@ -100,12 +101,11 @@ public class StorageCollection<T>
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по автомобилям в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -146,20 +146,17 @@ public class StorageCollection<T>
} }
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
@ -168,12 +165,11 @@ public class StorageCollection<T>
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new FileFormatException("В файле нет данных");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
//если нет такой записи, то это не те данные throw new FileFormatException("В файле неверные данные");
return false;
} }
_storages.Clear(); _storages.Clear();
@ -189,7 +185,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidOperationException("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -197,18 +193,23 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningWarship() is T warship) if (elem?.CreateDrawningWarship() is T warship)
{
try
{ {
if (collection.Insert(warship) == -1) if (collection.Insert(warship) == -1)
{ {
return false; throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal 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,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.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,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[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

@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1176, 38); groupBoxTools.Location = new Point(1187, 38);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(326, 923); groupBoxTools.Size = new Size(326, 904);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -84,13 +84,13 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 518); panelCompanyTools.Location = new Point(3, 518);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(320, 402); panelCompanyTools.Size = new Size(320, 383);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonAddWarship // buttonAddWarship
// //
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddWarship.Location = new Point(3, 14); buttonAddWarship.Location = new Point(3, 3);
buttonAddWarship.Name = "buttonAddWarship"; buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(314, 72); buttonAddWarship.Size = new Size(314, 72);
buttonAddWarship.TabIndex = 1; buttonAddWarship.TabIndex = 1;
@ -100,7 +100,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(3, 95); maskedTextBoxPosition.Location = new Point(3, 81);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(314, 35); maskedTextBoxPosition.Size = new Size(314, 35);
@ -110,9 +110,9 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 292); buttonRefresh.Location = new Point(3, 304);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(314, 72); buttonRefresh.Size = new Size(314, 70);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -121,9 +121,9 @@
// buttonRemoveWarship // buttonRemoveWarship
// //
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(3, 136); buttonRemoveWarship.Location = new Point(3, 152);
buttonRemoveWarship.Name = "buttonRemoveWarship"; buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(314, 72); buttonRemoveWarship.Size = new Size(314, 70);
buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.TabIndex = 4;
buttonRemoveWarship.Text = "Удаление военного корабля"; buttonRemoveWarship.Text = "Удаление военного корабля";
buttonRemoveWarship.UseVisualStyleBackColor = true; buttonRemoveWarship.UseVisualStyleBackColor = true;
@ -132,9 +132,9 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 214); buttonGoToCheck.Location = new Point(3, 228);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(314, 72); buttonGoToCheck.Size = new Size(314, 70);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@ -249,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 38); pictureBox.Location = new Point(0, 38);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1176, 923); pictureBox.Size = new Size(1187, 904);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -259,7 +259,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1502, 38); menuStrip.Size = new Size(1513, 38);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip"; menuStrip.Text = "menuStrip";
// //
@ -298,7 +298,7 @@
// //
AutoScaleDimensions = new SizeF(12F, 30F); AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1502, 961); ClientSize = new Size(1513, 942);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);

View File

@ -1,5 +1,8 @@
using ProjectAircraftCarrier_.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectAircraftCarrier_.CollectionGenericObjects;
using ProjectAircraftCarrier_.Drawnings; using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
using System.Xml.Linq;
namespace ProjectAircraftCarrier_; namespace ProjectAircraftCarrier_;
@ -18,13 +21,19 @@ public partial class FormWarshipCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormWarshipCollection() public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -45,7 +54,6 @@ public partial class FormWarshipCollection : Form
private void ButtonAddWarship_Click(object sender, EventArgs e) private void ButtonAddWarship_Click(object sender, EventArgs e)
{ {
FormWarshipConfig form = new(); FormWarshipConfig form = new();
// TODO передать метод +
form.AddEvent(SetWarship); form.AddEvent(SetWarship);
form.Show(); form.Show();
} }
@ -55,6 +63,8 @@ public partial class FormWarshipCollection : Form
/// </summary> /// </summary>
/// <param name="warship"></param> /// <param name="warship"></param>
private void SetWarship(DrawningWarship? warship) private void SetWarship(DrawningWarship? warship)
{
try
{ {
if (_company == null || warship == null) if (_company == null || warship == null)
{ {
@ -64,11 +74,14 @@ public partial class FormWarshipCollection : Form
if (_company + warship != -1) if (_company + warship != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {warship.GetDataForSave()}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
@ -89,16 +102,27 @@ public partial class FormWarshipCollection : Form
return; return;
} }
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else }
catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError($"Ошибка: {ex.Message}");
} }
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError($"Ошибка: {ex.Message}");
}
} }
/// <summary> /// <summary>
@ -162,6 +186,7 @@ public partial class FormWarshipCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return; return;
} }
@ -176,6 +201,7 @@ public partial class FormWarshipCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -197,6 +223,7 @@ public partial class FormWarshipCollection : Form
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -255,13 +282,16 @@ public partial class FormWarshipCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -273,17 +303,19 @@ public partial class FormWarshipCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); 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

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace ProjectAircraftCarrier_ namespace ProjectAircraftCarrier_
{ {
internal static class Program internal static class Program
@ -11,7 +16,31 @@ namespace ProjectAircraftCarrier_
// 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 FormWarshipCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormWarshipCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services
.AddSingleton<FormWarshipCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
} }
} }
} }

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +35,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Users\\Андрей\\OneDrive\\Рабочий стол\\уник\\ООП\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}