лаба 7

This commit is contained in:
Anastasia Yazykova 2024-06-09 18:43:48 +04:00
parent ee0d90098a
commit d4da4c02ae
14 changed files with 365 additions and 169 deletions

View File

@ -32,7 +32,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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>

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 TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
@ -40,42 +41,43 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
public T? Get(int position) public T? Get(int position)
{ {
if (position >= Count || position < 0) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) if (Count + 1 > _maxCount)
{ {
return -1; throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); _collection.Add(obj);
return _collection.Count; return 1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount || position < 0 || position > Count) if (position < 0 || position > Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
if (Count + 1 > _maxCount)
_collection.Insert(position, obj); {
return position; throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return 1;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (_collection == null || position < 0 || position >= _collection.Count) { if (position < 0 || position > Count)
{
return null; throw new PositionOutOfCollectionException(position);
} }
T? obj = _collection[position]; T? obj = _collection[position];
_collection[position] = null; _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 TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
@ -50,16 +51,34 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= _collection.Length || position < 0) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{
return null;
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
int index = 0; for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index = position + 1;
while (index < _collection.Length) while (index < _collection.Length)
{ {
if (_collection[index] == null) if (_collection[index] == null)
@ -67,50 +86,25 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[index] = obj; _collection[index] = obj;
return index; return index;
} }
index++; ++index;
} }
return -1; index = position - 1;
} while (index >= 0)
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] != null)
{ {
int nullIndex = -1; if (_collection[index] == null)
for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) _collection[index] = obj;
{ return index;
nullIndex = i;
break;
}
}
if (nullIndex < 0)
{
return -1;
}
int j = nullIndex - 1;
while (j >= position)
{
_collection[j + 1] = _collection[j];
j--;
} }
--index;
} }
_collection[position] = obj; throw new CollectionOverflowException(Count);
return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= _collection.Length || position < 0) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return null;
}
T? temp = _collection[position]; T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return temp;

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Drawnings; using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
@ -90,11 +91,12 @@ public class StorageCollection<T>
} }
} }
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))
{ {
@ -130,25 +132,25 @@ public class StorageCollection<T>
} }
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует!");
} }
using (StreamReader reader = new(filename)) using (StreamReader reader = new(filename))
{ {
string line = reader.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new ArgumentException("В файле нет данных");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
return false; throw new InvalidDataException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)
@ -163,25 +165,34 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningBus() is T bus) if (elem?.CreateDrawningBus() is T boat)
{ {
if (collection.Insert(bus) <0) try
{ {
return false; if (collection.Insert(boat) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
} }
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
/// <summary> /// <summary>

View File

@ -5,52 +5,49 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Entities; using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings { namespace TrolleybusProject.Drawnings;
public static class ExtentionDrawningBus public static class ExtentionDrawningBus
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info)
{ {
/// <summary> string[] strs = info.Split(_separatorForObject);
/// Разделитель для записи информации по объекту в файл EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs);
/// </summary> if (bus != null)
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info)
{ {
string[] strs = info.Split(_separatorForObject); return new DrawningTrolleybus(bus);
EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs);
if (bus != null)
{
return new DrawningTrolleybus(bus);
}
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
} }
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
} }
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
} }

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.Exceptions;
[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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.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

@ -127,7 +127,7 @@
buttonAddBus.Location = new Point(26, 18); buttonAddBus.Location = new Point(26, 18);
buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(244, 34); buttonAddBus.Size = new Size(244, 34);
buttonAddBus.TabIndex = 1; buttonAddBus.TabIndex = 2;
buttonAddBus.Text = "Добавление автобуса"; buttonAddBus.Text = "Добавление автобуса";
buttonAddBus.UseVisualStyleBackColor = true; buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click; buttonAddBus.Click += buttonAddBus_Click;
@ -212,7 +212,7 @@
radioButtonMassive.Location = new Point(11, 65); radioButtonMassive.Location = new Point(11, 65);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(98, 29); radioButtonMassive.Size = new Size(98, 29);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 1;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true; radioButtonMassive.UseVisualStyleBackColor = true;
@ -263,7 +263,6 @@
menuStrip.Size = new Size(1204, 33); menuStrip.Size = new Size(1204, 33);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "Фаил"; menuStrip.Text = "Фаил";
// //
// FileToolStripMenuItem // FileToolStripMenuItem
// //
@ -281,7 +280,7 @@
// //
save_ToolStripMenuItem.Name = "save_ToolStripMenuItem"; save_ToolStripMenuItem.Name = "save_ToolStripMenuItem";
save_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; save_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
save_ToolStripMenuItem.Size = new Size(270, 34); save_ToolStripMenuItem.Size = new Size(261, 34);
save_ToolStripMenuItem.Text = "Сохранить"; save_ToolStripMenuItem.Text = "Сохранить";
save_ToolStripMenuItem.Click += save_ToolStripMenuItem_Click; save_ToolStripMenuItem.Click += save_ToolStripMenuItem_Click;
// //
@ -289,7 +288,7 @@
// //
load_ToolStripMenuItem.Name = "load_ToolStripMenuItem"; load_ToolStripMenuItem.Name = "load_ToolStripMenuItem";
load_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; load_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
load_ToolStripMenuItem.Size = new Size(270, 34); load_ToolStripMenuItem.Size = new Size(261, 34);
load_ToolStripMenuItem.Text = "Загрузить"; load_ToolStripMenuItem.Text = "Загрузить";
load_ToolStripMenuItem.Click += load_ToolStripMenuItem_Click; load_ToolStripMenuItem.Click += load_ToolStripMenuItem_Click;
// //

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -9,6 +10,7 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using TrolleybusProject.CollectionGenericObjects; using TrolleybusProject.CollectionGenericObjects;
using TrolleybusProject.Drawnings; using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject; namespace TrolleybusProject;
@ -23,12 +25,18 @@ public partial class FormBusCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
public FormBusCollection() /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormBusCollection(ILogger<FormBusCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
private void buttonAddBus_Click(object sender, EventArgs e) private void buttonAddBus_Click(object sender, EventArgs e)
{ {
BusConfig form = new(); BusConfig form = new();
@ -37,18 +45,24 @@ public partial class FormBusCollection : Form
} }
private void SetBus(DrawningBus bus) private void SetBus(DrawningBus bus)
{ {
if (_company == null || bus == null) try
{ {
return; if (_company == null || bus == null)
{
return;
}
if (_company + bus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave());
}
} }
if (_company + bus != -1) catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show(ex.Message);
pictureBox.Image = _company.Show(); _logger.LogError($"Ошибка: {ex.Message}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
} }
} }
@ -67,20 +81,30 @@ public partial class FormBusCollection : Form
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
else
{
MessageBox.Show($"Не удалось удалить объект");
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -90,13 +114,23 @@ public partial class FormBusCollection : Form
{ {
return; return;
} }
DrawningBus? bus = null; DrawningBus? bus = null;
int counter = 100; int counter = 100;
while (bus == null) while (bus == null)
{ {
bus = _company.GetRandomObject(); try
counter--; {
bus = _company.GetRandomObject();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
} }
if (bus == null) if (bus == null)
{ {
@ -122,10 +156,11 @@ public partial class FormBusCollection : Form
private void buttonCollectionAdd_Click(object sender, EventArgs e) private void buttonCollectionAdd_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked)) (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -137,10 +172,9 @@ public partial class FormBusCollection : Form
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
collectionType); _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// Обновление списка в listBoxCollection /// Обновление списка в listBoxCollection
@ -159,19 +193,19 @@ public partial class FormBusCollection : Form
} }
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedItem == null) return; if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
if (listBoxCollection.SelectedIndex < 0)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление невыбранной коллекции");
return; return;
} }
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
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());
_logger.LogInformation($"Удалена коллекция: {name}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -181,6 +215,7 @@ public partial class FormBusCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании невыбранной коллекции");
return; return;
} }
ICollectionGenericObjects<DrawningBus>? collection = ICollectionGenericObjects<DrawningBus>? collection =
@ -188,6 +223,7 @@ public partial class FormBusCollection : Form
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return; return;
} }
switch (comboBoxSelectionCompany.Text) switch (comboBoxSelectionCompany.Text)
@ -205,37 +241,47 @@ public partial class FormBusCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", 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);
} }
} }
} }
private void load_ToolStripMenuItem_Click(object sender, EventArgs e) private void load_ToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) 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("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems(); 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,17 +1,40 @@
namespace TrolleybusProject using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace TrolleybusProject;
internal static class Program
{ {
internal static class Program /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{ {
/// <summary> // To customize application configuration such as set high DPI settings or default font,
/// The main entry point for the application. // see https://aka.ms/applicationconfiguration.
/// </summary> ApplicationConfiguration.Initialize();
[STAThread]
static void Main() ServiceCollection services = new();
{ ConfigureServices(services);
// To customize application configuration such as set high DPI settings or default font, using ServiceProvider serviceProvider = services.BuildServiceProvider();
// see https://aka.ms/applicationconfiguration. Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
ApplicationConfiguration.Initialize(); }
Application.Run(new FormBusCollection()); private static void ConfigureServices(ServiceCollection services)
} {
services
.AddSingleton<FormBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
} }
} }

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +37,13 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

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>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Trolleybus"
}
}
}