Compare commits

..

2 Commits

Author SHA1 Message Date
080b215b76 Лабораторная работа №7 2024-06-16 14:59:45 +03:00
Nikitin Egor
22e4478792 Лабораторная работа №7 2024-06-16 14:49:23 +03:00
14 changed files with 504 additions and 249 deletions

View File

@ -1,7 +1,12 @@
using ProjectTank.Drawnings; using ProjectTank.Drawnings;
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Exceptions;
namespace ProjectTank.CollectionGenericObjects; namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию самолётов
/// </summary>
public abstract class AbstractCompany public abstract class AbstractCompany
{ {
/// <summary> /// <summary>
@ -25,23 +30,22 @@ public abstract class AbstractCompany
protected readonly int _pictureHeight; protected readonly int _pictureHeight;
/// <summary> /// <summary>
/// Коллекция машин /// Коллекция самолётов
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningTank2>? _collection = null; protected ICollectionGenericObjects<DrawningTank2>? _collection = null;
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth">Ширина окна</param> /// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param> /// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция машин</param> /// <param name="collection">Коллекция самолётов</param>
public AbstractCompany(int picWidth, int picHeight, public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection)
ICollectionGenericObjects<DrawningTank2> collection)
{ {
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
@ -53,7 +57,7 @@ public abstract class AbstractCompany
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса
/// </summary> /// </summary>
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="trackedMachine">Добавляемый объект</param> /// <param name="tank2">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank2 tank2) public static int operator +(AbstractCompany company, DrawningTank2 tank2)
{ {
@ -66,9 +70,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param> /// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns> /// <returns></returns>
public static DrawningTank2 operator -(AbstractCompany company, int position) public static DrawningTank2? operator -(AbstractCompany company, int position)
{ {
return company._collection.Remove(position); return company._collection?.Remove(position);
} }
/// <summary> /// <summary>
@ -90,12 +94,20 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackgound(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningTank2? obj = _collection?.Get(i); DrawningTank2? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (ObjectNotFoundException)
{
}
}
return bitmap; return bitmap;
} }
@ -104,6 +116,7 @@ public abstract class AbstractCompany
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g); protected abstract void DrawBackgound(Graphics g);
/// <summary> /// <summary>
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>

View File

@ -1,5 +1,11 @@
namespace ProjectTank.CollectionGenericObjects; using ProjectTank.CollectionGenericObjects;
using ProjectTank.Exceptions;
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
@ -7,7 +13,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
private readonly List<T?> _collection; private readonly List<T?> _collection;
/// <summary> /// <summary>
/// Максимально допустимое число объектов в списке /// Максимально допустимое число объектов в списке
/// </summary> /// </summary>
@ -17,7 +22,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
get get
{ {
return Count; return _collection.Count;
} }
set set
{ {
@ -37,37 +42,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = new(); _collection = new();
} }
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null; if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
// TODO вставка в конец набора
if (Count + 1 > _maxCount) return -1;
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
// TODO проверка позиции if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
// TODO вставка по позиции
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
_collection.Insert(position, obj); _collection.Insert(position, obj);
return 1; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
// TODO проверка позиции if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
// TODO удаление объекта из списка
if (position < 0 || position > Count) return null;
T? temp = _collection[position]; T? temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;

View File

@ -1,6 +1,14 @@
namespace ProjectTank.CollectionGenericObjects; 
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Exceptions;
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T> namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
@ -47,13 +55,10 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position <= Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
else
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO вставка в свободное место набора // TODO вставка в свободное место набора
@ -65,7 +70,7 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
@ -75,39 +80,55 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// ищется свободное место после этой позиции и идет туда // ищется свободное место после этой позиции и идет туда
// если нет после, ищем до // если нет после, ищем до
// TODO вставка // TODO вставка
if (position < Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{ {
if (position < 0 || position >= Count) bool pushed = false;
for (int index = position + 1; index < Count; index++)
{ {
return -1; if (_collection[index] == null)
{
position = index;
pushed = true;
break;
} }
if (_collection[position] == null) }
if (!pushed)
{ {
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
else
{
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
}
}
return -1;
}
public T? Remove(int position) public T? Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= Count || position < 0) return null; if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
T? myObject = _collection[position];
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return myObject; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
@ -119,6 +140,3 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }

View File

@ -1,4 +1,7 @@
using ProjectTank.Drawnings; using ProjectTank.Drawnings;
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Exceptions;
using System.Data;
using System.Text; using System.Text;
namespace ProjectTank.CollectionGenericObjects; namespace ProjectTank.CollectionGenericObjects;
@ -7,7 +10,7 @@ namespace ProjectTank.CollectionGenericObjects;
/// Класс-хранилище коллекций /// Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
internal class StorageCollection<T> public class StorageCollection<T>
where T : DrawningTank2 where T : DrawningTank2
{ {
/// <summary> /// <summary>
@ -24,16 +27,17 @@ internal class StorageCollection<T>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
/// </summary> /// </summary>
private readonly string _collectionKey = "CollectionsStorage"; private readonly string _collectionKey = "CollectionsStorage";
/// <summary> /// <summary>
/// Разделитель для записи ключа и значения элемента словаря /// Разделитель для записи ключа и значения элемента словаря
/// </summary> /// </summary>
private readonly string _separatorForKeyValue = "|"; private readonly string _separatorForKeyValue = "|";
/// <summary> /// <summary>
/// Разделитель для записей коллекции данных в файл /// Разделитель для записей коллекции данных в файл
/// </summary> /// </summary>
private readonly string _separatorItems = ";"; private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -49,15 +53,13 @@ internal class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return; if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[name] = new ListGenericObjects<T>();
} }
/// <summary> /// <summary>
@ -66,7 +68,6 @@ internal class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
_storages.Remove(name); _storages.Remove(name);
} }
@ -80,7 +81,6 @@ internal class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
return _storages[name]; return _storages[name];
return null; return null;
@ -88,15 +88,14 @@ internal class StorageCollection<T>
} }
/// <summary> /// <summary>
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по самолётам в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -136,22 +135,18 @@ internal class StorageCollection<T>
} }
writer.Write(sb); writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по самолётам в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException($"{filename} не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@ -159,11 +154,11 @@ internal class StorageCollection<T>
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new FileFormatException("Файл не подходит");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
@ -178,25 +173,32 @@ internal class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTank2() is T tank2) if (elem?.CreateDrawningTank2() is T tank2)
{
try
{ {
if (collection.Insert(tank2) == -1) if (collection.Insert(tank2) == -1)
{ {
return false; throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типу
/// </summary> /// </summary>
@ -212,3 +214,4 @@ internal class StorageCollection<T>
}; };
} }
} }

