3 Commits
Lab05 ... Lab7

Author SHA1 Message Date
3139efc43b 7 лабораторная работа 2024-06-04 14:18:52 +04:00
786c0debb5 Устранение неполадок 2024-06-02 13:39:49 +04:00
9c06d0a188 Лабораторная работа №6 2024-06-02 09:38:24 +04:00
21 changed files with 703 additions and 128 deletions

View File

@@ -35,7 +35,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth)*(_pictureHeight / (_placeSizeHeight + 60));
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -70,7 +70,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
{ {
return company._collection.Remove(position); return company._collection?.Remove(position) ?? null;
} }
/// <summary> /// <summary>

View File

@@ -1,4 +1,5 @@
using ProjectExcavator.Drawnings; using ProjectExcavator.Drawnings;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects; namespace ProjectExcavator.CollectionGenericObjects;
@@ -35,6 +36,7 @@ internal class GarageService : AbstractCompany
g.DrawLine(pen, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2 + _placeSizeHeight); g.DrawLine(pen, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2 + _placeSizeHeight);
} }
} }
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
@@ -42,18 +44,20 @@ internal class GarageService : AbstractCompany
int LevelWidth = 0; int LevelWidth = 0;
int LevelHeight = 0; int LevelHeight = 0;
for (int i = 0; i < _collection?.Count ; i++)
for (int i = 0; i < _collection?.Count; i++)
{ {
if (_collection.Get(i) != null) if(_collection?.Get(i)== null )
{
return;
}
try
{ {
_collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition((_pictureWidth - 190) - _placeSizeWidth * LevelWidth, 20 + (_placeSizeHeight + 60) * LevelHeight); _collection?.Get(i)?.SetPosition((_pictureWidth - 190) - _placeSizeWidth * LevelWidth, 20 + (_placeSizeHeight + 60) * LevelHeight);
} }
catch (ObjectNotFoundException)
if (LevelHeight + 1 > _pictureHeight / (_placeSizeHeight + 60))
{ {
return; break;
} }
if (LevelWidth + 1 < _pictureWidth / _placeSizeWidth) if (LevelWidth + 1 < _pictureWidth / _placeSizeWidth)
@@ -65,6 +69,11 @@ internal class GarageService : AbstractCompany
LevelWidth = 0; LevelWidth = 0;
LevelHeight++; LevelHeight++;
} }
if (LevelHeight >= _pictureHeight / (_placeSizeHeight + 60))
{
return;
}
} }
} }
} }

View File

@@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -45,4 +45,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
} }

View File

