7 лаб. работа (не доделана)
This commit is contained in:
parent
077f39a55a
commit
497eb540fd
@ -1,4 +1,6 @@
|
|||||||
|
|
||||||
|
using MotorBoat.Exceptions;
|
||||||
|
|
||||||
namespace MotorBoat.CollectionGenericObjects;
|
namespace MotorBoat.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -45,34 +47,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count)
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
{
|
if (_collection[position] == null) throw new ObjectNotFoundException();
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
|
|
||||||
}
|
}
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
if (Count + 1 > _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
|
|
||||||
}
|
}
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (Count + 1 > _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
if (position < 0 || position > Count) return -1;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return 1;
|
return position;
|
||||||
}
|
}
|
||||||
public T? Remove(int position)
|
public T? Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position > Count) return null;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
T? temp = _collection[position];
|
T? obj = _collection[position];
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return temp;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<T?> GetItems()
|
public IEnumerable<T?> GetItems()
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
|
|
||||||
|
using MotorBoat.Exceptions;
|
||||||
|
|
||||||
namespace MotorBoat.CollectionGenericObjects;
|
namespace MotorBoat.CollectionGenericObjects;
|
||||||
|
|
||||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||||
@ -39,7 +41,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count) return null;
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
@ -52,15 +54,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException();
|
||||||
}
|
}
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (position >= Count || position < 0) return -1;
|
if (position < 0 || position >= Count)
|
||||||
|
{
|
||||||
|
throw new PositionOutOfCollectionException();
|
||||||
|
}
|
||||||
if (_collection[position] == null)
|
if (_collection[position] == null)
|
||||||
{
|
{
|
||||||
_collection[position] = obj;
|
_collection[position] = obj;
|
||||||
return position;
|
return position;
|
||||||
|
|
||||||
}
|
}
|
||||||
int temp = position + 1;
|
int temp = position + 1;
|
||||||
while (temp < Count)
|
while (temp < Count)
|
||||||
@ -86,7 +92,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
public T? Remove(int position)
|
public T? Remove(int position)
|
||||||
{
|
{
|
||||||
if (position >= Count || position < 0) return null;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||||
|
if (_collection[position] == null) throw new ObjectNotFoundException();
|
||||||
T? myObject = _collection[position];
|
T? myObject = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return myObject;
|
return myObject;
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using MotorBoat.Drawnings;
|
using MotorBoat.Drawnings;
|
||||||
|
using MotorBoat.Exceptions;
|
||||||
|
|
||||||
namespace MotorBoat.CollectionGenericObjects;
|
namespace MotorBoat.CollectionGenericObjects;
|
||||||
|
|
||||||
@ -90,15 +91,15 @@ public class StorageCollection<T>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Сохранение информации по автомобилям в хранилище в файл
|
/// Сохранение информации по лодкам в хранилище в файл
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename"></param>
|
/// <param name="filename"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public bool SaveData(string filename)
|
public void SaveData(string filename)
|
||||||
{
|
{
|
||||||
if (_storages.Count == 0)
|
if (_storages.Count == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||||
}
|
}
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
@ -134,31 +135,29 @@ public class StorageCollection<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Загрузка информации по автомобилям в хранилище из файла
|
/// Загрузка информации по лодкам в хранилище из файла
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename">>Путь и имя файла</param>
|
/// <param name="filename">>Путь и имя файла</param>
|
||||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||||
public bool LoadData(string filename)
|
public void LoadData(string filename)
|
||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
return false;
|
throw new FileNotFoundException("Файл не существует");
|
||||||
}
|
}
|
||||||
using (StreamReader reader = new(filename))
|
using (StreamReader reader = new(filename))
|
||||||
{
|
{
|
||||||
string line = reader.ReadLine();
|
string line = reader.ReadLine();
|
||||||
if (line == null || line.Length == 0)
|
if (line == null || line.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new ArgumentException("В файле нет данных");
|
||||||
}
|
}
|
||||||
if (!line.Equals(_collectionKey))
|
if (!line.Equals(_collectionKey))
|
||||||
{
|
{
|
||||||
//если нет такой записи, то это не те данные
|
throw new InvalidDataException("В файле неверные данные");
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
_storages.Clear();
|
_storages.Clear();
|
||||||
while ((line = reader.ReadLine()) != null)
|
while ((line = reader.ReadLine()) != null)
|
||||||
@ -170,28 +169,31 @@ public class StorageCollection<T>
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
|
||||||
if (collection == null)
|
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||||
string[] set = record[3].Split(_separatorItems,
|
string[] set = record[3].Split(_separatorItems,
|
||||||
StringSplitOptions.RemoveEmptyEntries);
|
StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (string elem in set)
|
foreach (string elem in set)
|
||||||
{
|
{
|
||||||
if (elem?.CreateDrawningBoat() is T boat)
|
if (elem?.CreateDrawningBoat() is T boat)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (collection.Insert(boat) == -1)
|
if (collection.Insert(boat) == -1)
|
||||||
{
|
{
|
||||||
return false;
|
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
|
{
|
||||||
|
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_storages.Add(record[0], collection);
|
_storages.Add(record[0], collection);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -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 MotorBoat.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) { }
|
||||||
|
}
|
21
MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs
Normal file
21
MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs
Normal 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 MotorBoat.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,21 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace MotorBoat.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) { }
|
||||||
|
}
|
@ -1,5 +1,7 @@
|
|||||||
using MotorBoat.CollectionGenericObjects;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using MotorBoat.CollectionGenericObjects;
|
||||||
using MotorBoat.Drawnings;
|
using MotorBoat.Drawnings;
|
||||||
|
using MotorBoat.Exceptions;
|
||||||
|
|
||||||
namespace MotorBoat;
|
namespace MotorBoat;
|
||||||
|
|
||||||
@ -16,13 +18,16 @@ public partial class FormBoatCollection : Form
|
|||||||
/// Компания
|
/// Компания
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private AbstractCompany? _company = null;
|
private AbstractCompany? _company = null;
|
||||||
|
|
||||||
|
private readonly ILogger _logger;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormBoatCollection()
|
public FormBoatCollection(ILogger<FormBoatCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выбор компании
|
/// Выбор компании
|
||||||
@ -60,15 +65,17 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
try
|
||||||
if (_company + boat != -1)
|
|
||||||
{
|
{
|
||||||
|
int addingObject = (_company + boat);
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
|
_logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
catch (CollectionOverflowException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -80,6 +87,7 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||||
@ -88,14 +96,22 @@ public partial class FormBoatCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||||
if (_company - pos != null)
|
try
|
||||||
{
|
{
|
||||||
|
object decrementObject = _company - pos;
|
||||||
MessageBox.Show("Объект удален");
|
MessageBox.Show("Объект удален");
|
||||||
|
_logger.LogInformation($"Удален по позиции {pos}");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
catch (ObjectNotFoundException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Объект не найден ");
|
||||||
|
_logger.LogWarning($"Удаление не найденного объекта в позиции {pos} ");
|
||||||
|
}
|
||||||
|
catch (PositionOutOfCollectionException ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Удаление вне рамках коллекции");
|
||||||
|
_logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -112,14 +128,20 @@ public partial class FormBoatCollection : Form
|
|||||||
DrawningBoat? boat = null;
|
DrawningBoat? boat = null;
|
||||||
int counter = 100;
|
int counter = 100;
|
||||||
while (boat == null)
|
while (boat == null)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
boat = _company.GetRandomObject();
|
boat = _company.GetRandomObject();
|
||||||
|
}
|
||||||
|
catch (ObjectNotFoundException)
|
||||||
|
{
|
||||||
counter--;
|
counter--;
|
||||||
if (counter <= 0)
|
if (counter <= 0)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (boat == null)
|
if (boat == null)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@ -154,6 +176,7 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning("Не заполненная коллекция");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
CollectionType collectionType = CollectionType.None;
|
CollectionType collectionType = CollectionType.None;
|
||||||
@ -166,6 +189,7 @@ public partial class FormBoatCollection : Form
|
|||||||
collectionType = CollectionType.List;
|
collectionType = CollectionType.List;
|
||||||
}
|
}
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
|
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -182,15 +206,17 @@ public partial class FormBoatCollection : Form
|
|||||||
if (listBoxCollection.SelectedIndex < 0)
|
if (listBoxCollection.SelectedIndex < 0)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
|
_logger.LogWarning("Удаление невыбранной коллекции");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
|
||||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление",
|
if (MessageBox.Show("Удалить коллекцию?", "Удаление",
|
||||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||||
|
_logger.LogInformation($"Удалена коллекция: {name}");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -218,6 +244,7 @@ public partial class FormBoatCollection : Form
|
|||||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
|
_logger.LogWarning("Создание компании невыбранной коллекции");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ICollectionGenericObjects<DrawningBoat>? collection =
|
ICollectionGenericObjects<DrawningBoat>? collection =
|
||||||
@ -225,6 +252,7 @@ public partial class FormBoatCollection : Form
|
|||||||
if (collection == null)
|
if (collection == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не проинициализирована");
|
MessageBox.Show("Коллекция не проинициализирована");
|
||||||
|
_logger.LogWarning("Не удалось инициализировать коллекцию");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (comboBoxSelectorCompany.Text)
|
switch (comboBoxSelectorCompany.Text)
|
||||||
@ -246,15 +274,16 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Сохранение прошло успешно",
|
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
|
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат",
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -268,14 +297,17 @@ public partial class FormBoatCollection : Form
|
|||||||
{
|
{
|
||||||
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);
|
||||||
|
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,12 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
|
@ -1,3 +1,8 @@
|
|||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Serilog;
|
||||||
|
|
||||||
namespace MotorBoat
|
namespace MotorBoat
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -8,8 +13,33 @@ namespace MotorBoat
|
|||||||
[STAThread]
|
[STAThread]
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
|
// To customize application configuration such as set high DPI settings or default font,
|
||||||
|
// see https://aka.ms/applicationconfiguration.
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormBoatCollection());
|
ServiceCollection services = new();
|
||||||
}
|
ConfigureServices(services);
|
||||||
|
using ServiceProvider serviceProvider =
|
||||||
|
services.BuildServiceProvider();
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
|
||||||
|
}
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormBoatCollection>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
var configuration = new ConfigurationBuilder()
|
||||||
|
.SetBasePath(Directory.GetCurrentDirectory())
|
||||||
|
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var logger = new LoggerConfiguration()
|
||||||
|
.ReadFrom.Configuration(configuration)
|
||||||
|
.CreateLogger();
|
||||||
|
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddSerilog(logger);
|
||||||
|
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}Û
|
20
MotorBoat/MotorBoat/serilog.json
Normal file
20
MotorBoat/MotorBoat/serilog.json
Normal 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": "MotorBoat"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user