ISEbd-12_Mukhamadieva_S.S._Simple_LabWork07 #7

Closed
safia wants to merge 6 commits from LabWork7 into LabWork6
13 changed files with 382 additions and 177 deletions

View File

@ -1,4 +1,5 @@
using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
@ -30,8 +31,7 @@ public abstract class AbstractCompany
/// Вычисление максимального количества элементов, который можно
/// разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight /
(_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -85,20 +85,30 @@ public abstract class AbstractCompany
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawingWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawingWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
protected abstract void DrawBackground(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>

View File

@ -1,4 +1,5 @@
using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
@ -12,12 +13,12 @@ public class Docks : AbstractCompany
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public Docks(int picWidth, int picHeight,
ICollectionGenericObjects<DrawingWarship> collection) :
public Docks(int picWidth, int picHeight,
ICollectionGenericObjects<DrawingWarship> collection) :
base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
protected override void DrawBackground(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
@ -26,48 +27,47 @@ public class Docks : AbstractCompany
{
for (int j = 0; j < height; ++j)
{
g.FillRectangle(brush, i * _placeSizeWidth,
g.FillRectangle(brush, i * _placeSizeWidth,
j * _placeSizeHeight, 200, 5);
g.FillRectangle(brush, i * _placeSizeWidth,
g.FillRectangle(brush, i * _placeSizeWidth,
j * _placeSizeHeight, 5, 80);
}
}
for (int j = 0; j < height - 4; ++j)
{
g.FillRectangle(brush, j * _placeSizeWidth,
g.FillRectangle(brush, j * _placeSizeWidth,
height * _placeSizeHeight, 200, 5);
}
}
protected override void SetObjectsPosition()
{
if (_collection == null) return;
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
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);
if (_warship != null)
try
{
if (_warship.SetPictureSize(_pictureWidth, _pictureHeight))
{
_warship.SetPosition(_placeSizeWidth * curWidth + 20,
curHeight * _placeSizeHeight + 15);
}
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
curWidth--;
if (curWidth < 0)
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0)
curWidth--;
else
{
curHeight++;
curWidth = width - 1;
curHeight++;
}
if (curHeight >= height)
{
return;
}
}
}
}
}

View File

@ -1,4 +1,9 @@
namespace ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
@ -16,7 +21,21 @@ where T : class
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
public int MaxCount
{
set
{
if (value > 0)
{
_maxCount = value;
}
}
get
{
return Count;
}
}
public CollectionType GetCollectionType => CollectionType.List;
@ -27,41 +46,33 @@ where T : class
{
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count <= _maxCount)
{
_collection.Add(obj);
return Count;
}
return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count < _maxCount && position >= 0 && position < _maxCount)
{
_collection.Insert(position, obj);
return position;
}
return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
T temp = _collection[position];
if (position >= 0 && position < _maxCount)
{
_collection.RemoveAt(position);
return temp;
}
return null;
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()

View File

@ -1,18 +1,22 @@
namespace ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Exceptions;
using ProjectBattleship.CollectionGenericObjects;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
/// <summary>
/// Установка максимального кол-ва объектов
/// </summary>
public int MaxCount
{
get
@ -44,69 +48,86 @@ where T : class
{
_collection = Array.Empty<T?>();
}
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция (индекс)</param>
/// <returns></returns>
public T? Get(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
int index = 0;
while (index < _collection.Length)
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[index] == null)
if (_collection[i] == null)
{
_collection[index] = obj;
return index;
_collection[i] = obj;
return i;
}
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
_collection[position] = obj;
return position;
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);
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
// вставка
_collection[position] = obj;
return position;
}
public T Remove(int position)
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{ return null; }
T DrawningWarship = _collection[position];
_collection[position] = null;
return DrawningWarship;
}
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)

View File

@ -1,12 +1,14 @@
using ProjectBattleship.DrawingObject;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawingWarship
public class StorageCollection<T> where T : DrawingWarship
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -44,20 +46,23 @@ where T : DrawingWarship
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(string name, CollectionType collectionType)
{
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
return;
switch (collectionType)
{
if (collectionType == CollectionType.List)
{
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive)
{
break;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
}
break;
default:
break;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
@ -71,15 +76,12 @@ where T : DrawingWarship
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
{
return _storages[name];
}
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
return value;
return null;
}
}
@ -88,16 +90,19 @@ where T : DrawingWarship
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
@ -118,6 +123,7 @@ where T : DrawingWarship
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -126,47 +132,43 @@ where T : DrawingWarship
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
return true;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
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)
{
return false;
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -174,25 +176,29 @@ where T : DrawingWarship
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingWarship() is T warship)
if (elem?.CreateDrawingWarship() is T Warship)
{
if (collection.Insert(warship) == -1)
return false;
try
{
if (collection.Insert(Warship) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) => collectionType switch
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}

View File

@ -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) { }
}

View File

@ -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) { }
}

View File

@ -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) { }
}

View File

@ -283,7 +283,7 @@ namespace ProjectBattleship
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(278, 34);
saveToolStripMenuItem.Text = "Сохранение ";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//

View File

@ -1,4 +1,6 @@
using ProjectBattleship.CollectionGenericObjects;
using Battleship.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
using System.Windows.Forms;
@ -17,12 +19,17 @@ public partial class FormWarshipCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipCollection()
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
@ -48,21 +55,25 @@ public partial class FormWarshipCollection : Form
/// <summary>
/// Добавление военного корабля в коллекцию
/// </summary>
/// <param name="car"></param>
private void SetWarship(DrawingWarship? warship)
/// <param name="Warship"></param>
private void SetWarship(DrawingWarship warship)
{
if (_company == null || warship == null)
{
return;
}
if (_company + warship != -1)
try
{
var res = _company + warship;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
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>
@ -144,14 +155,18 @@ public partial class FormWarshipCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
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>
@ -207,12 +222,12 @@ public partial class FormWarshipCollection : Form
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -222,9 +237,19 @@ public partial class FormWarshipCollection : Form
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
RerfreshListBoxItems();
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
@ -238,16 +263,18 @@ public partial class FormWarshipCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Вы хотите удалить эту коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
string? name = listBoxCollection.SelectedItem.ToString();
if (!string.IsNullOrEmpty(name))
{
_storageCollection.DelCollection(name);
}
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
@ -295,25 +322,27 @@ public partial class FormWarshipCollection : Form
}
/// <summary>
/// Обработка нажатия "Сохранить"
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
@ -323,14 +352,17 @@ public partial class FormWarshipCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -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
{
internal static class Program
@ -8,8 +16,37 @@ namespace ProjectBattleship
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new FormWarshipCollection());
// 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<FormWarshipCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà 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);
});
}
}
}

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +33,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Battleship"
}
}
}