View File

@ -1,11 +1,11 @@
using ProjectTank.Drawnings; using ProjectTank.Drawnings;
using ProjectTank.Entities; using ProjectTank.CollectionGenericObjects;
using System; using ProjectTank.Exceptions;
namespace ProjectTank.CollectionGenericObjects; namespace ProjectTank.CollectionGenericObjects;
/// <summary> /// <summary>
/// Реализация абстрактной компании - аренда поезда /// Реализация абстрактной компании - СимбирФлот
/// </summary> /// </summary>
public class TankBase : AbstractCompany public class TankBase : AbstractCompany
{ {
@ -18,7 +18,12 @@ public class TankBase : AbstractCompany
public TankBase(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection) : base(picWidth, picHeight, collection) public TankBase(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection) : base(picWidth, picHeight, collection)
{ {
} }
/// <summary>
/// Отрисовка хранилища
/// </summary>
/// <param name="g">Графика</param>
int pamat_i = 0;
int pamat_j = 0;
protected override void DrawBackgound(Graphics g) protected override void DrawBackgound(Graphics g)
{ {
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
@ -31,24 +36,40 @@ public class TankBase : AbstractCompany
} }
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
} }
} }
/// <summary>
/// Установка объекта в Хранилище
/// </summary>
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int n = 0; int n = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{ {
DrawningTank2? drawningTank2 = _collection?.Get(n); try
n++;
if (drawningTank2 != null)
{ {
drawningTank2.SetPictureSize(_pictureWidth, _pictureHeight); DrawningTank2? tank2 = _collection?.Get(n);
drawningTank2.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); if (tank2 != null)
} {
tank2.SetPictureSize(_pictureWidth, _pictureHeight);
tank2.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (PositionOutOfCollectionException e)
{
}
catch (ObjectNotFoundException e)
{
}
n++;
} }
} }
} }

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectTank.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

