Лабоарторная работа №7
This commit is contained in:
parent
b9afd42e2e
commit
914633077e
@ -57,6 +57,7 @@ public abstract class AbstractCompany
|
||||
/// <param name="truck">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingTruck truck)
|
||||
|
||||
{
|
||||
return company._collection.Insert(truck);
|
||||
}
|
||||
@ -94,8 +95,12 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawingTruck? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawingTruck? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
@ -1,4 +1,7 @@
|
||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||
using ProjectGasolineTanker.Exceptions;
|
||||
using System.CodeDom;
|
||||
|
||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@ -45,19 +48,20 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public T? Get(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// выброс ошибки, если выход за границы массива
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
return _collection[position];
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
|
||||
if (Count == _maxCount) return -1;
|
||||
// выброс ошибки если переполнение
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -65,29 +69,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// проверка, что не превышено максимальное количество элементов
|
||||
// проверка позиции
|
||||
// вставка по позиции
|
||||
// выброс ошибки, если переполнение
|
||||
// выброс ошибки если выход за границу
|
||||
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
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)
|
||||
{
|
||||
// проверка позиции
|
||||
// удаление объекта из списка
|
||||
if (position >= Count || position < 0) return null;
|
||||
//выброс ошибки, если выход за границы массива
|
||||
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
|
@ -1,4 +1,5 @@
|
||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||
using ProjectGasolineTanker.Exceptions;
|
||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@ -47,19 +48,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection = Array.Empty<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(position);
|
||||
return _collection[position];
|
||||
|
||||
}
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// вставка в свободное место набора
|
||||
for (int i = 0; i < Count; ++i)
|
||||
// выброс ошибки, если переполнение
|
||||
//выброс ошибки, если выход за границы массива
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
@ -67,7 +71,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
@ -76,11 +80,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до
|
||||
// вставка
|
||||
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
//выброс ошибки, если переполнение
|
||||
//выброс ошибки, если выход за границы массива
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
@ -106,20 +108,24 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
|
||||
}
|
||||
public T? Remove(int position)
|
||||
public T Remove(int position)
|
||||
{
|
||||
//// проверка позиции
|
||||
//// удаление объекта из массива, присвоив элементу массива значение null
|
||||
|
||||
if (position >= Count || position < 0) return null;
|
||||
// выброс ошибки, если выход за границы массива
|
||||
// выброс ошибки, если объект пустой
|
||||
if (position >= Count || position < 0) 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)
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectGasolineTanker.Drawings;
|
||||
using ProjectGasolineTanker.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||
@ -108,12 +109,12 @@ public class StorageCollection<T>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </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("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -151,30 +152,29 @@ public class StorageCollection<T>
|
||||
}
|
||||
|
||||
}
|
||||
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 Exception("Файл не существует");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле нет данных");
|
||||
|
||||
}
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
@ -189,7 +189,8 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
@ -197,15 +198,22 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (elem?.CreateDrawingTruck() is T truck)
|
||||
{
|
||||
if (collection.Insert(truck) == -1)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
if (collection.Insert(truck) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -44,11 +44,12 @@ public class TruckSharingService : AbstractCompany
|
||||
{
|
||||
for (int i = 0; i < (_collection.Count); i++)
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
try
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
if (positionWidth < width - 1)
|
||||
{
|
||||
|
@ -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) { }
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
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) { }
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,17 @@
|
||||
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) { }
|
||||
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
using ProjectGasolineTanker.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectGasolineTanker.CollectionGenericObjects;
|
||||
using ProjectGasolineTanker.Exceptions;
|
||||
using ProjectGasolineTanker.Drawings;
|
||||
using System.Windows.Forms;
|
||||
|
||||
@ -19,13 +21,20 @@ public partial class FormTruckCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormTruckCollection()
|
||||
public FormTruckCollection(ILogger<FormTruckCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -56,18 +65,24 @@ public partial class FormTruckCollection : Form
|
||||
/// <param name="truck"></param>
|
||||
private void SetTruck(DrawingTruck truck)
|
||||
{
|
||||
if (_company == null || truck == null)
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (_company == null || truck == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company + truck != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: " + truck.GetDataForSave());
|
||||
}
|
||||
}
|
||||
if (_company + truck != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -88,14 +103,19 @@ public partial class FormTruckCollection : Form
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -127,26 +147,30 @@ public partial class FormTruckCollection : Form
|
||||
}
|
||||
DrawingTruck? truck = null;
|
||||
int counter = 100;
|
||||
while (truck == null)
|
||||
{
|
||||
truck = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
try
|
||||
{
|
||||
while (truck == null)
|
||||
{
|
||||
truck = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (truck == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormGasolineTanker form = new()
|
||||
{
|
||||
SetTruck = truck
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SetTruck = truck
|
||||
};
|
||||
form.ShowDialog();
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
@ -156,21 +180,28 @@ public partial class FormTruckCollection : Form
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
try
|
||||
{
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
catch (Exception ex)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -189,14 +220,23 @@ public partial class FormTruckCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
try
|
||||
{
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
@ -252,14 +292,18 @@ public partial class FormTruckCollection : Form
|
||||
{
|
||||
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);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -274,16 +318,18 @@ public partial class FormTruckCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_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);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectGasolineTanker
|
||||
{
|
||||
internal static class Program
|
||||
@ -10,8 +15,38 @@ namespace ProjectGasolineTanker
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormTruckCollection());
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
|
||||
|
||||
}
|
||||
/// <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<FormTruckCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog1.json").Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -8,6 +8,20 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="serilog.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
17
ProjectGasolineTanker/ProjectGasolineTanker/serilog1.json
Normal file
17
ProjectGasolineTanker/ProjectGasolineTanker/serilog1.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Applicatoin": "Sample"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user