Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c9a539e25 | |||
| 1fe1d75be5 | |||
| 44f2614f95 | |||
| 88fde22201 | |||
| 1641bff131 | |||
| d4b74a7d92 | |||
| ceb90e2be8 |
@@ -1,4 +1,5 @@
|
|||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
|
using ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
namespace ProjectBattleship.CollectionGenericObjects;
|
namespace ProjectBattleship.CollectionGenericObjects;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -30,8 +31,7 @@ public abstract class AbstractCompany
|
|||||||
/// Вычисление максимального количества элементов, который можно
|
/// Вычисление максимального количества элементов, который можно
|
||||||
/// разместить в окне
|
/// разместить в окне
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private int GetMaxCount => _pictureWidth * _pictureHeight /
|
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||||
(_placeSizeWidth * _placeSizeHeight);
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -44,7 +44,7 @@ public abstract class AbstractCompany
|
|||||||
_pictureWidth = picWidth;
|
_pictureWidth = picWidth;
|
||||||
_pictureHeight = picHeight;
|
_pictureHeight = picHeight;
|
||||||
_collection = collection;
|
_collection = collection;
|
||||||
_collection.SetMaxCount = GetMaxCount;
|
_collection.MaxCount = GetMaxCount;
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перегрузка оператора сложения для класса
|
/// Перегрузка оператора сложения для класса
|
||||||
@@ -85,20 +85,30 @@ public abstract class AbstractCompany
|
|||||||
{
|
{
|
||||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||||
Graphics graphics = Graphics.FromImage(bitmap);
|
Graphics graphics = Graphics.FromImage(bitmap);
|
||||||
DrawBackgound(graphics);
|
DrawBackground(graphics);
|
||||||
|
|
||||||
SetObjectsPosition();
|
SetObjectsPosition();
|
||||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
DrawingWarship? obj = _collection?.Get(i);
|
DrawingWarship? obj = _collection?.Get(i);
|
||||||
obj?.DrawTransport(graphics);
|
obj?.DrawTransport(graphics);
|
||||||
}
|
}
|
||||||
|
catch (ObjectNotFoundException e)
|
||||||
|
{ }
|
||||||
|
catch (PositionOutOfCollectionException e)
|
||||||
|
{ }
|
||||||
|
}
|
||||||
|
|
||||||
return bitmap;
|
return bitmap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Вывод заднего фона
|
/// Вывод заднего фона
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="g"></param>
|
/// <param name="g"></param>
|
||||||
protected abstract void DrawBackgound(Graphics g);
|
protected abstract void DrawBackground(Graphics g);
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Расстановка объектов
|
/// Расстановка объектов
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
|
using ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
namespace ProjectBattleship.CollectionGenericObjects;
|
namespace ProjectBattleship.CollectionGenericObjects;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -17,7 +18,7 @@ public class Docks : AbstractCompany
|
|||||||
base(picWidth, picHeight, collection)
|
base(picWidth, picHeight, collection)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
protected override void DrawBackgound(Graphics g)
|
protected override void DrawBackground(Graphics g)
|
||||||
{
|
{
|
||||||
int width = _pictureWidth / _placeSizeWidth;
|
int width = _pictureWidth / _placeSizeWidth;
|
||||||
int height = _pictureHeight / _placeSizeHeight;
|
int height = _pictureHeight / _placeSizeHeight;
|
||||||
@@ -40,30 +41,29 @@ public class Docks : AbstractCompany
|
|||||||
}
|
}
|
||||||
protected override void SetObjectsPosition()
|
protected override void SetObjectsPosition()
|
||||||
{
|
{
|
||||||
if (_collection == null) return;
|
|
||||||
int width = _pictureWidth / _placeSizeWidth;
|
int width = _pictureWidth / _placeSizeWidth;
|
||||||
int height = _pictureHeight / _placeSizeHeight;
|
int height = _pictureHeight / _placeSizeHeight;
|
||||||
|
|
||||||
int curWidth = width - 1;
|
int curWidth = width - 1;
|
||||||
int curHeight = 0;
|
int curHeight = 0;
|
||||||
|
|
||||||
for (int i = 0; i < _collection.Count; i++)
|
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||||
{
|
{
|
||||||
DrawingWarship? _warship = _collection.Get(i);
|
try
|
||||||
if (_warship != null)
|
|
||||||
{
|
{
|
||||||
if (_warship.SetPictureSize(_pictureWidth, _pictureHeight))
|
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||||
{
|
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
|
||||||
_warship.SetPosition(_placeSizeWidth * curWidth + 20,
|
|
||||||
curHeight * _placeSizeHeight + 15);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
|
catch (PositionOutOfCollectionException e) { }
|
||||||
|
if (curWidth > 0)
|
||||||
curWidth--;
|
curWidth--;
|
||||||
if (curWidth < 0)
|
else
|
||||||
{
|
{
|
||||||
curHeight++;
|
|
||||||
curWidth = width - 1;
|
curWidth = width - 1;
|
||||||
|
curHeight++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (curHeight >= height)
|
if (curHeight >= height)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -4,22 +4,25 @@
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||||
public interface ICollectionGenericObjects<T>
|
public interface ICollectionGenericObjects<T>
|
||||||
where T : class
|
where T : class
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Количество объектов в коллекции
|
/// Количество объектов в коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
int Count { get; }
|
int Count { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Установка максимального количества элементов
|
/// Установка максимального количества элементов
|
||||||
/// </summary>
|
/// </summary>
|
||||||
int SetMaxCount { set; }
|
int MaxCount { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление объекта в коллекцию
|
/// Добавление объекта в коллекцию
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj">Добавляемый объект</param>
|
/// <param name="obj">Добавляемый объект</param>
|
||||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||||
int Insert(T obj);
|
int Insert(T obj);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление объекта в коллекцию на конкретную позицию
|
/// Добавление объекта в коллекцию на конкретную позицию
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -27,16 +30,29 @@ public interface ICollectionGenericObjects<T>
|
|||||||
/// <param name="position">Позиция</param>
|
/// <param name="position">Позиция</param>
|
||||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||||
int Insert(T obj, int position);
|
int Insert(T obj, int position);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление объекта из коллекции с конкретной позиции
|
/// Удаление объекта из коллекции с конкретной позиции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="position">Позиция</param>
|
/// <param name="position">Позиция</param>
|
||||||
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
||||||
T? Remove(int position);
|
T? Remove(int position);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение объекта по позиции
|
/// Получение объекта по позиции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="position">Позиция</param>
|
/// <param name="position">Позиция</param>
|
||||||
/// <returns>Объект</returns>
|
/// <returns>Объект</returns>
|
||||||
T? Get(int position);
|
T? Get(int position);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получение типа коллекции
|
||||||
|
/// </summary>
|
||||||
|
CollectionType GetCollectionType { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получение объектов коллекции по одному
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||||
|
IEnumerable<T?> GetItems();
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,43 @@
|
|||||||
namespace ProjectBattleship.CollectionGenericObjects;
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
|
using ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
|
|
||||||
|
namespace Battleship.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||||
where T : class
|
where T : class
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Список объектов, которые храним
|
/// Список объектов, которые храним
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private readonly List<T?> _collection;
|
private readonly List<T?> _collection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Максимально допустимое число объектов в списке
|
/// Максимально допустимое число объектов в списке
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private int _maxCount;
|
private int _maxCount;
|
||||||
|
|
||||||
public int Count => _collection.Count;
|
public int Count => _collection.Count;
|
||||||
|
|
||||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
public int MaxCount
|
||||||
|
{
|
||||||
|
set
|
||||||
|
{
|
||||||
|
if (value > 0)
|
||||||
|
{
|
||||||
|
_maxCount = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get
|
||||||
|
{
|
||||||
|
|
||||||
|
return Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CollectionType GetCollectionType => CollectionType.List;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
@@ -27,33 +46,40 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
{
|
{
|
||||||
_collection = new();
|
_collection = new();
|
||||||
}
|
}
|
||||||
|
public T Get(int position)
|
||||||
public T? Get(int position)
|
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count) return null;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T? obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count - 1;
|
return Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T? obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
if (position < 0 || position >= Count) return -1;
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
|
|
||||||
public T? Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count) return null;
|
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
T? obj = _collection[position];
|
T obj = _collection[position];
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public IEnumerable<T?> GetItems()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < Count; ++i)
|
||||||
|
{
|
||||||
|
yield return _collection[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
namespace ProjectBattleship.CollectionGenericObjects;
|
using ProjectBattleship.Exceptions;
|
||||||
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
|
|
||||||
|
namespace Battleship.CollectionGenericObjects;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -11,8 +14,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private T?[] _collection;
|
private T?[] _collection;
|
||||||
public int Count => _collection.Length;
|
public int Count => _collection.Length;
|
||||||
public int SetMaxCount
|
/// <summary>
|
||||||
|
/// Установка максимального кол-ва объектов
|
||||||
|
/// </summary>
|
||||||
|
public int MaxCount
|
||||||
{
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
return _collection.Length;
|
||||||
|
}
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
if (value > 0)
|
if (value > 0)
|
||||||
@@ -28,6 +38,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -35,60 +48,91 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
{
|
{
|
||||||
_collection = Array.Empty<T?>();
|
_collection = Array.Empty<T?>();
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Получение объекта по позиции
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="position">Позиция (индекс)</param>
|
||||||
|
/// <returns></returns>
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position > Count)
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||||
{
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
return Insert(obj, 0);
|
// вставка в свободное место набора
|
||||||
|
for (int i = 0; i < Count; i++)
|
||||||
|
{
|
||||||
|
if (_collection[i] == null)
|
||||||
|
{
|
||||||
|
_collection[i] = obj;
|
||||||
|
return i;
|
||||||
}
|
}
|
||||||
public int Insert(T obj, int position)
|
|
||||||
{
|
|
||||||
if (position < 0 || position > Count)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_collection[position] == null)
|
throw new CollectionOverflowException(Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
|
// проверка позиции
|
||||||
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||||
|
|
||||||
|
if (_collection[position] != null)
|
||||||
|
{
|
||||||
|
bool pushed = false;
|
||||||
|
for (int index = position + 1; index < Count; index++)
|
||||||
|
{
|
||||||
|
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;
|
_collection[position] = obj;
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = position + 1; i < Count; i++)
|
|
||||||
{
|
|
||||||
if (_collection[i] == null)
|
|
||||||
{
|
|
||||||
_collection[i] = obj;
|
|
||||||
return position;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = position - 1; i >= 0; i--)
|
|
||||||
{
|
|
||||||
if (_collection[i] == null)
|
|
||||||
{
|
|
||||||
_collection[i] = obj;
|
|
||||||
return position;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
public T? Remove(int position)
|
public T? Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position > Count || _collection[position] == null)
|
// проверка позиции
|
||||||
{
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
T? obj = _collection[position];
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
|
|
||||||
|
T? temp = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return obj;
|
return temp;
|
||||||
|
}
|
||||||
|
public IEnumerable<T?> GetItems()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < _collection.Length; ++i)
|
||||||
|
{
|
||||||
|
yield return _collection[i];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,39 @@
|
|||||||
namespace ProjectBattleship.CollectionGenericObjects;
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
|
using ProjectBattleship.DrawingObject;
|
||||||
|
using ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
|
namespace Battleship.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Класс-хранилище коллекций
|
/// Класс-хранилище коллекций
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public class StorageCollection<T>
|
public class StorageCollection<T> where T : DrawingWarship
|
||||||
where T : class
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Словарь (хранилище) с коллекциями
|
/// Словарь (хранилище) с коллекциями
|
||||||
/// </summary>
|
/// </summary>
|
||||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Возвращение списка названий коллекций
|
/// Возвращение списка названий коллекций
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public List<string> Keys => _storages.Keys.ToList();
|
public List<string> Keys => _storages.Keys.ToList();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ключевое слово, с которого должен начинаться файл
|
||||||
|
/// </summary>
|
||||||
|
private readonly string _collectionKey = "CollectionsStorage";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Разделитель для записи ключа и значения элемента словаря
|
||||||
|
/// </summary>
|
||||||
|
private readonly string _separatorForKeyValue = "|";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Разделитель для записей коллекции данных в файл
|
||||||
|
/// </summary>
|
||||||
|
private readonly string _separatorItems = ";";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -23,7 +41,6 @@ where T : class
|
|||||||
{
|
{
|
||||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление коллекции в хранилище
|
/// Добавление коллекции в хранилище
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -31,16 +48,18 @@ where T : class
|
|||||||
/// <param name="collectionType">тип коллекции</param>
|
/// <param name="collectionType">тип коллекции</param>
|
||||||
public void AddCollection(string name, CollectionType collectionType)
|
public void AddCollection(string name, CollectionType collectionType)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(name)) return;
|
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
||||||
if (_storages.ContainsKey(name)) return;
|
return;
|
||||||
if (collectionType == CollectionType.None) return;
|
switch (collectionType)
|
||||||
if (collectionType == CollectionType.Massive)
|
|
||||||
{
|
{
|
||||||
_storages[name] = new MassiveGenericObjects<T>();
|
case CollectionType.List:
|
||||||
}
|
_storages.Add(name, new ListGenericObjects<T>());
|
||||||
else if (collectionType == CollectionType.List)
|
break;
|
||||||
{
|
case CollectionType.Massive:
|
||||||
_storages[name] = new ListGenericObjects<T>();
|
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,12 +69,8 @@ where T : class
|
|||||||
/// <param name="name">Название коллекции</param>
|
/// <param name="name">Название коллекции</param>
|
||||||
public void DelCollection(string name)
|
public void DelCollection(string name)
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name))
|
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
|
||||||
{
|
|
||||||
_storages.Remove(name);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Доступ к коллекции
|
/// Доступ к коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -65,11 +80,125 @@ where T : class
|
|||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name))
|
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
|
||||||
{
|
return value;
|
||||||
return _storages[name];
|
|
||||||
}
|
|
||||||
return null;
|
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<string, 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.GetCollectionType);
|
||||||
|
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 != 4)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||||
|
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||||
|
if (collection == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||||
|
|
||||||
|
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
foreach (string elem in set)
|
||||||
|
{
|
||||||
|
if (elem?.CreateDrawingWarship() is T Warship)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (collection.Insert(Warship) == -1)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
|
{
|
||||||
|
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_storages.Add(record[0], collection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) => collectionType switch
|
||||||
|
{
|
||||||
|
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||||
|
CollectionType.List => new ListGenericObjects<T>(),
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,12 @@ namespace ProjectBattleship.DrawingObject;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class DrawingBattleship : DrawingWarship
|
public class DrawingBattleship : DrawingWarship
|
||||||
{
|
{
|
||||||
|
public DrawingBattleship(EntityWarship warship) : base(150, 50)
|
||||||
|
{
|
||||||
|
EntityWarship = warship;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -19,6 +25,7 @@ public class DrawingBattleship : DrawingWarship
|
|||||||
{
|
{
|
||||||
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment);
|
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void DrawTransport(Graphics g)
|
public override void DrawTransport(Graphics g)
|
||||||
{
|
{
|
||||||
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship ||
|
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship ||
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ public class DrawingWarship
|
|||||||
/// Верхняя кооридната прорисовки военного корабля
|
/// Верхняя кооридната прорисовки военного корабля
|
||||||
/// </summary>
|
/// </summary>
|
||||||
protected int? _startPosY;
|
protected int? _startPosY;
|
||||||
|
private EntityWarship warship;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ширина прорисовки военного корабля
|
/// Ширина прорисовки военного корабля
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -63,6 +65,14 @@ public class DrawingWarship
|
|||||||
_drawingWarshipWidth = drawingWarshipWidth;
|
_drawingWarshipWidth = drawingWarshipWidth;
|
||||||
_pictureHeight = drawingWarshipHeight;
|
_pictureHeight = drawingWarshipHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public DrawingWarship(EntityWarship warship)
|
||||||
|
{
|
||||||
|
EntityWarship = warship;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Установка границ поля
|
/// Установка границ поля
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using ProjectBattleship.Entities;
|
||||||
|
namespace ProjectBattleship.DrawingObject;
|
||||||
|
/// <summary>
|
||||||
|
/// Расширение для класса EntityWarship
|
||||||
|
/// </summary>
|
||||||
|
public static class ExtentionDrawingWarship
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Разделитель для записи информации по объекту в файл
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string _separatorForObject = ":";
|
||||||
|
/// <summary>
|
||||||
|
/// Создание объекта из строки
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="info">Строка с данными для создания объекта</param>
|
||||||
|
/// <returns>Объект</returns>
|
||||||
|
public static DrawingWarship? CreateDrawingWarship(this string info)
|
||||||
|
{
|
||||||
|
string[] strs = info.Split(_separatorForObject);
|
||||||
|
EntityWarship? warship = EntityBattleship.CreateEntityBattleship(strs);
|
||||||
|
if (warship != null)
|
||||||
|
{
|
||||||
|
return new DrawingBattleship(warship);
|
||||||
|
}
|
||||||
|
warship = EntityWarship.CreateEntityWarship(strs);
|
||||||
|
if (warship != null)
|
||||||
|
{
|
||||||
|
return new DrawingWarship(warship);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Получение данных для сохранения в файл
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="drawingWarship">Сохраняемый объект</param>
|
||||||
|
/// <returns>Строка с данными по объекту</returns>
|
||||||
|
public static string GetDataForSave(this DrawingWarship drawingWarship)
|
||||||
|
{
|
||||||
|
string[]? array = drawingWarship?.EntityWarship?.GetStringRepresentation();
|
||||||
|
if (array == null)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
return string.Join(_separatorForObject, array);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
namespace ProjectBattleship.Entities;
|
using System.Net.Sockets;
|
||||||
|
|
||||||
|
namespace ProjectBattleship.Entities;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Класс-сущность "Линкор"
|
/// Класс-сущность "Линкор"
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -19,4 +21,28 @@ public class EntityBattleship : EntityWarship
|
|||||||
Turret = turret;
|
Turret = turret;
|
||||||
RocketCompartment = rocketCompartment;
|
RocketCompartment = rocketCompartment;
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Получение строк со значениями свойств объекта класса-сущности
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override string[] GetStringRepresentation()
|
||||||
|
{
|
||||||
|
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(),
|
||||||
|
BodyColor.Name, AdditionalColor.Name, RocketCompartment.ToString(), Turret.ToString() };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Создание объекта из массива строк
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="strs"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static EntityWarship? CreateEntityBattleship(string[] strs)
|
||||||
|
{
|
||||||
|
if (strs.Length != 7 || strs[0] != nameof(EntityBattleship))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
|
||||||
|
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
namespace ProjectBattleship.Entities;
|
namespace ProjectBattleship.Entities;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Класс-сущность "Автомобиль"
|
/// Класс-сущность "Военный корабль"
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class EntityWarship
|
public class EntityWarship
|
||||||
{
|
{
|
||||||
@@ -18,4 +18,27 @@ public class EntityWarship
|
|||||||
Weight = weight;
|
Weight = weight;
|
||||||
BodyColor = bodyColor;
|
BodyColor = bodyColor;
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Получение строк со значениями свойств объекта класса-сущности
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public virtual string[] GetStringRepresentation()
|
||||||
|
{
|
||||||
|
return new[] { nameof(EntityWarship), Speed.ToString(),
|
||||||
|
Weight.ToString(), BodyColor.Name };
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Создание объекта из массива строк
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="strs"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static EntityWarship? CreateEntityWarship(string[] strs)
|
||||||
|
{
|
||||||
|
if (strs.Length != 4 || strs[0] != nameof(EntityWarship))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new EntityWarship(Convert.ToInt32(strs[1]),
|
||||||
|
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System.Runtime.Serialization;
|
||||||
|
namespace ProjectBattleship.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) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System.Runtime.Serialization;
|
||||||
|
namespace ProjectBattleship.Exceptions;
|
||||||
|
/// <summary>
|
||||||
|
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||||
|
/// </summary>
|
||||||
|
[Serializable]
|
||||||
|
|
||||||
|
internal class ObjectNotFoundException : ApplicationException
|
||||||
|
{
|
||||||
|
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||||
|
|
||||||
|
public ObjectNotFoundException() : base() { }
|
||||||
|
|
||||||
|
public ObjectNotFoundException(string message) : base(message) { }
|
||||||
|
|
||||||
|
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||||
|
|
||||||
|
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.Runtime.Serialization;
|
||||||
|
namespace ProjectBattleship.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) { }
|
||||||
|
}
|
||||||
@@ -49,10 +49,17 @@ namespace ProjectBattleship
|
|||||||
textBoxCollectionName = new TextBox();
|
textBoxCollectionName = new TextBox();
|
||||||
labelCollection = new Label();
|
labelCollection = new Label();
|
||||||
pictureBox = new PictureBox();
|
pictureBox = new PictureBox();
|
||||||
|
menuStrip = new MenuStrip();
|
||||||
|
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||||
|
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||||
|
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||||
|
saveFileDialog = new SaveFileDialog();
|
||||||
|
openFileDialog = new OpenFileDialog();
|
||||||
groupBoxCollectionTools.SuspendLayout();
|
groupBoxCollectionTools.SuspendLayout();
|
||||||
panelCompanyTools.SuspendLayout();
|
panelCompanyTools.SuspendLayout();
|
||||||
panelCollection.SuspendLayout();
|
panelCollection.SuspendLayout();
|
||||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||||
|
menuStrip.SuspendLayout();
|
||||||
SuspendLayout();
|
SuspendLayout();
|
||||||
//
|
//
|
||||||
// groupBoxCollectionTools
|
// groupBoxCollectionTools
|
||||||
@@ -62,9 +69,9 @@ namespace ProjectBattleship
|
|||||||
groupBoxCollectionTools.Controls.Add(buttonCreateCompany);
|
groupBoxCollectionTools.Controls.Add(buttonCreateCompany);
|
||||||
groupBoxCollectionTools.Controls.Add(comboBoxSelectorCompany);
|
groupBoxCollectionTools.Controls.Add(comboBoxSelectorCompany);
|
||||||
groupBoxCollectionTools.Controls.Add(panelCollection);
|
groupBoxCollectionTools.Controls.Add(panelCollection);
|
||||||
groupBoxCollectionTools.Location = new Point(694, 0);
|
groupBoxCollectionTools.Location = new Point(699, 27);
|
||||||
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
||||||
groupBoxCollectionTools.Size = new Size(279, 594);
|
groupBoxCollectionTools.Size = new Size(279, 618);
|
||||||
groupBoxCollectionTools.TabIndex = 1;
|
groupBoxCollectionTools.TabIndex = 1;
|
||||||
groupBoxCollectionTools.TabStop = false;
|
groupBoxCollectionTools.TabStop = false;
|
||||||
groupBoxCollectionTools.Text = "Инструменты";
|
groupBoxCollectionTools.Text = "Инструменты";
|
||||||
@@ -78,9 +85,9 @@ namespace ProjectBattleship
|
|||||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||||
panelCompanyTools.Controls.Add(buttonRemoveWarship);
|
panelCompanyTools.Controls.Add(buttonRemoveWarship);
|
||||||
panelCompanyTools.Enabled = false;
|
panelCompanyTools.Enabled = false;
|
||||||
panelCompanyTools.Location = new Point(6, 348);
|
panelCompanyTools.Location = new Point(6, 354);
|
||||||
panelCompanyTools.Name = "panelCompanyTools";
|
panelCompanyTools.Name = "panelCompanyTools";
|
||||||
panelCompanyTools.Size = new Size(267, 240);
|
panelCompanyTools.Size = new Size(267, 234);
|
||||||
panelCompanyTools.TabIndex = 11;
|
panelCompanyTools.TabIndex = 11;
|
||||||
//
|
//
|
||||||
// buttonRefresh
|
// buttonRefresh
|
||||||
@@ -144,7 +151,7 @@ namespace ProjectBattleship
|
|||||||
//
|
//
|
||||||
// buttonCreateCompany
|
// buttonCreateCompany
|
||||||
//
|
//
|
||||||
buttonCreateCompany.Location = new Point(14, 314);
|
buttonCreateCompany.Location = new Point(14, 320);
|
||||||
buttonCreateCompany.Name = "buttonCreateCompany";
|
buttonCreateCompany.Name = "buttonCreateCompany";
|
||||||
buttonCreateCompany.Size = new Size(251, 34);
|
buttonCreateCompany.Size = new Size(251, 34);
|
||||||
buttonCreateCompany.TabIndex = 10;
|
buttonCreateCompany.TabIndex = 10;
|
||||||
@@ -157,7 +164,7 @@ namespace ProjectBattleship
|
|||||||
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||||
comboBoxSelectorCompany.FormattingEnabled = true;
|
comboBoxSelectorCompany.FormattingEnabled = true;
|
||||||
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
||||||
comboBoxSelectorCompany.Location = new Point(14, 275);
|
comboBoxSelectorCompany.Location = new Point(14, 281);
|
||||||
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
||||||
comboBoxSelectorCompany.Size = new Size(251, 33);
|
comboBoxSelectorCompany.Size = new Size(251, 33);
|
||||||
comboBoxSelectorCompany.TabIndex = 0;
|
comboBoxSelectorCompany.TabIndex = 0;
|
||||||
@@ -172,7 +179,7 @@ namespace ProjectBattleship
|
|||||||
panelCollection.Controls.Add(radioButtonMassive);
|
panelCollection.Controls.Add(radioButtonMassive);
|
||||||
panelCollection.Controls.Add(textBoxCollectionName);
|
panelCollection.Controls.Add(textBoxCollectionName);
|
||||||
panelCollection.Controls.Add(labelCollection);
|
panelCollection.Controls.Add(labelCollection);
|
||||||
panelCollection.Location = new Point(6, 25);
|
panelCollection.Location = new Point(6, 30);
|
||||||
panelCollection.Name = "panelCollection";
|
panelCollection.Name = "panelCollection";
|
||||||
panelCollection.Size = new Size(267, 246);
|
panelCollection.Size = new Size(267, 246);
|
||||||
panelCollection.TabIndex = 9;
|
panelCollection.TabIndex = 9;
|
||||||
@@ -247,19 +254,62 @@ namespace ProjectBattleship
|
|||||||
// pictureBox
|
// pictureBox
|
||||||
//
|
//
|
||||||
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
||||||
pictureBox.Location = new Point(0, 0);
|
pictureBox.Location = new Point(0, 51);
|
||||||
pictureBox.Name = "pictureBox";
|
pictureBox.Name = "pictureBox";
|
||||||
pictureBox.Size = new Size(688, 594);
|
pictureBox.Size = new Size(688, 567);
|
||||||
pictureBox.TabIndex = 2;
|
pictureBox.TabIndex = 2;
|
||||||
pictureBox.TabStop = false;
|
pictureBox.TabStop = false;
|
||||||
//
|
//
|
||||||
|
// menuStrip
|
||||||
|
//
|
||||||
|
menuStrip.ImageScalingSize = new Size(24, 24);
|
||||||
|
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||||
|
menuStrip.Location = new Point(0, 0);
|
||||||
|
menuStrip.Name = "menuStrip";
|
||||||
|
menuStrip.Size = new Size(978, 33);
|
||||||
|
menuStrip.TabIndex = 3;
|
||||||
|
menuStrip.Text = "menuStrip";
|
||||||
|
//
|
||||||
|
// файлToolStripMenuItem
|
||||||
|
//
|
||||||
|
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||||
|
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||||
|
файлToolStripMenuItem.Size = new Size(69, 29);
|
||||||
|
файлToolStripMenuItem.Text = "Файл";
|
||||||
|
//
|
||||||
|
// saveToolStripMenuItem
|
||||||
|
//
|
||||||
|
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||||
|
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||||
|
saveToolStripMenuItem.Size = new Size(278, 34);
|
||||||
|
saveToolStripMenuItem.Text = "Сохранение ";
|
||||||
|
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||||
|
//
|
||||||
|
// loadToolStripMenuItem
|
||||||
|
//
|
||||||
|
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||||
|
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||||
|
loadToolStripMenuItem.Size = new Size(278, 34);
|
||||||
|
loadToolStripMenuItem.Text = "Загрузка";
|
||||||
|
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
|
||||||
|
//
|
||||||
|
// saveFileDialog
|
||||||
|
//
|
||||||
|
saveFileDialog.Filter = "txt file | *.txt";
|
||||||
|
//
|
||||||
|
// openFileDialog
|
||||||
|
//
|
||||||
|
openFileDialog.Filter = "txt file | *.txt";
|
||||||
|
//
|
||||||
// FormWarshipCollection
|
// FormWarshipCollection
|
||||||
//
|
//
|
||||||
AutoScaleDimensions = new SizeF(10F, 25F);
|
AutoScaleDimensions = new SizeF(10F, 25F);
|
||||||
AutoScaleMode = AutoScaleMode.Font;
|
AutoScaleMode = AutoScaleMode.Font;
|
||||||
ClientSize = new Size(978, 594);
|
ClientSize = new Size(978, 618);
|
||||||
Controls.Add(groupBoxCollectionTools);
|
Controls.Add(groupBoxCollectionTools);
|
||||||
Controls.Add(pictureBox);
|
Controls.Add(pictureBox);
|
||||||
|
Controls.Add(menuStrip);
|
||||||
|
MainMenuStrip = menuStrip;
|
||||||
Name = "FormWarshipCollection";
|
Name = "FormWarshipCollection";
|
||||||
Text = "Коллекция военных кораблей";
|
Text = "Коллекция военных кораблей";
|
||||||
groupBoxCollectionTools.ResumeLayout(false);
|
groupBoxCollectionTools.ResumeLayout(false);
|
||||||
@@ -268,7 +318,10 @@ namespace ProjectBattleship
|
|||||||
panelCollection.ResumeLayout(false);
|
panelCollection.ResumeLayout(false);
|
||||||
panelCollection.PerformLayout();
|
panelCollection.PerformLayout();
|
||||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||||
|
menuStrip.ResumeLayout(false);
|
||||||
|
menuStrip.PerformLayout();
|
||||||
ResumeLayout(false);
|
ResumeLayout(false);
|
||||||
|
PerformLayout();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -291,5 +344,11 @@ namespace ProjectBattleship
|
|||||||
private Button buttonCollectionDel;
|
private Button buttonCollectionDel;
|
||||||
private ListBox listBoxCollection;
|
private ListBox listBoxCollection;
|
||||||
private Panel panelCompanyTools;
|
private Panel panelCompanyTools;
|
||||||
|
private MenuStrip menuStrip;
|
||||||
|
private ToolStripMenuItem файлToolStripMenuItem;
|
||||||
|
private ToolStripMenuItem saveToolStripMenuItem;
|
||||||
|
private ToolStripMenuItem loadToolStripMenuItem;
|
||||||
|
private SaveFileDialog saveFileDialog;
|
||||||
|
private OpenFileDialog openFileDialog;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
using ProjectBattleship.CollectionGenericObjects;
|
using Battleship.CollectionGenericObjects;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace ProjectBattleship;
|
namespace ProjectBattleship;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -16,12 +19,17 @@ public partial class FormWarshipCollection : Form
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private AbstractCompany? _company = null;
|
private AbstractCompany? _company = null;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// Логер
|
||||||
|
/// </summary>
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormWarshipCollection()
|
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выбор компании
|
/// Выбор компании
|
||||||
@@ -47,21 +55,25 @@ public partial class FormWarshipCollection : Form
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление военного корабля в коллекцию
|
/// Добавление военного корабля в коллекцию
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="car"></param>
|
/// <param name="Warship"></param>
|
||||||
private void SetWarship(DrawingWarship? warship)
|
private void SetWarship(DrawingWarship warship)
|
||||||
{
|
{
|
||||||
if (_company == null || warship == null)
|
if (_company == null || warship == null)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (_company + warship != -1)
|
try
|
||||||
{
|
{
|
||||||
|
var res = _company + warship;
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
|
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||||
|
MessageBoxIcon.Error);
|
||||||
|
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -143,14 +155,18 @@ public partial class FormWarshipCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||||
if (_company - pos != null)
|
try
|
||||||
{
|
{
|
||||||
|
var res = _company - pos;
|
||||||
MessageBox.Show("Объект удален");
|
MessageBox.Show("Объект удален");
|
||||||
|
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||||
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -208,10 +224,10 @@ public partial class FormWarshipCollection : Form
|
|||||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
CollectionType collectionType = CollectionType.None;
|
CollectionType collectionType = CollectionType.None;
|
||||||
if (radioButtonMassive.Checked)
|
if (radioButtonMassive.Checked)
|
||||||
{
|
{
|
||||||
@@ -221,10 +237,20 @@ public partial class FormWarshipCollection : Form
|
|||||||
{
|
{
|
||||||
collectionType = CollectionType.List;
|
collectionType = CollectionType.List;
|
||||||
}
|
}
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text,
|
|
||||||
collectionType);
|
try
|
||||||
|
{
|
||||||
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
|
_logger.LogInformation("Добавление коллекции");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление коллекции
|
/// Удаление коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -237,16 +263,18 @@ public partial class FormWarshipCollection : Form
|
|||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show("Вы хотите удалить эту коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
|
||||||
|
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||||
|
DialogResult.Yes)
|
||||||
{
|
{
|
||||||
string? name = listBoxCollection.SelectedItem.ToString();
|
return;
|
||||||
if (!string.IsNullOrEmpty(name))
|
|
||||||
{
|
|
||||||
_storageCollection.DelCollection(name);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||||
|
_logger.LogInformation("Коллекция удалена");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обновление списка в listBoxCollection
|
/// Обновление списка в listBoxCollection
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -292,4 +320,50 @@ public partial class FormWarshipCollection : Form
|
|||||||
panelCompanyTools.Enabled = true;
|
panelCompanyTools.Enabled = true;
|
||||||
RerfreshListBoxItems();
|
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("Не сохранилось", "Результат", 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
|
||||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -117,4 +117,13 @@
|
|||||||
<resheader name="writer">
|
<resheader name="writer">
|
||||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||||
</resheader>
|
</resheader>
|
||||||
|
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||||
|
<value>17, 17</value>
|
||||||
|
</metadata>
|
||||||
|
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||||
|
<value>163, 17</value>
|
||||||
|
</metadata>
|
||||||
|
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||||
|
<value>351, 17</value>
|
||||||
|
</metadata>
|
||||||
</root>
|
</root>
|
||||||
@@ -1,3 +1,11 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NLog.Extensions.Logging;
|
||||||
|
using System.Drawing;
|
||||||
|
using System;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Serilog;
|
||||||
|
|
||||||
namespace ProjectBattleship
|
namespace ProjectBattleship
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@@ -8,8 +16,37 @@ namespace ProjectBattleship
|
|||||||
[STAThread]
|
[STAThread]
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
|
// To customize application configuration such as set high DPI settings or default font,
|
||||||
|
// see https://aka.ms/applicationconfiguration.
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormWarshipCollection());
|
ServiceCollection services = new();
|
||||||
|
ConfigureServices(services);
|
||||||
|
using ServiceProvider serviceProvider =
|
||||||
|
services.BuildServiceProvider();
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormWarshipCollection>());
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormWarshipCollection>().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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,16 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||||
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
|
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
@@ -23,4 +33,10 @@
|
|||||||
</EmbeddedResource>
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="serilogConfig.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
20
ProjectBattleship/ProjectBattleship/serilogConfig.json
Normal file
20
ProjectBattleship/ProjectBattleship/serilogConfig.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"Serilog": {
|
||||||
|
"Using": [ "Serilog.Sinks.File" ],
|
||||||
|
"MinimumLevel": "Information",
|
||||||
|
"WriteTo": [
|
||||||
|
{
|
||||||
|
"Name": "File",
|
||||||
|
"Args": {
|
||||||
|
"path": "Logs/log_.log",
|
||||||
|
"rollingInterval": "Day",
|
||||||
|
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "Battleship"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user