View File

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

@ -68,9 +68,11 @@ namespace ProjectTank
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(931, 28); groupBoxTools.Location = new Point(856, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(218, 659); groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(191, 543);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -84,17 +86,19 @@ namespace ProjectTank
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 379); panelCompanyTools.Location = new Point(3, 333);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(212, 277); panelCompanyTools.Size = new Size(185, 208);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonDelTank // buttonDelTank
// //
buttonDelTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonDelTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelTank.Location = new Point(3, 120); buttonDelTank.Location = new Point(3, 90);
buttonDelTank.Margin = new Padding(3, 2, 3, 2);
buttonDelTank.Name = "buttonDelTank"; buttonDelTank.Name = "buttonDelTank";
buttonDelTank.Size = new Size(203, 49); buttonDelTank.Size = new Size(177, 37);
buttonDelTank.TabIndex = 4; buttonDelTank.TabIndex = 4;
buttonDelTank.Text = "Удалить танка "; buttonDelTank.Text = "Удалить танка ";
buttonDelTank.UseVisualStyleBackColor = true; buttonDelTank.UseVisualStyleBackColor = true;
@ -103,9 +107,10 @@ namespace ProjectTank
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(4, 225); buttonRefresh.Location = new Point(4, 169);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(202, 49); buttonRefresh.Size = new Size(176, 37);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -114,19 +119,21 @@ namespace ProjectTank
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(4, 87); maskedTextBox.Location = new Point(4, 65);
maskedTextBox.Margin = new Padding(3, 2, 3, 2);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(202, 27); maskedTextBox.Size = new Size(176, 23);
maskedTextBox.TabIndex = 3; maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int); maskedTextBox.ValidatingType = typeof(int);
// //
// buttonAddTank // buttonAddTank
// //
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(3, 3); buttonAddTank.Location = new Point(3, 2);
buttonAddTank.Margin = new Padding(3, 2, 3, 2);
buttonAddTank.Name = "buttonAddTank"; buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(205, 49); buttonAddTank.Size = new Size(178, 37);
buttonAddTank.TabIndex = 1; buttonAddTank.TabIndex = 1;
buttonAddTank.Text = "Добавление бронированной машины"; buttonAddTank.Text = "Добавление бронированной машины";
buttonAddTank.UseVisualStyleBackColor = true; buttonAddTank.UseVisualStyleBackColor = true;
@ -135,9 +142,10 @@ namespace ProjectTank
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 173); buttonGoToCheck.Location = new Point(3, 130);
buttonGoToCheck.Margin = new Padding(3, 2, 3, 2);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(203, 49); buttonGoToCheck.Size = new Size(177, 37);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@ -145,9 +153,10 @@ namespace ProjectTank
// //
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(6, 339); buttonCreateCompany.Location = new Point(5, 254);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(206, 34); buttonCreateCompany.Size = new Size(180, 26);
buttonCreateCompany.TabIndex = 8; buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true; buttonCreateCompany.UseVisualStyleBackColor = true;
@ -163,16 +172,18 @@ namespace ProjectTank
panelStorage.Controls.Add(textBoxCollectionName); panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName); panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23); panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(212, 276); panelStorage.Size = new Size(185, 207);
panelStorage.TabIndex = 7; panelStorage.TabIndex = 7;
// //
// buttonCollectinDel // buttonCollectinDel
// //
buttonCollectinDel.Location = new Point(3, 241); buttonCollectinDel.Location = new Point(3, 181);
buttonCollectinDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectinDel.Name = "buttonCollectinDel"; buttonCollectinDel.Name = "buttonCollectinDel";
buttonCollectinDel.Size = new Size(206, 29); buttonCollectinDel.Size = new Size(180, 22);
buttonCollectinDel.TabIndex = 6; buttonCollectinDel.TabIndex = 6;
buttonCollectinDel.Text = "Удалить коллекцию"; buttonCollectinDel.Text = "Удалить коллекцию";
buttonCollectinDel.UseVisualStyleBackColor = true; buttonCollectinDel.UseVisualStyleBackColor = true;
@ -181,17 +192,19 @@ namespace ProjectTank
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20; listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 131); listBoxCollection.Location = new Point(3, 98);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(206, 104); listBoxCollection.Size = new Size(181, 79);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 5;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(3, 96); buttonCollectionAdd.Location = new Point(3, 72);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(206, 29); buttonCollectionAdd.Size = new Size(180, 22);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionAdd.UseVisualStyleBackColor = true;
@ -200,9 +213,10 @@ namespace ProjectTank
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(106, 66); radioButtonList.Location = new Point(93, 50);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24); radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
@ -211,9 +225,10 @@ namespace ProjectTank
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(18, 66); radioButtonMassive.Location = new Point(16, 50);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24); radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
@ -221,17 +236,18 @@ namespace ProjectTank
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(3, 33); textBoxCollectionName.Location = new Point(3, 25);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(206, 27); textBoxCollectionName.Size = new Size(181, 23);
textBoxCollectionName.TabIndex = 1; textBoxCollectionName.TabIndex = 1;
// //
// labelCollectionName // labelCollectionName
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(27, 10); labelCollectionName.Location = new Point(24, 8);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20); labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
@ -241,18 +257,20 @@ namespace ProjectTank
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 305); comboBoxSelectorCompany.Location = new Point(5, 229);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(206, 28); comboBoxSelectorCompany.Size = new Size(181, 23);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
// //
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 24);
pictureBox.Margin = new Padding(3, 2, 3, 2);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(931, 659); pictureBox.Size = new Size(856, 543);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -262,7 +280,8 @@ namespace ProjectTank
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1149, 28); menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(1047, 24);
menuStrip.TabIndex = 6; menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -270,14 +289,14 @@ namespace ProjectTank
// //
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem"; файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24); файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл"; файлToolStripMenuItem.Text = "Файл";
// //
// saveToolStripMenuItem // saveToolStripMenuItem
// //
saveToolStripMenuItem.Name = "saveToolStripMenuItem"; saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26); saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение"; saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
@ -285,7 +304,7 @@ namespace ProjectTank
// //
loadToolStripMenuItem.Name = "loadToolStripMenuItem"; loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26); loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка"; loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -299,13 +318,14 @@ namespace ProjectTank
// //
// FormTankCollection // FormTankCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1149, 687); ClientSize = new Size(1047, 567);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormTankCollection"; Name = "FormTankCollection";
Text = "Коллекция танков"; Text = "Коллекция танков";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);

