лаба 7

# Conflicts:
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/CollectionGenericObjects/StorageCollection.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.Designer.cs
#	ProjectGasolineTanker/ProjectGasolineTanker/FormTankerCollection.cs
This commit is contained in:
Roman-Klemendeev 2024-05-26 22:15:39 +04:00
parent 6725a8cb3a
commit c9ad7127f9
13 changed files with 420 additions and 102 deletions

View File

@ -15,7 +15,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Размер места (высота) /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 80; protected readonly int _placeSizeHeight = 97;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -35,7 +35,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -95,10 +95,15 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningTanker? obj = _collection?.Get(i); DrawningTanker? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }

View File

@ -17,8 +17,6 @@ public class CarPark : AbstractCompany
protected override void DrawBackground(Graphics g) protected override void DrawBackground(Graphics g)
{ {
Pen pen = new Pen(Color.Brown, 3); Pen pen = new Pen(Color.Brown, 3);
int offsetX = 10, offsetY = -12; int offsetX = 10, offsetY = -12;
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
@ -48,9 +46,13 @@ public class CarPark : AbstractCompany
} }
int row = numRows - 1, col = numCols; int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--) for (int i = 0; i < _collection?.Count; i++, col--)
{
try
{ {
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1) if (col == 1)
{ {
col = numCols + 1; col = numCols + 1;

View File

@ -1,4 +1,6 @@
 
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects; namespace ProjectGasolineTanker.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -35,30 +37,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{
return _collection[position]; return _collection[position];
} }
else
{
return null;
}
}
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; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count || Count == _maxCount) if (position < 0 || position >= Count)
{ throw new PositionOutOfCollectionException(position);
return -1;
} if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -66,7 +62,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position) public T Remove(int position)
{ {
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

@ -1,4 +1,6 @@
namespace ProjectGasolineTanker.CollectionGenericObjects; using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -44,14 +46,11 @@ where T : class
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= _collection.Length || position < 0) 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)
{ {
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
@ -62,14 +61,14 @@ where T : class
return i; return i;
} }
} }
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)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) if (_collection[position] == null)
{ {
@ -94,15 +93,16 @@ where T : class
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;

View File

@ -1,5 +1,5 @@
<<<<<<< HEAD using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Drawnings; using ProjectGasolineTanker.Exceptions;
using System.Text; using System.Text;
namespace ProjectGasolineTanker.CollectionGenericObjects; namespace ProjectGasolineTanker.CollectionGenericObjects;
@ -108,11 +108,11 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -148,7 +148,6 @@ public class StorageCollection<T>
sb.Clear(); sb.Clear();
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -156,19 +155,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader sr = new StreamReader(filename))
{ {
string? str; string? str;
str = sr.ReadLine(); str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString()) if (str != _collectionKey.ToString())
return false; throw new Exception("В файле неверные данные");
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
@ -181,7 +182,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 Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -190,16 +191,21 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTanker() is T tanker) if (elem?.CreateDrawningTanker() is T tanker)
{
try
{ {
if (collection.Insert(tanker) == -1) if (collection.Insert(tanker) == -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,17 @@
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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,16 @@
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.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 ProjectGasolineTanker.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

@ -235,19 +235,45 @@ namespace ProjectGasolineTanker
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// panelCompanyTools // menuStrip
// //
panelCompanyTools.Controls.Add(buttonAddTanker); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
panelCompanyTools.Controls.Add(maskedTextBoxPosition); menuStrip.Location = new Point(0, 0);
panelCompanyTools.Controls.Add(buttonRefresh); menuStrip.Name = "menuStrip";
panelCompanyTools.Controls.Add(buttonRemoveTanker); menuStrip.Size = new Size(1086, 24);
panelCompanyTools.Controls.Add(buttonGoToCheck); menuStrip.TabIndex = 2;
panelCompanyTools.Dock = DockStyle.Bottom; menuStrip.Text = "menuStrip1";
panelCompanyTools.Enabled = false; //
panelCompanyTools.Location = new Point(3, 360); // файлToolStripMenuItem
panelCompanyTools.Name = "panelCompanyTools"; //
panelCompanyTools.Size = new Size(173, 253); файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
panelCompanyTools.TabIndex = 9; файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
// //
// FormTankerCollection // FormTankerCollection
// //

View File

@ -1,5 +1,7 @@
using ProjectGasolineTanker.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.Drawnings; using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectGasolineTanker; namespace ProjectGasolineTanker;
@ -19,13 +21,16 @@ public partial class FormTankerCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTankerCollection() public FormTankerCollection(ILogger<FormTankerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -54,6 +59,8 @@ public partial class FormTankerCollection : Form
/// </summary> /// </summary>
/// <param name="tank"></param> /// <param name="tank"></param>
private void SetTanker(DrawningTanker? tank) private void SetTanker(DrawningTanker? tank)
{
try
{ {
if (_company == null || tank == null) if (_company == null || tank == null)
{ {
@ -64,23 +71,29 @@ public partial class FormTankerCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
} }
else }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
/// Удаление объекта /// Удаление объекта
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveTanker_Click(object sender, EventArgs e) private void ButtonRemoveTanker_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; throw new Exception("Входные данные отсутствуют");
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@ -88,15 +101,18 @@ public partial class FormTankerCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -112,11 +128,13 @@ public partial class FormTankerCollection : Form
return; return;
} }
DrawningTanker? car = null; DrawningTanker? tanker = null;
int counter = 100; int counter = 100;
while (car == null) try
{ {
car = _company.GetRandomObject(); while (tanker == null)
{
tanker = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@ -124,15 +142,21 @@ public partial class FormTankerCollection : Form
} }
} }
if (car == null) if (tanker == null)
{ {
return; return;
} }
FormGasolineTanker form = new FormGasolineTanker(); FormGasolineTanker form = new FormGasolineTanker();
form.SetTanker = car; form.SetTanker = tanker;
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
@ -148,4 +172,152 @@ public partial class FormTankerCollection : Form
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTanker>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new CarPark(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", 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 ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
internal static class Program internal static class Program
@ -11,7 +16,32 @@ namespace ProjectGasolineTanker
// 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 FormTankerCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankerCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
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<FormTankerCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
} }
} }
} }

View File

@ -8,4 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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