@@ -1,4 +1,6 @@
namespace ProjectExcavator.CollectionGenericObjects; using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@@ -19,7 +21,18 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -31,24 +44,18 @@ 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);
{
return _collection[position]; return _collection[position];
} }
else
{
return null;
}
}
public int Insert(T obj) public int Insert(T obj)
{ {
//проверка, что не превышено максимальное количество элементов //проверка, что не превышено максимальное количество элементов
//вставка в конец набора //вставка в конец набора
if (_collection.Count > _maxCount) if (Count + 1 > MaxCount)
{ {
return -1; throw new CollectionOverflowException();
} }
_collection.Add(obj); _collection.Add(obj);
return 1; return 1;
@@ -61,9 +68,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// проверка позиции // проверка позиции
// вставка по позиции // вставка по позиции
if ((_collection.Count > _maxCount) || (position < 0 || position > Count)) if (_collection.Count + 1 < _maxCount)
{ {
return -1; throw new CollectionOverflowException();
}
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
} }
_collection.Insert(position, obj); _collection.Insert(position, obj);
return 1; return 1;
@@ -74,14 +85,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// проверка позиции // проверка позиции
// удаление объекта из списка // удаление объекта из списка
if (position < 0 || position > Count) if(position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
{
return null;
}
T? obj = _collection[position]; T? obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -1,4 +1,5 @@
namespace ProjectExcavator.CollectionGenericObjects; using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@@ -14,8 +15,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -32,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -46,7 +53,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position < 0 || position > Count-1) if (position < 0 || position > Count-1)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
else else
{ {
@@ -68,7 +75,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
//Ищется свободное место после этой позиции и идет вставка туда //Ищется свободное место после этой позиции и идет вставка туда
//если нет после, ищем до вставка //если нет после, ищем до вставка
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
@@ -99,7 +106,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
behind_position --; behind_position --;
} }
return -1; throw new CollectionOverflowException(Count);
} }
} }
@@ -109,13 +116,21 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// Проверка позиции // Проверка позиции
// Удаление объекта из массива, присвоив элементу массива значение null // Удаление объекта из массива, присвоив элементу массива значение null
if (position < 0 || _collection[position] == null || position > Count -1) 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];
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic; using ProjectExcavator.Exceptions;
using System.Xml.Linq; using ProjectExcavator.Drawnings;
using System.Text;
namespace ProjectExcavator.CollectionGenericObjects; namespace ProjectExcavator.CollectionGenericObjects;
@@ -8,18 +9,35 @@ namespace ProjectExcavator.CollectionGenericObjects;
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningTrackedVehicle
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -79,4 +97,125 @@ public class StorageCollection<T>
return _storages[name]; return _storages[name];
} }
} }
/// <summary>
/// Сохранение информации по машинам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter fs = new StreamWriter(filename))
{
fs.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
fs.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по машинам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new ArgumentException("В файле нет данных");
if (str != _collectionKey.ToString())
throw new InvalidDataException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T trackedVehicle)
{
try
{
if (collection.Insert(trackedVehicle) == -1)
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@@ -16,10 +16,20 @@ public class DrawningExcavator : DrawningTrackedVehicle
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bucket">Признак наличия ковша</param> /// <param name="bucket">Признак наличия ковша</param>
/// <param name="supports">Признак наличия поддержки</param> /// <param name="supports">Признак наличия поддержки</param>
public DrawningExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool bucket, bool supports) : base(135, 82) public DrawningExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool bucket, bool supports) : base(125, 60)
{ {
EntityTrackedVehicle = new EntityExcavator(speed, weight, bodyColor, additionalColor, bucket, supports); EntityTrackedVehicle = new EntityExcavator(speed, weight, bodyColor, additionalColor, bucket, supports);
} }
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="trackedVehicle">Объект класса-сущность</param>
public DrawningExcavator(EntityTrackedVehicle trackedVehicle) : base(125,60)
{
EntityTrackedVehicle = trackedVehicle;
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@@ -35,12 +35,12 @@ public class DrawningTrackedVehicle
/// <summary> /// <summary>
/// Ширина прорисовки гусеничной машины /// Ширина прорисовки гусеничной машины
/// </summary> /// </summary>
private readonly int _drawningExcavatorWidth = 78; private readonly int _drawningTrackedVehicleWidth = 78;
/// <summary> /// <summary>
/// Высота прорисовки гусеничной машины /// Высота прорисовки гусеничной машины
/// </summary> /// </summary>
private readonly int _drawningExcavatorHeight = 63; private readonly int _drawningTrackedVehicleHeight = 63;
/// <summary> /// <summary>
/// Координата X объекта /// Координата X объекта
@@ -55,17 +55,17 @@ public class DrawningTrackedVehicle
/// <summary> /// <summary>
/// Ширина объекта /// Ширина объекта
/// </summary> /// </summary>
public int GetWidth => _drawningExcavatorWidth; public int GetWidth => _drawningTrackedVehicleWidth;
/// <summary> /// <summary>
/// Высота объекта /// Высота объекта
/// </summary> /// </summary>
public int GetHeight => _drawningExcavatorHeight; public int GetHeight => _drawningTrackedVehicleHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
private DrawningTrackedVehicle() protected DrawningTrackedVehicle()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@@ -84,6 +84,15 @@ public class DrawningTrackedVehicle
EntityTrackedVehicle = new EntityTrackedVehicle(speed, weight, bodyColor); EntityTrackedVehicle = new EntityTrackedVehicle(speed, weight, bodyColor);
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="trackedVehicle">Класс-сущность</param>
public DrawningTrackedVehicle(EntityTrackedVehicle trackedVehicle) : base()
{
EntityTrackedVehicle = trackedVehicle;
}
/// <summary> /// <summary>
/// Конструктор для наследников /// Конструктор для наследников
/// </summary> /// </summary>
@@ -91,8 +100,8 @@ public class DrawningTrackedVehicle
/// <param name="drawningExcavatorHeight">Высота прорисовки гусеничной машины</param> /// <param name="drawningExcavatorHeight">Высота прорисовки гусеничной машины</param>
protected DrawningTrackedVehicle(int drawningExcavatorWidth, int drawningExcavatorHeight) : this() protected DrawningTrackedVehicle(int drawningExcavatorWidth, int drawningExcavatorHeight) : this()
{ {
_drawningExcavatorWidth = drawningExcavatorWidth; _drawningTrackedVehicleWidth = drawningExcavatorWidth;
_drawningExcavatorHeight = drawningExcavatorHeight; _drawningTrackedVehicleHeight = drawningExcavatorHeight;
} }
/// <summary> /// <summary>
@@ -104,7 +113,7 @@ public class DrawningTrackedVehicle
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
//проверка, что объект "влезает" в размеры поля //проверка, что объект "влезает" в размеры поля
if (_drawningExcavatorWidth > width || _drawningExcavatorHeight > height) if (_drawningTrackedVehicleWidth > width || _drawningTrackedVehicleHeight > height)
{ {
EntityTrackedVehicle = null; EntityTrackedVehicle = null;
return false; return false;
@@ -116,14 +125,14 @@ public class DrawningTrackedVehicle
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
if (_startPosX.HasValue && (_startPosX.Value + _drawningExcavatorWidth > _pictureWidth)) if (_startPosX.HasValue && (_startPosX.Value + _drawningTrackedVehicleWidth > _pictureWidth))
{ {
_startPosX = _pictureWidth - _drawningExcavatorWidth; _startPosX = _pictureWidth - _drawningTrackedVehicleWidth;
} }
if (_startPosY.HasValue && (_startPosY + _drawningExcavatorHeight > _pictureHeight)) if (_startPosY.HasValue && (_startPosY + _drawningTrackedVehicleHeight > _pictureHeight))
{ {
_startPosY = _pictureHeight - _drawningExcavatorHeight; _startPosY = _pictureHeight - _drawningTrackedVehicleHeight;
} }
return true; return true;
@@ -141,9 +150,9 @@ public class DrawningTrackedVehicle
// то надо изменить координаты, чтобы он оставался в этих границах // то надо изменить координаты, чтобы он оставался в этих границах
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
if (_startPosX + _drawningExcavatorWidth > _pictureWidth) if (_startPosX + _drawningTrackedVehicleWidth > _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningExcavatorWidth; _startPosX = _pictureWidth - _drawningTrackedVehicleWidth;
} }
if (_startPosX < 0) if (_startPosX < 0)
@@ -151,9 +160,9 @@ public class DrawningTrackedVehicle
_startPosX = 0; _startPosX = 0;
} }
if (_startPosY + _drawningExcavatorHeight > _pictureHeight) if (_startPosY + _drawningTrackedVehicleHeight > _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningExcavatorHeight; _startPosY = _pictureHeight - _drawningTrackedVehicleHeight;
} }
if (_startPosY < 0) if (_startPosY < 0)
@@ -192,14 +201,14 @@ public class DrawningTrackedVehicle
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + EntityTrackedVehicle.Step < _pictureWidth - _drawningExcavatorWidth) if (_startPosX.Value + EntityTrackedVehicle.Step < _pictureWidth - _drawningTrackedVehicleWidth)
{ {
_startPosX += (int)EntityTrackedVehicle.Step; _startPosX += (int)EntityTrackedVehicle.Step;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + EntityTrackedVehicle.Step < _pictureHeight - _drawningExcavatorHeight) if (_startPosY.Value + EntityTrackedVehicle.Step < _pictureHeight - _drawningTrackedVehicleHeight)
{ {
_startPosY += (int)EntityTrackedVehicle.Step; _startPosY += (int)EntityTrackedVehicle.Step;
} }

View File

@@ -0,0 +1,53 @@
using ProjectExcavator.Drawnings;
using ProjectExcavator.Entities;
/// <summary>
/// Расширение для класса TrackedVehicle
/// </summary>
public static class ExtentionDrawningTrackedVehicle
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedVehicle? CreateDrawningTrackedVehicle(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedVehicle? trackedVehicle = EntityExcavator.CreateEntityExcavator(strs);
if (trackedVehicle != null)
{
return new DrawningExcavator(trackedVehicle);
}
trackedVehicle = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs);
if (trackedVehicle != null)
{
return new DrawningTrackedVehicle(trackedVehicle);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrackedVehicle">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedVehicle drawningTrackedVehicle)
{
string[]? array = drawningTrackedVehicle?.EntityTrackedVehicle?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -1,4 +1,7 @@
namespace ProjectExcavator.Entities; using System.ComponentModel;
using System.Net.Sockets;
namespace ProjectExcavator.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Экскаватор" /// Класс-сущность "Экскаватор"
@@ -42,4 +45,28 @@ public class EntityExcavator : EntityTrackedVehicle
Bucket = bucket; Bucket = bucket;
Supports = supports; Supports = supports;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityExcavator), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bucket.ToString(), Supports.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityExcavator? CreateEntityExcavator(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityExcavator))
{
return null;
}
return new EntityExcavator(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
} }

