7 лаба //

This commit is contained in:
Anya 2024-06-17 00:13:00 +04:00
parent 3655b5bd9a
commit 8aea0aebc3
17 changed files with 412 additions and 167 deletions

View File

@ -1,4 +1,5 @@
using ProjectBus.Drawnings;
using ProjectBus.Exceptions;
namespace ProjectBus.CollectionGenericObject;
/// <summary>
@ -34,7 +35,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -95,8 +96,19 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningSimpleBus? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningSimpleBus? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
}
return bitmap;

View File

@ -1,5 +1,6 @@
using ProjectBus.Drawnings;
using ProjectBus.Entities;
using ProjectBus.Exceptions;
using System;
namespace ProjectBus.CollectionGenericObject;
@ -41,13 +42,25 @@ public class BusStation : AbstractCompany
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningSimpleBus? drawningSimpleBus = _collection?.Get(n);
n++;
if (drawningSimpleBus != null)
try
{
drawningSimpleBus.SetPictureSize(_pictureWidth, _pictureHeight);
drawningSimpleBus.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
DrawningSimpleBus? drawingSimpleBus = _collection?.Get(n);
if (drawingSimpleBus != null)
{
drawingSimpleBus.SetPictureSize(_pictureWidth, _pictureHeight);
drawingSimpleBus.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
n++;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -46,42 +47,32 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position > _collection.Count - 1)
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (_collection.Count + 1 > _maxCount) { return 0; }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return 1;
return Count;
}
public int Insert(T obj, int position)
{
if (_collection.Count + 1 < _maxCount) { return 0; }
if (position > _collection.Count || position < 0)
{
return 0;
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T Remove(int position)
{
if (position > _collection.Count || position < 0)
{
return null;
}
T temp = _collection[position];
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return temp;
return obj;
}
public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using System;
using ProjectBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -50,48 +51,57 @@ namespace ProjectBus.CollectionGenericObject;
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (position >= 0 && position < Count)
if (_collection[i] == null)
{
return _collection[position];
_collection[i] = obj;
return i;
}
return null;
}
public int Insert(T obj)
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
{
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
position = index;
pushed = true;
break;
}
}
return -1;
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count)
if (!pushed)
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то ищется свободное место после этой позиции и идет вставка туда если нет после, ищем до
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
@ -100,46 +110,30 @@ namespace ProjectBus.CollectionGenericObject;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
return position;
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
if (!pushed)
{
return null;
throw new CollectionOverflowException(Count);
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
@ -147,5 +141,4 @@ namespace ProjectBus.CollectionGenericObject;
yield return _collection[i];
}
}
}
}

View File

@ -1,6 +1,8 @@
using ProjectBus.Drawnings;
using ProjectBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -54,19 +56,12 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { });
return;
}
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
@ -76,8 +71,8 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
/// <summary>
@ -89,8 +84,9 @@ public class StorageCollection<T>
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
if (_storages.ContainsKey(name))
return _storages[name];
return null;
}
}
@ -99,11 +95,11 @@ 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 InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -118,6 +114,7 @@ public class StorageCollection<T>
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
@ -137,16 +134,12 @@ public class StorageCollection<T>
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
@ -154,11 +147,11 @@ public class StorageCollection<T>
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException($"{filename} не существует");
}
using (StreamReader fs = File.OpenText(filename))
@ -166,14 +159,12 @@ public class StorageCollection<T>
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new FileFormatException("Файл не подходит");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new IOException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
@ -183,31 +174,33 @@ public class StorageCollection<T>
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningSimpleBus() is T bus)
if (elem?.CreateDrawningSimpleBus() is T simpleBus)
{
if (collection.Insert(bus) == -1)
try
{
return false;
if (collection.Insert(simpleBus) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new DataException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(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 ProjectBus.Exceptions;
public class CollectionInsertException : Exception
{
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectBus.Exceptions;
[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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.Exceptions;
[Serializable]
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :base(message, exception)
{ }
protected CollectionTypeException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBus.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) : base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectBus.Exceptions;
[Serializable]
public 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.Runtime.Serialization;
namespace ProjectBus.Exceptions;
[Serializable]
public 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

@ -2,6 +2,7 @@
using ProjectBus.Drawnings;
using ProjectBus.CollectionGenericObject;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
namespace ProjectBus;
@ -17,13 +18,16 @@ public partial class FormSimpleBusCollection : Form
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormSimpleBusCollection()
public FormSimpleBusCollection(ILogger<FormSimpleBusCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -35,8 +39,9 @@ public partial class FormSimpleBusCollection : Form
{
switch (comboBoxSelectorCompany.Text)
{
case "хранилище":
_company = new BusStation(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningSimpleBus>());
case "Хранилище":
_company = new BusStation(pictureBox.Width, pictureBox.Height,
new MassiveGenericObjects<DrawningSimpleBus>());
break;
}
}
@ -55,18 +60,24 @@ public partial class FormSimpleBusCollection : Form
private void SetSimpleBus(DrawningSimpleBus? drawningSimpleBus)
{
if (_company == null || drawningSimpleBus == null) return;
drawningSimpleBus.SetPictureSize(pictureBox.Width, pictureBox.Height);
if (_company + drawningSimpleBus != -1)
if (_company == null || drawningSimpleBus == null)
{
return;
}
try
{
var res = _company + drawningSimpleBus;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Объект не удалось добавить");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -128,20 +139,25 @@ public partial class FormSimpleBusCollection : Form
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -153,13 +169,15 @@ public partial class FormSimpleBusCollection : Form
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
return;
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
pictureBox.Image = _company.Show();
}
/// <summary>
@ -206,7 +224,8 @@ public partial class FormSimpleBusCollection : Form
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
@ -222,8 +241,18 @@ public partial class FormSimpleBusCollection : Form
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -239,15 +268,19 @@ public partial class FormSimpleBusCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
@ -287,8 +320,9 @@ public partial class FormSimpleBusCollection : Form
switch (comboBoxSelectorCompany.Text)
{
case "хранилище":
case "Хранилище":
_company = new BusStation(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
@ -296,6 +330,7 @@ public partial class FormSimpleBusCollection : Form
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
@ -305,13 +340,19 @@ public partial class FormSimpleBusCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_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($"Ошибка: {ex.Message}", ex.Message);
}
}
@ -326,14 +367,20 @@ public partial class FormSimpleBusCollection : 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);
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
RerfreshListBoxItems();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,4 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using NLog.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using ProjectBus;
using System;
using Microsoft.Extensions.Logging;
namespace lab_0
{
@ -13,7 +18,22 @@ namespace lab_0
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormSimpleBusCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormSimpleBusCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormSimpleBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

25
lab_0/ProjectBus.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectBus", "ProjectBus.csproj", "{7F126B40-AEDE-40A9-840E-4158D2218B6F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7F126B40-AEDE-40A9-840E-4158D2218B6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F126B40-AEDE-40A9-840E-4158D2218B6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F126B40-AEDE-40A9-840E-4158D2218B6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F126B40-AEDE-40A9-840E-4158D2218B6F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {771E3743-AEF8-46E6-BE29-0866902F9DDA}
EndGlobalSection
EndGlobal

15
lab_0/nlog.config Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>