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.CollectionGenericObjects;
using ProjectTank.Exceptions;
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию самолётов
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
@ -25,23 +30,22 @@ public abstract class AbstractCompany
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция машин
/// Коллекция самолётов
/// </summary>
protected ICollectionGenericObjects<DrawningTank2>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция машин</param>
public AbstractCompany(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningTank2> collection)
/// <param name="collection">Коллекция самолётов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
@ -53,7 +57,7 @@ public abstract class AbstractCompany
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="trackedMachine">Добавляемый объект</param>
/// <param name="tank2">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank2 tank2)
{
@ -66,9 +70,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <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>
@ -90,12 +94,20 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningTank2? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
}
}
return bitmap;
}
@ -104,6 +116,7 @@ public abstract class AbstractCompany
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <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>
where T : class
{
@ -7,7 +13,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
@ -17,7 +22,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
get
{
return Count;
return _collection.Count;
}
set
{
@ -37,37 +42,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
_collection = new();
}
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count + 1 > _maxCount) return -1;
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position < 0 || position > Count) return null;
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
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
{
/// <summary>
@ -47,13 +55,10 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position <= Count)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
else
return null;
}
public int Insert(T obj)
{
// TODO вставка в свободное место набора
@ -65,7 +70,7 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
@ -75,39 +80,55 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// ищется свободное место после этой позиции и идет туда
// если нет после, ищем до
// 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;
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)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= Count || position < 0) return null;
T? myObject = _collection[position];
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return myObject;
return temp;
}
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.CollectionGenericObjects;
using ProjectTank.Exceptions;
using System.Data;
using System.Text;
namespace ProjectTank.CollectionGenericObjects;
@ -7,7 +10,7 @@ namespace ProjectTank.CollectionGenericObjects;
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
internal class StorageCollection<T>
public class StorageCollection<T>
where T : DrawningTank2
{
/// <summary>
@ -24,16 +27,17 @@ internal class StorageCollection<T>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -49,15 +53,13 @@ internal class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
/// <summary>
@ -66,7 +68,6 @@ internal class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
@ -80,7 +81,6 @@ internal class StorageCollection<T>
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
return null;
@ -88,15 +88,14 @@ internal class StorageCollection<T>
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -136,22 +135,18 @@ internal class StorageCollection<T>
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// Загрузка информации по самолётам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException($"{filename} не существует");
}
using (StreamReader fs = File.OpenText(filename))
@ -159,11 +154,11 @@ internal class StorageCollection<T>
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new FileFormatException("Файл не подходит");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new IOException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
@ -178,25 +173,32 @@ internal class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTank2() is T tank2)
{
try
{
if (collection.Insert(tank2) == -1)
{
return false;
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
@ -212,3 +214,4 @@ internal class StorageCollection<T>
};
}
}

View File