View File

@@ -43,4 +43,27 @@ public class EntityTrackedVehicle
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle))
{
return null;
}
return new EntityTrackedVehicle(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.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,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.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,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.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

@@ -46,10 +46,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -59,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(777, 0); groupBoxTools.Location = new Point(777, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(225, 639); groupBoxTools.Size = new Size(225, 646);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@@ -251,19 +258,63 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(777, 639); pictureBox.Size = new Size(777, 646);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1002, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormExcavatorCollection // FormExcavatorCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1002, 639); ClientSize = new Size(1002, 674);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormExcavatorCollection"; Name = "FormExcavatorCollection";
Text = "Коллекция экскаваторов"; Text = "Коллекция экскаваторов";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -272,7 +323,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -295,5 +349,11 @@
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -1,5 +1,7 @@
using ProjectExcavator.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectExcavator.CollectionGenericObjects;
using ProjectExcavator.Drawnings; using ProjectExcavator.Drawnings;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator; namespace ProjectExcavator;
/// <summary> /// <summary>
@@ -12,6 +14,11 @@ public partial class FormExcavatorCollection : Form
/// </summary> /// </summary>
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
@@ -20,10 +27,12 @@ public partial class FormExcavatorCollection : Form
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormExcavatorCollection() public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@@ -46,9 +55,9 @@ public partial class FormExcavatorCollection : Form
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e) { private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e)
{
FormExcavatorConfig form = new(); FormExcavatorConfig form = new();
// TODO передать метод(c)
form.Show(); form.Show();
form.AddEvent(SetTrackedVehicle); form.AddEvent(SetTrackedVehicle);
} }
@@ -58,6 +67,8 @@ public partial class FormExcavatorCollection : Form
/// </summary> /// </summary>
/// <param name="trackedVehicle"></param> /// <param name="trackedVehicle"></param>
private void SetTrackedVehicle(DrawningTrackedVehicle? trackedVehicle) private void SetTrackedVehicle(DrawningTrackedVehicle? trackedVehicle)
{
try
{ {
if (_company == null || trackedVehicle == null) if (_company == null || trackedVehicle == null)
{ {
@@ -68,10 +79,14 @@ public partial class FormExcavatorCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + trackedVehicle.GetDataForSave());
} }
else }
//catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("В коллекции превышено допустимое количество элементов:" );
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
} }
@@ -84,21 +99,41 @@ public partial class FormExcavatorCollection : Form
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if ((_company - pos) != null)
try
{ {
MessageBox.Show("Объект удален!"); if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
pictureBox.Image = _company.Show(); {
throw new Exception("Входные данные отсутствуют");
} }
else
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{ {
MessageBox.Show("Не удалось удалить объект"); return;
}
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
}
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Объект по позиции " + pos + " не существует ");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -161,13 +196,12 @@ public partial class FormExcavatorCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e) private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{ {
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.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@@ -179,9 +213,8 @@ public partial class FormExcavatorCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
RefreshListBoxItems();
} }
/// <summary> /// <summary>
@@ -196,18 +229,28 @@ public partial class FormExcavatorCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
/// Обновление списка в listBoxCollection /// Обновление списка в listBoxCollection
/// </summary> /// </summary>
private void RerfreshListBoxItems() private void RefreshListBoxItems()
{ {
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
@@ -250,7 +293,53 @@ public partial class FormExcavatorCollection : Form
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RefreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RefreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
} }

View File

@@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>62</value>
</metadata>
</root> </root>

View File

@@ -35,7 +35,7 @@ public partial class FormExcavatorConfig : Form
panelBlack.MouseDown += Panel_MouseDown; panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown; panelPurple.MouseDown += Panel_MouseDown;
// TODO buttonCancel.Click привязать анонимный метод через lambda с закрытием формы(c) // buttonCancel.Click привязать анонимный метод через lambda с закрытием формы(c)
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
@@ -49,7 +49,6 @@ public partial class FormExcavatorConfig : Form
_trackedVehicleDelegate += excavatorDelegate; _trackedVehicleDelegate += excavatorDelegate;
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectExcavator namespace ProjectExcavator
{ {
internal static class Program internal static class Program
@@ -11,7 +16,28 @@ namespace ProjectExcavator
// 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 FormExcavatorCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormExcavatorCollection>());
}
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<FormExcavatorCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}appSetting.json").Build()).CreateLogger());
});
} }
} }
} }

View File

@@ -8,6 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" 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>
@@ -23,4 +31,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appSetting.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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