3 Commits
Lab_8 ... Lab_5

Author SHA1 Message Date
746003b2e2 s 2024-05-23 02:28:07 +04:00
73604d6abb s 2024-05-23 02:26:00 +04:00
9cb1345723 в 2024-05-22 21:50:20 +04:00
34 changed files with 210 additions and 1175 deletions

View File

@@ -8,15 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,4 @@
using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
@@ -29,14 +28,14 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция артиллерийских установок
/// Коллекция артиллирийских установок
/// </summary>
protected ICollectionGenericObjects<DrawningArtilleryUnit>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -50,7 +49,7 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
@@ -61,7 +60,7 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningArtilleryUnit сruiser)
{
return company._collection.Insert(сruiser, new DrawiningArtilleryUnitEqutables());
return company._collection.Insert(сruiser);
}
/// <summary>
@@ -97,25 +96,11 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningArtilleryUnit? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
DrawningArtilleryUnit? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningArtilleryUnit?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@@ -1,5 +1,4 @@
using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
@@ -23,7 +22,7 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width; i++)
for (int i = 0; i < width + 1; i++)
{
for (int j = 0; j < height + 1; ++j)
{
@@ -42,16 +41,13 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
catch (ObjectNotFoundException) { }
catch(PositionOutOfCollectionException e) { }
if (curWidth < width - 1)
if (curWidth < width)
curWidth++;
else
{

View File

@@ -1,75 +0,0 @@
namespace ProjectArtilleryUnit.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -1,6 +1,4 @@
using ProjectArtilleryUnit.Drawnings;
namespace ProjectArtilleryUnit.CollectionGenericObjects
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@@ -17,15 +15,14 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null);
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@@ -33,7 +30,7 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null);
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -48,23 +45,6 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@@ -1,7 +1,4 @@
using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
@@ -19,20 +16,7 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
@@ -43,43 +27,26 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
public T? Get(int position)
{
// TODO проверка позиции
// TODO выброc позиций, если выход за границы массива
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null)
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
// TODO вставка в конец набора
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningArtilleryUnit), (obj as DrawningArtilleryUnit))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) return -1;
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null)
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO вставка по позиции
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningArtilleryUnit), (obj as DrawningArtilleryUnit))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj);
return position;
@@ -88,26 +55,11 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
public T Remove(int position)
{
// TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO удаление объекта из списка
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@@ -1,5 +1,4 @@
using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
@@ -15,12 +14,8 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
public int SetMaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -37,8 +32,6 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -49,115 +42,74 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
public T? Get(int position)
{
// TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
{ return null; }
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null)
public int Insert(T obj)
{
// TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
for (int i = 0; i < Count; i++)
int index = 0;
while (index < _collection.Length)
{
if (comparer.Equals((_collection[i] as DrawningArtilleryUnit), (obj as DrawningArtilleryUnit))) throw new ObjectAlreadyInCollectionException(i);
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
_collection[index] = obj;
return index;
}
}
throw new CollectionOverflowException(Count);
index++;
}
return -1;
}
public int Insert(T obj, int position, IEqualityComparer<DrawningArtilleryUnit?>? comparer = null)
public int Insert(T obj, int position)
{
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO выбром позиций, если переполнение
// TODO вставка
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningArtilleryUnit), (obj as DrawningArtilleryUnit))) throw new ObjectAlreadyInCollectionException(i);
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
for (index = position + 1; index < _collection.Length; ++index)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
if (_collection[index] == null)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
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;
}
}
_collection[position] = obj;
return position;
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
// TODO выбром позиций, если выход за границы массива
// TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
if (position >= _collection.Length || position < 0)
{ return null; }
T obj = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
return obj;
}
}
}

View File