@ -1,11 +1,11 @@
using ProjectTank.Drawnings;
using ProjectTank.Entities;
using System;
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Exceptions;
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - аренда поезда
/// Реализация абстрактной компании - СимбирФлот
/// </summary>
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)
{
}
/// <summary>
/// Отрисовка хранилища
/// </summary>
/// <param name="g">Графика</param>
int pamat_i = 0;
int pamat_j = 0;
protected override void DrawBackgound(Graphics g)
{
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)));
}
}
/// <summary>
/// Установка объекта в Хранилище
/// </summary>
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningTank2? drawningTank2 = _collection?.Get(n);
n++;
if (drawningTank2 != null)
try
{
drawningTank2.SetPictureSize(_pictureWidth, _pictureHeight);
drawningTank2.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
DrawningTank2? tank2 = _collection?.Get(n);
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(comboBoxSelectorCompany);
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.Size = new Size(218, 659);
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(191, 543);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -84,17 +86,19 @@ namespace ProjectTank
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
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.Size = new Size(212, 277);
panelCompanyTools.Size = new Size(185, 208);
panelCompanyTools.TabIndex = 9;
//
// buttonDelTank
//
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.Size = new Size(203, 49);
buttonDelTank.Size = new Size(177, 37);
buttonDelTank.TabIndex = 4;
buttonDelTank.Text = "Удалить танка ";
buttonDelTank.UseVisualStyleBackColor = true;
@ -103,9 +107,10 @@ namespace ProjectTank
// buttonRefresh
//
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.Size = new Size(202, 49);
buttonRefresh.Size = new Size(176, 37);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -114,19 +119,21 @@ namespace ProjectTank
// maskedTextBox
//
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.Name = "maskedTextBox";
maskedTextBox.Size = new Size(202, 27);
maskedTextBox.Size = new Size(176, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonAddTank
//
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.Size = new Size(205, 49);
buttonAddTank.Size = new Size(178, 37);
buttonAddTank.TabIndex = 1;
buttonAddTank.Text = "Добавление бронированной машины";
buttonAddTank.UseVisualStyleBackColor = true;
@ -135,9 +142,10 @@ namespace ProjectTank
// buttonGoToCheck
//
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.Size = new Size(203, 49);
buttonGoToCheck.Size = new Size(177, 37);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -145,9 +153,10 @@ namespace ProjectTank
//
// 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.Size = new Size(206, 34);
buttonCreateCompany.Size = new Size(180, 26);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -163,16 +172,18 @@ namespace ProjectTank
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
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.Size = new Size(212, 276);
panelStorage.Size = new Size(185, 207);
panelStorage.TabIndex = 7;
//
// 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.Size = new Size(206, 29);
buttonCollectinDel.Size = new Size(180, 22);
buttonCollectinDel.TabIndex = 6;
buttonCollectinDel.Text = "Удалить коллекцию";
buttonCollectinDel.UseVisualStyleBackColor = true;
@ -181,17 +192,19 @@ namespace ProjectTank
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(3, 131);
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 98);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(206, 104);
listBoxCollection.Size = new Size(181, 79);
listBoxCollection.TabIndex = 5;
//
// 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.Size = new Size(206, 29);
buttonCollectionAdd.Size = new Size(180, 22);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
@ -200,9 +213,10 @@ namespace ProjectTank
// radioButtonList
//
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.Size = new Size(80, 24);
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@ -211,9 +225,10 @@ namespace ProjectTank
// radioButtonMassive
//
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.Size = new Size(82, 24);
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@ -221,17 +236,18 @@ namespace ProjectTank
//
// 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.Size = new Size(206, 27);
textBoxCollectionName.Size = new Size(181, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(27, 10);
labelCollectionName.Location = new Point(24, 8);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20);
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
@ -241,18 +257,20 @@ namespace ProjectTank
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
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.Size = new Size(206, 28);
comboBoxSelectorCompany.Size = new Size(181, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
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.Size = new Size(931, 659);
pictureBox.Size = new Size(856, 543);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -262,7 +280,8 @@ namespace ProjectTank
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
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.Text = "menuStrip1";
//
@ -270,14 +289,14 @@ namespace ProjectTank
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
@ -285,7 +304,7 @@ namespace ProjectTank
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -299,13 +318,14 @@ namespace ProjectTank
//
// FormTankCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1149, 687);
ClientSize = new Size(1047, 567);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormTankCollection";
Text = "Коллекция танков";
groupBoxTools.ResumeLayout(false);

View File

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

View File

@ -77,8 +77,10 @@ namespace ProjectTank
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Margin = new Padding(3, 2, 3, 2);
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.TabStop = false;
groupBoxConfig.Text = "Параметры";
@ -93,9 +95,11 @@ namespace ProjectTank
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
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.Size = new Size(293, 143);
groupBoxColors.Padding = new Padding(3, 2, 3, 2);
groupBoxColors.Size = new Size(256, 107);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
@ -103,73 +107,82 @@ namespace ProjectTank
// panelGray
//
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.Size = new Size(49, 45);
panelGray.Size = new Size(43, 34);
panelGray.TabIndex = 7;
//
// panelBlack
//
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.Size = new Size(49, 45);
panelBlack.Size = new Size(43, 34);
panelBlack.TabIndex = 6;
//
// panelPurple
//
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.Size = new Size(49, 45);
panelPurple.Size = new Size(43, 34);
panelPurple.TabIndex = 5;
//
// panelWhite
//
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.Size = new Size(49, 45);
panelWhite.Size = new Size(43, 34);
panelWhite.TabIndex = 4;
//
// panelYellow
//
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.Size = new Size(49, 45);
panelYellow.Size = new Size(43, 34);
panelYellow.TabIndex = 3;
//
// panelBlue
//
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.Size = new Size(49, 45);
panelBlue.Size = new Size(43, 34);
panelBlue.TabIndex = 2;
//
// panelGreen
//
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.Size = new Size(49, 45);
panelGreen.Size = new Size(43, 34);
panelGreen.TabIndex = 1;
//
// panelRed
//
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.Size = new Size(49, 45);
panelRed.Size = new Size(43, 34);
panelRed.TabIndex = 0;
//
// checkBoxGunTurret
//
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.Size = new Size(299, 24);
checkBoxGunTurret.Size = new Size(237, 19);
checkBoxGunTurret.TabIndex = 9;
checkBoxGunTurret.Text = "Признак наличия зенитного пулемёта";
checkBoxGunTurret.UseVisualStyleBackColor = true;
@ -177,57 +190,60 @@ namespace ProjectTank
// checkBoxMachineGun
//
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.Size = new Size(281, 24);
checkBoxMachineGun.Size = new Size(224, 19);
checkBoxMachineGun.TabIndex = 8;
checkBoxMachineGun.Text = "Признак наличия башни с орудием";
checkBoxMachineGun.UseVisualStyleBackColor = true;
//
// 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.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(119, 27);
numericUpDownWeight.Size = new Size(104, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 72);
labelWeight.Location = new Point(10, 54);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// 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.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(119, 27);
numericUpDownSpeed.Size = new Size(104, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 34);
labelSpeed.Location = new Point(10, 26);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(457, 161);
labelModifiedObject.Location = new Point(400, 121);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(144, 39);
labelModifiedObject.Size = new Size(126, 30);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
@ -236,9 +252,9 @@ namespace ProjectTank
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(308, 161);
labelSimpleObject.Location = new Point(270, 121);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(138, 39);
labelSimpleObject.Size = new Size(121, 30);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
@ -246,17 +262,19 @@ namespace ProjectTank
//
// 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.Size = new Size(222, 152);
pictureBoxObject.Size = new Size(217, 133);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// 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.Size = new Size(94, 29);
buttonAdd.Size = new Size(121, 23);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
@ -264,9 +282,10 @@ namespace ProjectTank
//
// 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.Size = new Size(94, 29);
buttonCancel.Size = new Size(109, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -277,9 +296,10 @@ namespace ProjectTank
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
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.Size = new Size(258, 220);
panelObject.Size = new Size(253, 197);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
@ -288,9 +308,9 @@ namespace ProjectTank
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(148, 13);
labelAdditionalColor.Location = new Point(139, 12);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(93, 39);
labelAdditionalColor.Size = new Size(95, 30);
labelAdditionalColor.TabIndex = 12;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
@ -301,9 +321,9 @@ namespace ProjectTank
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(19, 13);
labelBodyColor.Location = new Point(17, 12);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(93, 39);
labelBodyColor.Size = new Size(99, 30);
labelBodyColor.TabIndex = 11;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@ -312,13 +332,14 @@ namespace ProjectTank
//
// FormTankConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(900, 274);
ClientSize = new Size(821, 249);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Margin = new Padding(3, 2, 3, 2);
Name = "FormTankConfig";
Text = "Создание объекта";
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
{
@ -6,15 +11,39 @@ namespace ProjectTank
{
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<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"
}
}
}