WIP Лабораторная работа №7

This commit is contained in:
alhimek17 2024-05-19 17:48:32 +04:00
parent dbce9c8b1d
commit 66e3aab441
10 changed files with 270 additions and 127 deletions

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectAirPlane.Drawnings; using ProjectAirPlane.Drawnings;
using ProjectAirPlane.Exceptions;
namespace ProjectAirPlane.CollectionGenericObjects; namespace ProjectAirPlane.CollectionGenericObjects;
@ -48,7 +49,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
@ -56,7 +57,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора // TODO вставка в конец набора
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
@ -66,8 +67,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции // TODO проверка позиции
// TODO вставка по позиции // TODO вставка по позиции
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@ -76,7 +77,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из списка // TODO удаление объекта из списка
if (position >= Count || position < 0) return null; if (position >= 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;

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectAirPlane.Exceptions;
namespace ProjectAirPlane.CollectionGenericObjects; namespace ProjectAirPlane.CollectionGenericObjects;
@ -51,7 +52,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= _collection.Length || position < 0) return null; if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
@ -68,7 +70,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
++index; ++index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
@ -78,8 +80,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
// TODO вставка // TODO вставка
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
return -1;
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -105,17 +107,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
--index; --index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
}
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;

View File

@ -1,5 +1,6 @@
using System.Text; using System.Text;
using ProjectAirPlane.Drawnings; using ProjectAirPlane.Drawnings;
using ProjectAirPlane.Exceptions;
namespace ProjectAirPlane.CollectionGenericObjects; namespace ProjectAirPlane.CollectionGenericObjects;
@ -14,12 +15,10 @@ public class StorageCollection<T>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly 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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -27,7 +26,6 @@ public class StorageCollection<T>
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// </summary> /// </summary>
@ -35,37 +33,22 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом if (_storages.ContainsKey(name)) return;
// TODO Прописать логику для добавления if (collectionType == CollectionType.None) return;
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
{
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
{ _storages[name] = new MassiveGenericObjects<T>();
_storages.Add(name, new MassiveGenericObjects<T>()); else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
} }
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
// TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(name))
if (_storages.ContainsKey(name)) { _storages.Remove(name); } _storages.Remove(name);
} }
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
/// </summary> /// </summary>
@ -75,7 +58,6 @@ public class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
return _storages[name]; return _storages[name];
return null; return null;
@ -97,12 +79,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 Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -113,19 +94,17 @@ public class StorageCollection<T>
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); writer.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); writer.Write(value.Key);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); writer.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -133,43 +112,37 @@ public class StorageCollection<T>
{ {
continue; continue;
} }
sb.Append(data); writer.Write(data);
sb.Append(_separatorItems); writer.Write(_separatorItems);
} }
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 Exception("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
@ -179,24 +152,29 @@ 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 Exception("Не удалось создать коллекцию");
} }
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);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningPlane() is T plane) if (elem?.CreateDrawningPlane() is T plane)
{
try
{ {
if (collection.Insert(plane) == -1) if (collection.Insert(plane) == -1)
{ {
return false; throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirPlane.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
public 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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirPlane.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirPlane.Exceptions;
[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

@ -7,8 +7,10 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using ProjectAirPlane.CollectionGenericObjects; using ProjectAirPlane.CollectionGenericObjects;
using ProjectAirPlane.Drawnings; using ProjectAirPlane.Drawnings;
using ProjectAirPlane.Exceptions;
namespace ProjectAirPlane; namespace ProjectAirPlane;
@ -27,13 +29,20 @@ public partial class FormPlaneCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormPlaneCollection() public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -59,6 +68,8 @@ public partial class FormPlaneCollection : Form
/// </summary> /// </summary>
/// <param name="ship"></param> /// <param name="ship"></param>
private void SetPlane(DrawningPlane plane) private void SetPlane(DrawningPlane plane)
{
try
{ {
if (_company == null || plane == null) if (_company == null || plane == null)
{ {
@ -69,10 +80,14 @@ public partial class FormPlaneCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
} }
else }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка : {Messsage}", ex.Message);
} }
} }
@ -94,15 +109,20 @@ public partial class FormPlaneCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int position = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{
if (_company - position != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + position);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Ошибка: {Message}", ex.Message);
} }
} }
@ -115,6 +135,9 @@ public partial class FormPlaneCollection : Form
DrawningPlane? plane = null; DrawningPlane? plane = null;
int counter = 100; int counter = 100;
try
{
while (plane == null) while (plane == null)
{ {
plane = _company.GetRandomObject(); plane = _company.GetRandomObject();
@ -124,18 +147,22 @@ public partial class FormPlaneCollection : Form
break; break;
} }
} }
if (plane == null)
{
return;
}
FormAirPlane form = new() FormAirPlane form = new()
{ {
SetPlane = plane SetPlane = plane
}; };
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (plane == null)
{
return;
}
}
private void ButtonRefresh_Click(object sender, EventArgs e) private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
@ -157,10 +184,13 @@ public partial class FormPlaneCollection : Form
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -170,9 +200,14 @@ public partial class FormPlaneCollection : Form
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -198,17 +233,29 @@ public partial class FormPlaneCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e) private void ButtonCollectionDel_Click(object sender, EventArgs e)
{ {
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
/// Создание компании /// Создание компании
@ -249,15 +296,16 @@ public partial class FormPlaneCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storageCollection.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -271,16 +319,17 @@ public partial class FormPlaneCollection : 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);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirPlane namespace ProjectAirPlane
{ {
internal static class Program internal static class Program
@ -11,8 +16,32 @@ namespace ProjectAirPlane
// 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 FormPlaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormPlaneCollection>());
} }
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
} }
} }

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}