@@ -1,46 +1,27 @@
using ProjectArtilleryUnit.Drawnings;
using ProjectArtilleryUnit.Exceptions;
using System.Text;
namespace ProjectArtilleryUnit.CollectionGenericObjects
namespace ProjectArtilleryUnit.CollectionGenericObjects
{
// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningArtilleryUnit
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
@@ -48,40 +29,29 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(CollectionInfo name)
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (name == null || _storages.ContainsKey(name))
{
return;
}
if (_storages.ContainsKey(name)) return;
if (name.CollectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
if (name.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
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>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(CollectionInfo name)
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (name == null || !_storages.ContainsKey(name))
{
return;
}
_storages.Remove(name);
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
/// <summary>
@@ -89,144 +59,15 @@ namespace ProjectArtilleryUnit.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[CollectionInfo name]
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
{
return _storages[name];
}
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
throw new FormatException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningArtilleryUnit() is T artilleryUnit)
{
try
{
if (collection.Insert(artilleryUnit, new DrawiningArtilleryUnitEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}

View File

@@ -1,54 +0,0 @@
using System.Diagnostics.CodeAnalysis;
namespace ProjectArtilleryUnit.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningArtilleryUnitEqutables : IEqualityComparer<DrawningArtilleryUnit?>
{
public bool Equals(DrawningArtilleryUnit? x, DrawningArtilleryUnit? y)
{
if (x == null || x.EntityArtilleryUnit == null)
{
return false;
}
if (y == null || y.EntityArtilleryUnit == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityArtilleryUnit.Speed != y.EntityArtilleryUnit.Speed)
{
return false;
}
if (x.EntityArtilleryUnit.Weight != y.EntityArtilleryUnit.Weight)
{
return false;
}
if (x.EntityArtilleryUnit.BodyColor != y.EntityArtilleryUnit.BodyColor)
{
return false;
}
if (x is DrawningMilitaryArtilleryUnit && y is DrawningMilitaryArtilleryUnit)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningArtilleryUnit obj)
{
return obj.GetHashCode();
}
}

View File

@@ -19,20 +19,20 @@ public class DrawningArtilleryUnit
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки артиллерийской установки
/// Левая координата прорисовки автомобиля
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки артиллерийской установки
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки артиллерийской установки
/// Ширина прорисовки артиллирийской установки
/// </summary>
private readonly int _drawningArtilleryUnitWidth = 150;
/// <summary>
/// Высота прорисовки артиллерийской установки
/// Высота прорисовки артиллирийской установки
/// </summary>
private readonly int _drawningArtilleryUnitHeight = 50;
private readonly int _drawningEnginesWidth = 3;
@@ -57,7 +57,7 @@ public class DrawningArtilleryUnit
/// <summary>
/// Пустой онструктор
/// </summary>
public DrawningArtilleryUnit()
private DrawningArtilleryUnit()
{
_pictureWidth = null;
_pictureHeight = null;
@@ -86,15 +86,6 @@ public class DrawningArtilleryUnit
_pictureHeight = drawningCarHeight;
}
/// <summary>
/// конструктор
/// </summary>
/// <param name="entityArtilleryUnit"></param>
public DrawningArtilleryUnit(EntityArtilleryUnit entityArtilleryUnit)
{
EntityArtilleryUnit = entityArtilleryUnit;
}
/// <summary>
/// Установка границ поля
/// </summary>
@@ -192,7 +183,6 @@ public class DrawningArtilleryUnit
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
@@ -231,5 +221,6 @@ public class DrawningArtilleryUnit
g.DrawArc(pen, _startPosX.Value + 70, _startPosY.Value + 24, 10, 10, 0, 170);
g.DrawArc(pen, _startPosX.Value + 93, _startPosY.Value + 24, 10, 10, 0, 170);
}
}

View File

@@ -1,34 +0,0 @@
using ProjectArtilleryUnit.Entities;
namespace ProjectArtilleryUnit.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningArtilleryUnitCompareByColor : IComparer<DrawningArtilleryUnit?>
{
public int Compare(DrawningArtilleryUnit? x, DrawningArtilleryUnit? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityArtilleryUnit == null)
{
return 1;
}
if (y == null || y.EntityArtilleryUnit == null)
{
return -1;
}
var bodycolorCompare = x.EntityArtilleryUnit.BodyColor.Name.CompareTo(y.EntityArtilleryUnit.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityArtilleryUnit.Speed.CompareTo(y.EntityArtilleryUnit.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityArtilleryUnit.Weight.CompareTo(y.EntityArtilleryUnit.Weight);
}
}

View File

@@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningArtilleryUnitCompareByType : IComparer<DrawningArtilleryUnit?>
{
public int Compare(DrawningArtilleryUnit? x, DrawningArtilleryUnit? y)
{
if (x == null || x.EntityArtilleryUnit == null)
{
return 1;
}
if (y == null || y.EntityArtilleryUnit == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityArtilleryUnit.Speed.CompareTo(y.EntityArtilleryUnit.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityArtilleryUnit.Weight.CompareTo(y.EntityArtilleryUnit.Weight);
}
}

View File

@@ -22,14 +22,6 @@ namespace ProjectArtilleryUnit.Drawnings
EntityArtilleryUnit = new EntityMilitaryArtilleryUnit(speed, weight, bodyColor, additionalColor, muzzle, gun, luke);
}
public DrawningMilitaryArtilleryUnit(EntityArtilleryUnit entityArtilleryUnit)
{
if (entityArtilleryUnit != null)
{
EntityArtilleryUnit = entityArtilleryUnit;
}
}
public override void DrawTransport(Graphics g)
{
if (EntityArtilleryUnit == null || EntityArtilleryUnit is not EntityMilitaryArtilleryUnit entityMilitaryArtilleryUnit || !_startPosX.HasValue ||
@@ -69,7 +61,6 @@ namespace ProjectArtilleryUnit.Drawnings
{
g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value + 4, 25, 2);
}
}
}
}

View File

@@ -1,50 +0,0 @@
using ProjectArtilleryUnit.Entities;
namespace ProjectArtilleryUnit.Drawnings
{
public static class ExtentionDrawningArtilleryUnit
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningArtilleryUnit? CreateDrawningArtilleryUnit(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityArtilleryUnit? artilleryUnit = EntityMilitaryArtilleryUnit.CreateEntityMilitaryArtilleryUnit(strs);
if (artilleryUnit != null)
{
return new DrawningMilitaryArtilleryUnit(artilleryUnit);
}
artilleryUnit = EntityArtilleryUnit.CreateEntityArtilleryUnit(strs);
if (artilleryUnit != null)
{
return new DrawningArtilleryUnit(artilleryUnit);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawning ArtilleryUnit">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningArtilleryUnit drawningArtilleryUnit)
{
string[]? array = drawningArtilleryUnit?.EntityArtilleryUnit?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
}

View File

@@ -1,7 +1,7 @@
namespace ProjectArtilleryUnit.Entities;
/// <summary>
/// Класс-сущность "артиллерийская установка"
/// Класс-сущность "артиллирийская установка"
/// </summary>
public class EntityArtilleryUnit
{
@@ -31,7 +31,7 @@ public class EntityArtilleryUnit
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса артиллерийской установки
/// Инициализация полей объекта-класса артиллирийской установки
/// </summary>
/// <param name="speed">скорость</param>
/// <param name="weight">вес</param>
@@ -42,28 +42,4 @@ public class EntityArtilleryUnit
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityArtilleryUnit), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityArtilleryUnit? CreateEntityArtilleryUnit(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityArtilleryUnit))
{
return null;
}
return new EntityArtilleryUnit(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -33,30 +33,5 @@
Gun = gun;
Luke = luke;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityArtilleryUnit), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Muzzle.ToString(), Gun.ToString(), Luke.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityArtilleryUnit? CreateEntityMilitaryArtilleryUnit(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityArtilleryUnit))
{
return null;
}
return new EntityMilitaryArtilleryUnit(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}
}

View File

@@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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

@@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.Exceptions;
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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

@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectArtilleryUnit.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

@@ -41,7 +41,7 @@ namespace ProjectArtilleryUnit
}
/// <summary>
/// Метод прорисовки артиллерийской установки
/// Метод прорисовки круисера
/// </summary>
private void Draw()
{

View File

@@ -75,8 +75,10 @@
groupBoxConfing.Controls.Add(labelSimpleObject);
groupBoxConfing.Dock = DockStyle.Left;
groupBoxConfing.Location = new Point(0, 0);
groupBoxConfing.Margin = new Padding(3, 2, 3, 2);
groupBoxConfing.Name = "groupBoxConfing";
groupBoxConfing.Size = new Size(626, 262);
groupBoxConfing.Padding = new Padding(3, 2, 3, 2);
groupBoxConfing.Size = new Size(548, 196);
groupBoxConfing.TabIndex = 0;
groupBoxConfing.TabStop = false;
groupBoxConfing.Text = "Параметры";
@@ -91,9 +93,11 @@
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(327, 26);
groupBoxColors.Location = new Point(286, 20);
groupBoxColors.Margin = new Padding(3, 2, 3, 2);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(280, 154);
groupBoxColors.Padding = new Padding(3, 2, 3, 2);
groupBoxColors.Size = new Size(245, 116);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
@@ -101,141 +105,156 @@
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(217, 96);
panelPurple.Location = new Point(190, 72);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(48, 47);
panelPurple.Size = new Size(42, 35);
panelPurple.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(149, 96);
panelBlack.Location = new Point(130, 72);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(48, 47);
panelBlack.Size = new Size(42, 35);
panelBlack.TabIndex = 1;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(82, 96);
panelGray.Location = new Point(72, 72);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray";
panelGray.Size = new Size(48, 47);
panelGray.Size = new Size(42, 35);
panelGray.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(17, 96);
panelWhite.Location = new Point(15, 72);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(48, 47);
panelWhite.Size = new Size(42, 35);
panelWhite.TabIndex = 1;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(217, 31);
panelYellow.Location = new Point(190, 23);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(48, 47);
panelYellow.Size = new Size(42, 35);
panelYellow.TabIndex = 1;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(149, 31);
panelBlue.Location = new Point(130, 23);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(48, 47);
panelBlue.Size = new Size(42, 35);
panelBlue.TabIndex = 1;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(82, 31);
panelGreen.Location = new Point(72, 23);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(48, 47);
panelGreen.Size = new Size(42, 35);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(17, 31);
panelRed.Location = new Point(15, 23);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(48, 47);
panelRed.Size = new Size(42, 35);
panelRed.TabIndex = 0;
//
// checkBoxLuke
//
checkBoxLuke.AutoSize = true;
checkBoxLuke.Location = new Point(6, 217);
checkBoxLuke.Location = new Point(5, 163);
checkBoxLuke.Margin = new Padding(3, 2, 3, 2);
checkBoxLuke.Name = "checkBoxLuke";
checkBoxLuke.Size = new Size(202, 24);
checkBoxLuke.Size = new Size(155, 19);
checkBoxLuke.TabIndex = 8;
checkBoxLuke.Text = "Признак наличие пушки";
checkBoxLuke.Text = "Признак наличие люка";
checkBoxLuke.UseVisualStyleBackColor = true;
//
// checkBoxGun
//
checkBoxGun.AutoSize = true;
checkBoxGun.Location = new Point(6, 169);
checkBoxGun.Location = new Point(5, 127);
checkBoxGun.Margin = new Padding(3, 2, 3, 2);
checkBoxGun.Name = "checkBoxGun";
checkBoxGun.Size = new Size(215, 24);
checkBoxGun.Size = new Size(182, 19);
checkBoxGun.TabIndex = 7;
checkBoxGun.Text = "Признак наличие шлюпок";
checkBoxGun.Text = "Признак наличие установки";
checkBoxGun.UseVisualStyleBackColor = true;
checkBoxGun.CheckedChanged += checkBoxGun_CheckedChanged;
//
// checkBoxMuzzle
//
checkBoxMuzzle.AutoSize = true;
checkBoxMuzzle.Location = new Point(6, 123);
checkBoxMuzzle.Location = new Point(5, 92);
checkBoxMuzzle.Margin = new Padding(3, 2, 3, 2);
checkBoxMuzzle.Name = "checkBoxMuzzle";
checkBoxMuzzle.Size = new Size(321, 24);
checkBoxMuzzle.Size = new Size(151, 19);
checkBoxMuzzle.TabIndex = 6;
checkBoxMuzzle.Text = "Признак наличие вертолетной площадки";
checkBoxMuzzle.Text = "Признак наличие дула";
checkBoxMuzzle.UseVisualStyleBackColor = true;
checkBoxMuzzle.CheckedChanged += checkBoxMuzzle_CheckedChanged;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(94, 68);
numericUpDownWeight.Location = new Point(82, 51);
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(114, 27);
numericUpDownWeight.Size = new Size(100, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(27, 70);
labelWeight.Location = new Point(24, 52);
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(114, 27);
numericUpDownSpeed.Size = new Size(100, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 32);
labelSpeed.Location = new Point(10, 24);
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(476, 203);
labelModifiedObject.Location = new Point(416, 152);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(131, 44);
labelModifiedObject.Size = new Size(115, 34);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
@@ -244,9 +263,9 @@
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(327, 203);
labelSimpleObject.Location = new Point(286, 152);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(130, 44);
labelSimpleObject.Size = new Size(114, 34);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
@@ -254,17 +273,19 @@
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(11, 56);
pictureBoxObject.Location = new Point(10, 42);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(183, 125);
pictureBoxObject.Size = new Size(160, 94);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(632, 212);
buttonAdd.Location = new Point(553, 159);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.Size = new Size(82, 22);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
@@ -272,9 +293,10 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(740, 212);
buttonCancel.Location = new Point(648, 159);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@@ -285,9 +307,10 @@
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(632, 12);
panelObject.Location = new Point(553, 9);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject";
panelObject.Size = new Size(205, 194);
panelObject.Size = new Size(179, 146);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
@@ -296,9 +319,9 @@
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(108, 11);
labelAdditionalColor.Location = new Point(94, 8);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(83, 36);
labelAdditionalColor.Size = new Size(73, 28);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
@@ -309,9 +332,9 @@
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(11, 11);
labelBodyColor.Location = new Point(10, 8);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(83, 36);
labelBodyColor.Size = new Size(73, 28);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@@ -320,13 +343,14 @@
//
// FormArtilleryUnitConfing
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(838, 262);
ClientSize = new Size(733, 196);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfing);
Margin = new Padding(3, 2, 3, 2);
Name = "FormArtilleryUnitConfing";
Text = "Создание объекта";
groupBoxConfing.ResumeLayout(false);

View File

@@ -62,8 +62,8 @@ namespace ProjectArtilleryUnit
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>labelSimpleObject
/// <param name="e"></param>labelSimpleObject
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
@@ -171,6 +171,17 @@ namespace ProjectArtilleryUnit
ArtilleryUnitDelegate?.Invoke(_artilleryUnit);
Close();
}
}
private void checkBoxMuzzle_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBoxGun_CheckedChanged(object sender, EventArgs e)
{
}
}
}

