Лабораторная работа №7
This commit is contained in:
parent
2025901f29
commit
9ddfd8be3e
@ -1,4 +1,5 @@
|
||||
using ProjectAircraftCarrier_.Drawnings;
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
|
||||
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
|
||||
@ -80,8 +81,15 @@ public abstract class AbstractCompany
|
||||
public DrawningWarship? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
try
|
||||
{
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
@ -95,10 +103,17 @@ public abstract class AbstractCompany
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawningWarship? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
|
||||
using ProjectAircraftCarrier_.Drawnings;
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
|
||||
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
|
||||
@ -39,6 +40,8 @@ public class Docks : AbstractCompany
|
||||
int m = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_collection?.Get(i) != null)
|
||||
{
|
||||
@ -49,13 +52,18 @@ public class Docks : AbstractCompany
|
||||
_collection?.Get(i)?.SetPosition(x, y);
|
||||
}
|
||||
|
||||
if (n < _pictureWidth / _placeSizeWidth)
|
||||
n++;
|
||||
if (n < _pictureWidth / _placeSizeWidth) n++;
|
||||
|
||||
else
|
||||
{
|
||||
n = 0;
|
||||
m++;
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
using System.CodeDom.Compiler;
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
|
||||
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
|
||||
@ -35,9 +35,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO выброс ошибки, если выход за границы списка
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
return _collection[position];
|
||||
@ -45,9 +46,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO выброс ошибки, если переполнение
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
_collection.Add(obj);
|
||||
@ -56,9 +58,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
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);
|
||||
@ -67,14 +75,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO выброс ошибки, если выход за границы списка
|
||||
if (position < 0 || position > Count)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
T? obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
|
||||
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -49,15 +50,23 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO выброс ошибки, если выход за границы массива
|
||||
// TODO выброс ошибки, если объект пустой
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO выброс ошибки, если переполнение
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
@ -66,14 +75,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// TODO выброс ошибки, если выход за границы массива
|
||||
// TODO выброс ошибки, если переполнение
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
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];
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAircraftCarrier_.Drawnings;
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
@ -100,12 +101,11 @@ public class StorageCollection<T>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </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 NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -146,20 +146,17 @@ public class StorageCollection<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new(filename))
|
||||
@ -168,12 +165,11 @@ public class StorageCollection<T>
|
||||
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new FileFormatException("В файле нет данных");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new FileFormatException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
|
||||
@ -189,7 +185,7 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -197,18 +193,23 @@ public class StorageCollection<T>
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningWarship() is T warship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(warship) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new OverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -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) { }
|
||||
}
|
@ -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) { }
|
||||
}
|
@ -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) { }
|
||||
}
|
@ -66,9 +66,9 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(1176, 38);
|
||||
groupBoxTools.Location = new Point(1187, 38);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(326, 923);
|
||||
groupBoxTools.Size = new Size(326, 904);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@ -84,13 +84,13 @@
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(3, 518);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(320, 402);
|
||||
panelCompanyTools.Size = new Size(320, 383);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonAddWarship
|
||||
//
|
||||
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonAddWarship.Location = new Point(3, 14);
|
||||
buttonAddWarship.Location = new Point(3, 3);
|
||||
buttonAddWarship.Name = "buttonAddWarship";
|
||||
buttonAddWarship.Size = new Size(314, 72);
|
||||
buttonAddWarship.TabIndex = 1;
|
||||
@ -100,7 +100,7 @@
|
||||
//
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
maskedTextBoxPosition.Location = new Point(3, 95);
|
||||
maskedTextBoxPosition.Location = new Point(3, 81);
|
||||
maskedTextBoxPosition.Mask = "00";
|
||||
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
maskedTextBoxPosition.Size = new Size(314, 35);
|
||||
@ -110,9 +110,9 @@
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(3, 292);
|
||||
buttonRefresh.Location = new Point(3, 304);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(314, 72);
|
||||
buttonRefresh.Size = new Size(314, 70);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
buttonRefresh.Text = "Обновить";
|
||||
buttonRefresh.UseVisualStyleBackColor = true;
|
||||
@ -121,9 +121,9 @@
|
||||
// buttonRemoveWarship
|
||||
//
|
||||
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRemoveWarship.Location = new Point(3, 136);
|
||||
buttonRemoveWarship.Location = new Point(3, 152);
|
||||
buttonRemoveWarship.Name = "buttonRemoveWarship";
|
||||
buttonRemoveWarship.Size = new Size(314, 72);
|
||||
buttonRemoveWarship.Size = new Size(314, 70);
|
||||
buttonRemoveWarship.TabIndex = 4;
|
||||
buttonRemoveWarship.Text = "Удаление военного корабля";
|
||||
buttonRemoveWarship.UseVisualStyleBackColor = true;
|
||||
@ -132,9 +132,9 @@
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(3, 214);
|
||||
buttonGoToCheck.Location = new Point(3, 228);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(314, 72);
|
||||
buttonGoToCheck.Size = new Size(314, 70);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
buttonGoToCheck.Text = "Передать на тесты";
|
||||
buttonGoToCheck.UseVisualStyleBackColor = true;
|
||||
@ -249,7 +249,7 @@
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 38);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(1176, 923);
|
||||
pictureBox.Size = new Size(1187, 904);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -259,7 +259,7 @@
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(1502, 38);
|
||||
menuStrip.Size = new Size(1513, 38);
|
||||
menuStrip.TabIndex = 2;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
@ -298,7 +298,7 @@
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(12F, 30F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1502, 961);
|
||||
ClientSize = new Size(1513, 942);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
|
@ -1,5 +1,8 @@
|
||||
using ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAircraftCarrier_.CollectionGenericObjects;
|
||||
using ProjectAircraftCarrier_.Drawnings;
|
||||
using ProjectAircraftCarrier_.Exceptions;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace ProjectAircraftCarrier_;
|
||||
|
||||
@ -18,13 +21,19 @@ public partial class FormWarshipCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarshipCollection()
|
||||
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -45,7 +54,6 @@ public partial class FormWarshipCollection : Form
|
||||
private void ButtonAddWarship_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormWarshipConfig form = new();
|
||||
// TODO передать метод +
|
||||
form.AddEvent(SetWarship);
|
||||
form.Show();
|
||||
}
|
||||
@ -55,6 +63,8 @@ public partial class FormWarshipCollection : Form
|
||||
/// </summary>
|
||||
/// <param name="warship"></param>
|
||||
private void SetWarship(DrawningWarship? warship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_company == null || warship == null)
|
||||
{
|
||||
@ -64,11 +74,14 @@ public partial class FormWarshipCollection : Form
|
||||
if (_company + warship != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавлен объект {warship.GetDataForSave()}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"Ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -89,16 +102,27 @@ public partial class FormWarshipCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Удален объект по позиции {pos}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError($"Ошибка: {ex.Message}");
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError($"Ошибка: {ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -162,6 +186,7 @@ public partial class FormWarshipCollection : Form
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -176,6 +201,7 @@ public partial class FormWarshipCollection : Form
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -197,6 +223,7 @@ public partial class FormWarshipCollection : Form
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -255,13 +282,16 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -273,17 +303,19 @@ public partial class FormWarshipCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO продумать логику
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_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);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAircraftCarrier_
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,31 @@ namespace ProjectAircraftCarrier_
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
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());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,18 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +35,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilogConfig.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -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}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user