Лабораторная работа номер 7

This commit is contained in:
SAliulov 2024-06-16 23:00:17 +03:00
parent 53148d85e4
commit 3a7858e07a
12 changed files with 302 additions and 138 deletions

View File

@ -1,4 +1,5 @@
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
namespace ProjectAirBomber.CollectionGenericObjects; namespace ProjectAirBomber.CollectionGenericObjects;
@ -32,18 +33,18 @@ public abstract class AbstractCompany
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningBomber>? _collection = null; protected ICollectionGenericObjects<DrawningBomber>? _collection = null;
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth">Ширина окна</param> /// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param> /// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param> /// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection)
{ {
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
@ -83,31 +84,37 @@ public abstract class AbstractCompany
return _collection?.Get(rnd.Next(GetMaxCount)); return _collection?.Get(rnd.Next(GetMaxCount));
} }
/// <summary> /// <summary>
/// Вывод всей коллекции /// Вывод всей коллекции
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public Bitmap? Show() public Bitmap? Show()
{ {
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackgound(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningBomber? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
} DrawningBomber? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
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 DrawBackgound(Graphics g);
/// <summary> /// <summary>
/// Расстановка объектов /// Расстановка объектов

View File

@ -1,5 +1,6 @@
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Entities; using ProjectAirBomber.Entities;
using ProjectAirBomber.Exceptions;
using System; using System;
namespace ProjectAirBomber.CollectionGenericObjects; namespace ProjectAirBomber.CollectionGenericObjects;
@ -9,56 +10,63 @@ namespace ProjectAirBomber.CollectionGenericObjects;
/// </summary> /// </summary>
public class BomberHungarService : AbstractCompany public class BomberHungarService : AbstractCompany
{ {
/// <summary>
/// Конструктор /// <summary>
/// </summary> /// Конструктор
/// <param name="picWidth"></param> /// </summary>
/// <param name="picHeight"></param> /// <param name="picWidth"></param>
/// <param name="collection"></param> /// <param name="picHeight"></param>
public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) : base(picWidth, picHeight, collection) /// <param name="collection"></param>
public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) : base(picWidth, picHeight, collection)
{ {
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Отрисовка хранилища
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g">Графика</param>
/// int pamat_i = 0;
int pamat_j = 0;
protected override void DrawBackgound(Graphics g) protected override void DrawBackgound(Graphics g)
{ {
Pen pen = new(Color.Black, 2); Pen pen = new(Color.Black, 4);
for (int i = 0; i < _pictureWidth / _placeSizeWidth + 1; i++) for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{ {
pamat_i = i;
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{ {
pamat_j = j;
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * j)); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
} }
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
} }
} }
/// <summary> /// <summary>
/// Установка объекта в Ангар /// Установка объекта в Ангар
/// </summary> /// </summary>
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int n = 0; int currentIndex = 0;
for (int i = _pictureWidth / _placeSizeWidth; i > 0; i--) for (int j = pamat_j; j >= 0; j--)
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) for (int i = pamat_i; i >= 0; i--)
{ {
DrawningBomber? drawningBomber = _collection?.Get(n); try
n++;
if (drawningBomber != null)
{ {
drawningBomber.SetPictureSize(_pictureWidth, _pictureHeight); if (_collection?.Get(currentIndex) != null)
drawningBomber.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); {
_collection.Get(currentIndex)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(currentIndex)?.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
} }
catch (ObjectNotFoundException)
{
}
currentIndex++;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using ProjectAirBomber.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -50,25 +51,26 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
public T? Get(int position) public T? Get(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count + 1 > _maxCount) return -1; if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count + 1 > _maxCount) return -1; if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
if (position < 0 || position > Count) return -1; if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return 1; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position > Count) return null; if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? temp = _collection[position]; T? temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;
@ -81,4 +83,4 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
} }

View File

@ -1,6 +1,6 @@
using System.Runtime.Remoting; using System.Runtime.Remoting;
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
namespace ProjectAirBomber.CollectionGenericObjects; namespace ProjectAirBomber.CollectionGenericObjects;
/// <summary> /// <summary>
@ -52,12 +52,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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 _collection[position]; return _collection[position];
}
return null;
} }
public int Insert(T obj) public int Insert(T obj)
@ -72,20 +69,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то // проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
if (_collection[position] != null) if (_collection[position] != null)
{ {
bool pushed = false; bool pushed = false;
@ -114,7 +108,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (!pushed) if (!pushed)
{ {
return position; throw new CollectionOverflowException(Count);
} }
} }
@ -123,21 +117,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{
return null;
}
if (_collection[position] == null) return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position]; T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < _collection.Length; ++i) for (int i = 0; i < _collection.Length; ++i)