View File

@@ -40,25 +40,16 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
ButtonAddArtilleryUnit = new Button();
buttonRefresh = new Button();
ButtonRemoveArtilleryUnit = new Button();
maskedTextBoxPosision = new MaskedTextBox();
buttonGetToTest = new Button();
pictureBoxArtilleryUnit = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -68,11 +59,11 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(552, 24);
groupBoxTools.Location = new Point(522, 0);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(194, 492);
groupBoxTools.Size = new Size(182, 490);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
@@ -101,7 +92,7 @@
panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(188, 212);
panelStorage.Size = new Size(176, 212);
panelStorage.TabIndex = 6;
//
// buttonCollectionDel
@@ -191,8 +182,6 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(ButtonAddArtilleryUnit);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ButtonRemoveArtilleryUnit);
@@ -205,30 +194,6 @@
panelCompanyTools.Size = new Size(189, 206);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSortByColor.Location = new Point(17, 181);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(163, 23);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Right;
buttonSortByType.Location = new Point(17, 149);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(163, 28);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// ButtonAddArtilleryUnit
//
ButtonAddArtilleryUnit.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@@ -236,7 +201,7 @@
ButtonAddArtilleryUnit.Location = new Point(16, 2);
ButtonAddArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
ButtonAddArtilleryUnit.Name = "ButtonAddArtilleryUnit";
ButtonAddArtilleryUnit.Size = new Size(163, 39);
ButtonAddArtilleryUnit.Size = new Size(163, 55);
ButtonAddArtilleryUnit.TabIndex = 1;
ButtonAddArtilleryUnit.Text = "добваление артиллерийской установки";
ButtonAddArtilleryUnit.UseVisualStyleBackColor = true;
@@ -245,10 +210,10 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(17, 123);
buttonRefresh.Location = new Point(16, 170);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(163, 22);
buttonRefresh.Size = new Size(163, 31);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -257,18 +222,18 @@
// ButtonRemoveArtilleryUnit
//
ButtonRemoveArtilleryUnit.Anchor = AnchorStyles.Right;
ButtonRemoveArtilleryUnit.Location = new Point(17, 74);
ButtonRemoveArtilleryUnit.Location = new Point(16, 88);
ButtonRemoveArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveArtilleryUnit.Name = "ButtonRemoveArtilleryUnit";
ButtonRemoveArtilleryUnit.Size = new Size(163, 21);
ButtonRemoveArtilleryUnit.Size = new Size(163, 46);
ButtonRemoveArtilleryUnit.TabIndex = 3;
ButtonRemoveArtilleryUnit.Text = "удалить установку";
ButtonRemoveArtilleryUnit.Text = "удалить артиллерийскую установку";
ButtonRemoveArtilleryUnit.UseVisualStyleBackColor = true;
ButtonRemoveArtilleryUnit.Click += ButtonRemoveArtilleryUnit_Click;
//
// maskedTextBoxPosision
//
maskedTextBoxPosision.Location = new Point(16, 45);
maskedTextBoxPosision.Location = new Point(16, 61);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision";
@@ -279,10 +244,10 @@
// buttonGetToTest
//
buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(16, 99);
buttonGetToTest.Location = new Point(16, 138);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(163, 20);
buttonGetToTest.Size = new Size(163, 30);
buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true;
@@ -291,78 +256,30 @@
// pictureBoxArtilleryUnit
//
pictureBoxArtilleryUnit.Dock = DockStyle.Fill;
pictureBoxArtilleryUnit.Location = new Point(0, 24);
pictureBoxArtilleryUnit.Location = new Point(0, 0);
pictureBoxArtilleryUnit.Margin = new Padding(3, 2, 3, 2);
pictureBoxArtilleryUnit.Name = "pictureBoxArtilleryUnit";
pictureBoxArtilleryUnit.Size = new Size(552, 492);
pictureBoxArtilleryUnit.Size = new Size(522, 490);
pictureBoxArtilleryUnit.TabIndex = 1;
pictureBoxArtilleryUnit.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(746, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
//
// FormArtilleryUnitsCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(746, 516);
ClientSize = new Size(704, 490);
Controls.Add(pictureBoxArtilleryUnit);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormArtilleryUnitsCollection";
Text = "FormArtilleryUnitsCollection";
Load += FormArtilleryUnitsCollection_Load;
groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxArtilleryUnit).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -385,13 +302,5 @@
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,5 +1,4 @@
using Microsoft.Extensions.Logging;
using ProjectArtilleryUnit.CollectionGenericObjects;
using ProjectArtilleryUnit.CollectionGenericObjects;
using ProjectArtilleryUnit.Drawnings;
using System.Windows.Forms;
@@ -17,19 +16,13 @@ namespace ProjectArtilleryUnit
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormArtilleryUnitsCollection(ILogger<FormArtilleryUnitsCollection> logger)
public FormArtilleryUnitsCollection()
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@@ -42,11 +35,6 @@ namespace ProjectArtilleryUnit
panelCompanyTools.Enabled = false;
}
/// <summary>
/// добавление артиллерийской установки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddArtilleryUnit_Click(object sender, EventArgs e)
{
FormArtilleryUnitConfing form = new();
@@ -60,24 +48,21 @@ namespace ProjectArtilleryUnit
/// Добавление артиллерийской установки в коллекцию
/// </summary>
/// <param name="artilleryUnit"></param>
private void SetArtilleryUnit(DrawningArtilleryUnit? artilleryUnit)
private void SetArtilleryUnit(DrawningArtilleryUnit artilleryUnit)
{
if (_company == null || artilleryUnit == null)
{
return;
}
try
if (_company + artilleryUnit != -1)
{
var res = _company + artilleryUnit;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxArtilleryUnit.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("Не удалось добавить объект");
}
}
@@ -98,18 +83,14 @@ namespace ProjectArtilleryUnit
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
try
if (_company - pos != null)
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
MessageBox.Show("объект удален");
pictureBoxArtilleryUnit.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("не удалось удалить объект");
}
}
@@ -162,7 +143,8 @@ namespace ProjectArtilleryUnit
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
@@ -174,11 +156,7 @@ namespace ProjectArtilleryUnit
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation("Добавление коллекции");
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
@@ -198,11 +176,7 @@ namespace ProjectArtilleryUnit
{
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation("Коллекция удалена");
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
@@ -214,7 +188,7 @@ namespace ProjectArtilleryUnit
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@@ -223,7 +197,7 @@ namespace ProjectArtilleryUnit
}
/// <summary>
/// Создание компании
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@@ -234,111 +208,23 @@ namespace ProjectArtilleryUnit
MessageBox.Show("Коллекция не выбрана");
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningArtilleryUnit>? collection = _storageCollection[collectionInfo];
ICollectionGenericObjects<DrawningArtilleryUnit>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new ArtilleryUnitDockingService(pictureBoxArtilleryUnit.Width, pictureBoxArtilleryUnit.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareArtilleryUnits(new DrawningArtilleryUnitCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareArtilleryUnits(new DrawningArtilleryUnitCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareArtilleryUnits(IComparer<DrawningArtilleryUnit?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBoxArtilleryUnit.Image = _company.Show();
}
private void FormArtilleryUnitsCollection_Load(object sender, EventArgs e)
{
}
}
}

View File

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

View File

@@ -1,8 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectArtilleryUnit
{
internal static class Program
@@ -15,31 +10,7 @@ namespace ProjectArtilleryUnit
{
// To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormArtilleryUnitsCollection>());
Application.Run(new FormArtilleryUnitsCollection());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormArtilleryUnitsCollection>().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}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="artilleryUnitlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@@ -1,20 +0,0 @@
{
"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": "artilleryUnit"
}
}
}