View File

@ -1,5 +1,16 @@
using ProjectTank.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Drawnings; using ProjectTank.Drawnings;
using ProjectTank.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectTank; namespace ProjectTank;
@ -18,15 +29,20 @@ public partial class FormTankCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTankCollection() public FormTankCollection(ILogger<FormTankCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
/// </summary> /// </summary>
@ -44,10 +60,9 @@ public partial class FormTankCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
public void ButtonAddTank_Click(object sender, EventArgs e) public void ButtonAddTank_Click(object sender, EventArgs e)
{ {
FormTankConfig form = new FormTankConfig();
FormTankConfig form = new();
form.AddEvent(SetMachine);
form.Show(); form.Show();
form.AddEvent(SetMachine);
} }
/// <summary> /// <summary>
@ -60,14 +75,18 @@ public partial class FormTankCollection : Form
{ {
return; return;
} }
if (_company + tank2 != -1) try
{ {
var res = _company + tank2;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
@ -82,6 +101,7 @@ public partial class FormTankCollection : Form
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
_logger.LogError("Удаление объекта из несуществующей коллекции");
return; return;
} }
@ -91,14 +111,22 @@ public partial class FormTankCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.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)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Объект не найден");
_logger.LogError($"Удаление не найденного объекта в позиции {pos} ");
}
catch (PositionOutOfCollectionException)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogError($"Удаление объекта за пределами коллекции {pos} ");
} }
} }
@ -108,6 +136,7 @@ public partial class FormTankCollection : Form
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
{ {
if (_company == null) if (_company == null)
{ {
@ -137,6 +166,7 @@ public partial class FormTankCollection : Form
}; };
form.ShowDialog(); form.ShowDialog();
} }
}
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
@ -163,6 +193,7 @@ public partial class FormTankCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Не заполненная коллекция");
return; return;
} }
@ -177,6 +208,7 @@ public partial class FormTankCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -191,13 +223,16 @@ public partial class FormTankCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogError("Удаление невыбранной коллекции");
return; return;
} }
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
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());
_logger.LogInformation($"Удалена коллекция: {name}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -228,6 +263,7 @@ public partial class FormTankCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogError("Создание компании невыбранной коллекции");
return; return;
} }
@ -235,9 +271,11 @@ public partial class FormTankCollection : Form
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
_logger.LogError("Не удалось инициализировать коллекцию");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -257,13 +295,16 @@ public partial class FormTankCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -279,16 +320,17 @@ public partial class FormTankCollection : Form
// TODO продумать логику // TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storageCollection.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -77,8 +77,10 @@ namespace ProjectTank
groupBoxConfig.Controls.Add(labelSimpleObject); groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left; groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0); groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Margin = new Padding(3, 2, 3, 2);
groupBoxConfig.Name = "groupBoxConfig"; groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(630, 274); groupBoxConfig.Padding = new Padding(3, 2, 3, 2);
groupBoxConfig.Size = new Size(551, 249);
groupBoxConfig.TabIndex = 0; groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false; groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры"; groupBoxConfig.Text = "Параметры";
@ -93,9 +95,11 @@ namespace ProjectTank
groupBoxColors.Controls.Add(panelBlue); groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen); groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed); groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(308, 12); groupBoxColors.Location = new Point(270, 9);
groupBoxColors.Margin = new Padding(3, 2, 3, 2);
groupBoxColors.Name = "groupBoxColors"; groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(293, 143); groupBoxColors.Padding = new Padding(3, 2, 3, 2);
groupBoxColors.Size = new Size(256, 107);
groupBoxColors.TabIndex = 8; groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false; groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета"; groupBoxColors.Text = "Цвета";
@ -103,73 +107,82 @@ namespace ProjectTank
// panelGray // panelGray
// //
panelGray.BackColor = Color.Gray; panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(85, 81); panelGray.Location = new Point(74, 61);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray"; panelGray.Name = "panelGray";
panelGray.Size = new Size(49, 45); panelGray.Size = new Size(43, 34);
panelGray.TabIndex = 7; panelGray.TabIndex = 7;
// //
// panelBlack // panelBlack
// //
panelBlack.BackColor = Color.Black; panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(151, 81); panelBlack.Location = new Point(132, 61);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack"; panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(49, 45); panelBlack.Size = new Size(43, 34);
panelBlack.TabIndex = 6; panelBlack.TabIndex = 6;
// //
// panelPurple // panelPurple
// //
panelPurple.BackColor = Color.Purple; panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(220, 81); panelPurple.Location = new Point(192, 61);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple"; panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(49, 45); panelPurple.Size = new Size(43, 34);
panelPurple.TabIndex = 5; panelPurple.TabIndex = 5;
// //
// panelWhite // panelWhite
// //
panelWhite.BackColor = Color.White; panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(16, 81); panelWhite.Location = new Point(14, 61);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite"; panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(49, 45); panelWhite.Size = new Size(43, 34);
panelWhite.TabIndex = 4; panelWhite.TabIndex = 4;
// //
// panelYellow // panelYellow
// //
panelYellow.BackColor = Color.Yellow; panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(220, 26); panelYellow.Location = new Point(192, 20);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow"; panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(49, 45); panelYellow.Size = new Size(43, 34);
panelYellow.TabIndex = 3; panelYellow.TabIndex = 3;
// //
// panelBlue // panelBlue
// //
panelBlue.BackColor = Color.Blue; panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(151, 26); panelBlue.Location = new Point(132, 20);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue"; panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(49, 45); panelBlue.Size = new Size(43, 34);
panelBlue.TabIndex = 2; panelBlue.TabIndex = 2;
// //
// panelGreen // panelGreen
// //
panelGreen.BackColor = Color.Green; panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(85, 26); panelGreen.Location = new Point(74, 20);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen"; panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(49, 45); panelGreen.Size = new Size(43, 34);
panelGreen.TabIndex = 1; panelGreen.TabIndex = 1;
// //
// panelRed // panelRed
// //
panelRed.BackColor = Color.Red; panelRed.BackColor = Color.Red;
panelRed.Location = new Point(16, 26); panelRed.Location = new Point(14, 20);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed"; panelRed.Name = "panelRed";
panelRed.Size = new Size(49, 45); panelRed.Size = new Size(43, 34);
panelRed.TabIndex = 0; panelRed.TabIndex = 0;
// //
// checkBoxGunTurret // checkBoxGunTurret
// //
checkBoxGunTurret.AutoSize = true; checkBoxGunTurret.AutoSize = true;
checkBoxGunTurret.Location = new Point(6, 114); checkBoxGunTurret.Location = new Point(5, 86);
checkBoxGunTurret.Margin = new Padding(3, 2, 3, 2);
checkBoxGunTurret.Name = "checkBoxGunTurret"; checkBoxGunTurret.Name = "checkBoxGunTurret";
checkBoxGunTurret.Size = new Size(299, 24); checkBoxGunTurret.Size = new Size(237, 19);
checkBoxGunTurret.TabIndex = 9; checkBoxGunTurret.TabIndex = 9;
checkBoxGunTurret.Text = "Признак наличия зенитного пулемёта"; checkBoxGunTurret.Text = "Признак наличия зенитного пулемёта";
checkBoxGunTurret.UseVisualStyleBackColor = true; checkBoxGunTurret.UseVisualStyleBackColor = true;
@ -177,57 +190,60 @@ namespace ProjectTank
// checkBoxMachineGun // checkBoxMachineGun
// //
checkBoxMachineGun.AutoSize = true; checkBoxMachineGun.AutoSize = true;
checkBoxMachineGun.Location = new Point(6, 144); checkBoxMachineGun.Location = new Point(5, 108);
checkBoxMachineGun.Margin = new Padding(3, 2, 3, 2);
checkBoxMachineGun.Name = "checkBoxMachineGun"; checkBoxMachineGun.Name = "checkBoxMachineGun";
checkBoxMachineGun.Size = new Size(281, 24); checkBoxMachineGun.Size = new Size(224, 19);
checkBoxMachineGun.TabIndex = 8; checkBoxMachineGun.TabIndex = 8;
checkBoxMachineGun.Text = "Признак наличия башни с орудием"; checkBoxMachineGun.Text = "Признак наличия башни с орудием";
checkBoxMachineGun.UseVisualStyleBackColor = true; checkBoxMachineGun.UseVisualStyleBackColor = true;
// //
// numericUpDownWeight // numericUpDownWeight
// //
numericUpDownWeight.Location = new Point(94, 70); numericUpDownWeight.Location = new Point(82, 52);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight"; numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(119, 27); numericUpDownWeight.Size = new Size(104, 23);
numericUpDownWeight.TabIndex = 5; numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
// //
// labelWeight // labelWeight
// //
labelWeight.AutoSize = true; labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 72); labelWeight.Location = new Point(10, 54);
labelWeight.Name = "labelWeight"; labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20); labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4; labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:"; labelWeight.Text = "Вес:";
// //
// numericUpDownSpeed // numericUpDownSpeed
// //
numericUpDownSpeed.Location = new Point(94, 32); numericUpDownSpeed.Location = new Point(82, 24);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed"; numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(119, 27); numericUpDownSpeed.Size = new Size(104, 23);
numericUpDownSpeed.TabIndex = 3; numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 }); numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
// //
// labelSpeed // labelSpeed
// //
labelSpeed.AutoSize = true; labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 34); labelSpeed.Location = new Point(10, 26);
labelSpeed.Name = "labelSpeed"; labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20); labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2; labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:"; labelSpeed.Text = "Скорость:";
// //
// labelModifiedObject // labelModifiedObject
// //
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle; labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(457, 161); labelModifiedObject.Location = new Point(400, 121);
labelModifiedObject.Name = "labelModifiedObject"; labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(144, 39); labelModifiedObject.Size = new Size(126, 30);
labelModifiedObject.TabIndex = 1; labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый"; labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter; labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
@ -236,9 +252,9 @@ namespace ProjectTank
// labelSimpleObject // labelSimpleObject
// //
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle; labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(308, 161); labelSimpleObject.Location = new Point(270, 121);
labelSimpleObject.Name = "labelSimpleObject"; labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(138, 39); labelSimpleObject.Size = new Size(121, 30);
labelSimpleObject.TabIndex = 0; labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой"; labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter; labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
@ -246,17 +262,19 @@ namespace ProjectTank
// //
// pictureBoxObject // pictureBoxObject
// //
pictureBoxObject.Location = new Point(19, 65); pictureBoxObject.Location = new Point(17, 49);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject"; pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(222, 152); pictureBoxObject.Size = new Size(217, 133);
pictureBoxObject.TabIndex = 1; pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false; pictureBoxObject.TabStop = false;
// //
// buttonAdd // buttonAdd
// //
buttonAdd.Location = new Point(655, 233); buttonAdd.Location = new Point(559, 206);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd"; buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29); buttonAdd.Size = new Size(121, 23);
buttonAdd.TabIndex = 2; buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить"; buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true; buttonAdd.UseVisualStyleBackColor = true;
@ -264,9 +282,10 @@ namespace ProjectTank
// //
// buttonCancel // buttonCancel
// //
buttonCancel.Location = new Point(784, 233); buttonCancel.Location = new Point(700, 206);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel"; buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29); buttonCancel.Size = new Size(109, 23);
buttonCancel.TabIndex = 3; buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена"; buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
@ -277,9 +296,10 @@ namespace ProjectTank
panelObject.Controls.Add(labelAdditionalColor); panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor); panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject); panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(636, 7); panelObject.Location = new Point(556, 5);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject"; panelObject.Name = "panelObject";
panelObject.Size = new Size(258, 220); panelObject.Size = new Size(253, 197);
panelObject.TabIndex = 4; panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop; panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter; panelObject.DragEnter += PanelObject_DragEnter;
@ -288,9 +308,9 @@ namespace ProjectTank
// //
labelAdditionalColor.AllowDrop = true; labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle; labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(148, 13); labelAdditionalColor.Location = new Point(139, 12);
labelAdditionalColor.Name = "labelAdditionalColor"; labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(93, 39); labelAdditionalColor.Size = new Size(95, 30);
labelAdditionalColor.TabIndex = 12; labelAdditionalColor.TabIndex = 12;
labelAdditionalColor.Text = "Доп. цвет"; labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
@ -301,9 +321,9 @@ namespace ProjectTank
// //
labelBodyColor.AllowDrop = true; labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle; labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(19, 13); labelBodyColor.Location = new Point(17, 12);
labelBodyColor.Name = "labelBodyColor"; labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(93, 39); labelBodyColor.Size = new Size(99, 30);
labelBodyColor.TabIndex = 11; labelBodyColor.TabIndex = 11;
labelBodyColor.Text = "Цвет"; labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter; labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@ -312,13 +332,14 @@ namespace ProjectTank
// //
// FormTankConfig // FormTankConfig
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(900, 274); ClientSize = new Size(821, 249);
Controls.Add(panelObject); Controls.Add(panelObject);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonAdd); Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig); Controls.Add(groupBoxConfig);
Margin = new Padding(3, 2, 3, 2);
Name = "FormTankConfig"; Name = "FormTankConfig";
Text = "Создание объекта"; Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false); groupBoxConfig.ResumeLayout(false);

View File

@ -1,4 +1,9 @@
using System.Drawing; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using ProjectTank;
namespace ProjectTank namespace ProjectTank
{ {
@ -6,15 +11,39 @@ namespace ProjectTank
{ {
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// <summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// 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 FormTankCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTankCollection>());
} }
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTankCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
} }

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View 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": "Tank"
}
}
}