View File

@ -1,4 +1,6 @@
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System.Data;
using System.Text; using System.Text;
namespace ProjectAirBomber.CollectionGenericObjects; namespace ProjectAirBomber.CollectionGenericObjects;
@ -88,12 +90,11 @@ public class StorageCollection<T>
/// Сохранение информации по самолётам в хранилище в файл /// Сохранение информации по самолётам в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -133,21 +134,18 @@ public class StorageCollection<T>
} }
writer.Write(sb); writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по самолётам в хранилище из файла /// Загрузка информации по самолётам в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException($"{filename} не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@ -155,11 +153,11 @@ public class StorageCollection<T>
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new FileFormatException("Файл не подходит");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
@ -174,7 +172,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -182,15 +180,21 @@ public class StorageCollection<T>
{ {
if (elem?.CreateDrawningBomber() is T bomber) if (elem?.CreateDrawningBomber() is T bomber)
{ {
if (collection.Insert(bomber) == -1) try
{ {
return false; if (collection.Insert(bomber) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }
@ -208,4 +212,4 @@ public class StorageCollection<T>
_ => null, _ => null,
}; };
} }
} }

View File

@ -0,0 +1,18 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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,17 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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,17 @@

using System.Runtime.Serialization;
namespace ProjectAirBomber.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

@ -1,5 +1,7 @@
using ProjectAirBomber.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectAirBomber.CollectionGenericObjects;
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -29,15 +31,22 @@ public partial class FormBomberCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormBomberCollection() public FormBomberCollection(ILogger<FormBomberCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
/// </summary> /// </summary>
@ -71,14 +80,17 @@ public partial class FormBomberCollection : Form
return; return;
} }
if (_company + bomber != -1) try
{ {
int addingObject = (_company + bomber);
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bomber.GetDataForSave()}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Не удалось добавить объект: {ex.Message}");
} }
} }
@ -92,6 +104,7 @@ public partial class FormBomberCollection : Form
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
_logger.LogError("Удаление объекта из несуществующей коллекции");
return; return;
} }
@ -101,14 +114,22 @@ public partial class FormBomberCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) try
{ {
object decrementObject = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (ObjectNotFoundException)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Объект не найден");
_logger.LogError($"Удаление не найденного объекта в позиции {pos} ");
}
catch (PositionOutOfCollectionException)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogError($"Удаление объекта за пределами коллекции {pos} ");
} }
} }
@ -124,28 +145,33 @@ public partial class FormBomberCollection : Form
return; return;
} }
DrawningBomber? bomber = null; try
int counter = 100;
while (bomber == null)
{ {
bomber = _company.GetRandomObject(); DrawningBomber? bomber = null;
counter--; int counter = 100;
if (counter <= 0) while (bomber == null)
{ {
break; bomber = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
} }
if (bomber == null)
{
return;
}
FormAirBomber form = new()
{
SetBomber = bomber
};
form.ShowDialog();
} }
catch (ObjectNotFoundException)
if (bomber == null)
{ {
return; _logger.LogError("Ошибка при передаче объекта на FormAirFighter");
} }
FormAirBomber form = new()
{
SetBomber = bomber
};
form.ShowDialog();
} }
/// <summary> /// <summary>
@ -226,6 +252,7 @@ public partial class FormBomberCollection : Form
} }
} }
} }
/// <summary> /// <summary>
/// Создание компании /// Создание компании
/// </summary> /// </summary>
@ -264,17 +291,21 @@ public partial class FormBomberCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
/// <summary> /// <summary>
/// Обработка нажатия "Загрузка" /// Обработка нажатия "Загрузка"
/// </summary> /// </summary>
@ -284,16 +315,17 @@ public partial class FormBomberCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storageCollection.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,17 +1,45 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Serilog;
using Microsoft.Extensions.Logging;
namespace ProjectAirBomber namespace ProjectAirBomber
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormBomberCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBomberCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBomberCollection>().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,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +37,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </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": "AirBomber"
}
}
}