Лабораторная работа №7
This commit is contained in:
parent
726d0b2eae
commit
46b2d2d8ec
@ -1,4 +1,5 @@
|
||||
using ProjectCleaningCar.Drawnings;
|
||||
using ProjectSportCar.Exceptions;
|
||||
|
||||
namespace ProjectCleaningCar.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@ -9,11 +10,11 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 150;
|
||||
protected readonly int _placeSizeWidth = 160;
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 80;
|
||||
protected readonly int _placeSizeHeight = 90;
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
@ -29,7 +30,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -85,8 +86,12 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningTruck? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningTruck? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException) { };
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
@ -1,10 +1,5 @@
|
||||
using ProjectCleaningCar.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Metrics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ProjectSportCar.Exceptions;
|
||||
|
||||
namespace ProjectCleaningCar.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@ -38,16 +33,25 @@ public class CarSharingCompany : AbstractCompany
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int counter = 0;
|
||||
for (int y = 5; y < _pictureHeight; y += 90)
|
||||
int valPlaceY = _pictureHeight / _placeSizeHeight;
|
||||
int valPlaceX = _pictureWidth / _placeSizeWidth;
|
||||
for (int y = 5; y < (valPlaceY * _placeSizeHeight); y += _placeSizeHeight)
|
||||
{
|
||||
for (int x = 5; x < _pictureWidth; x += 190)
|
||||
for (int x = 5; x < (valPlaceX * _placeSizeWidth); x += _placeSizeWidth)
|
||||
{
|
||||
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(counter)?.SetPosition(x, y);
|
||||
if (counter < _collection?.Count)
|
||||
{
|
||||
try
|
||||
{
|
||||
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(counter)?.SetPosition(x, y);
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
}
|
||||
x += 30;
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using ProjectCleaningCar.Exceptions;
|
||||
using ProjectSportCar.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -46,38 +48,33 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
return _collection[position];
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) { return -1; }
|
||||
if (Count == _maxCount) { throw new CollectionOverflowException(_collection.Count); }
|
||||
_collection.Add(obj);
|
||||
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count || Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
_collection.Insert(position, obj);
|
||||
|
||||
return position;
|
||||
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position < 0 || position >= _collection.Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
|
@ -1,4 +1,7 @@
|
||||
namespace ProjectCleaningCar.CollectionGenericObjects;
|
||||
using ProjectCleaningCar.Exceptions;
|
||||
using ProjectSportCar.Exceptions;
|
||||
|
||||
namespace ProjectCleaningCar.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
@ -46,33 +49,28 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
if (position < 0 && position >= Count)
|
||||
{
|
||||
return _collection[position];
|
||||
throw new PositionOutOfCollectionException();
|
||||
}
|
||||
|
||||
return null;
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
return Insert(obj, 0);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
@ -96,14 +94,15 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException("Отсутствует свободное место для вставки");
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= _collection.Length)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
throw new ObjectNotFoundException(position);
|
||||
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
|
@ -1,9 +1,6 @@
|
||||
using ProjectCleaningCar.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ProjectCleaningCar.Exceptions;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectCleaningCar.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@ -106,12 +103,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 Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -147,18 +143,16 @@ public class StorageCollection<T>
|
||||
sb.Clear();
|
||||
}
|
||||
}
|
||||
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 sr = new StreamReader(filename))
|
||||
@ -166,7 +160,7 @@ public class StorageCollection<T>
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
return false;
|
||||
throw new Exception("Не удалось преобразовать данные");
|
||||
_storages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
@ -179,7 +173,7 @@ 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]);
|
||||
@ -187,16 +181,24 @@ public class StorageCollection<T>
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTruck() is T ship)
|
||||
if (elem?.CreateDrawningTruck() is T truck)
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
if (collection.Insert(truck) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
|
@ -1,10 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ProjectCleaningCar.Entites;
|
||||
using ProjectCleaningCar.Entites;
|
||||
|
||||
namespace ProjectCleaningCar.Drawnings;
|
||||
/// <summary>
|
||||
|
@ -0,0 +1,15 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectCleaningCar.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,15 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectSportCar.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,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectSportCar.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,13 +1,9 @@
|
||||
using ProjectCleaningCar.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectCleaningCar.CollectionGenericObjects;
|
||||
using ProjectCleaningCar.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ProjectCleaningCar.Exceptions;
|
||||
using ProjectSportCar.Exceptions;
|
||||
using System.Numerics;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectCleaningCar;
|
||||
@ -24,15 +20,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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
/// </summary>
|
||||
@ -55,21 +56,29 @@ public partial class FormTruckCollection : Form
|
||||
form.Show();
|
||||
}
|
||||
|
||||
private void SetTruck(DrawningTruck? plane)
|
||||
private void SetTruck(DrawningTruck? truck)
|
||||
{
|
||||
if (_company == null || plane == null)
|
||||
if (_company == null || truck == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + plane != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company + truck != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show("Ошибка переполнения коллекции");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -80,26 +89,40 @@ public partial class FormTruckCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveTruck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company ==
|
||||
null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
return;
|
||||
}
|
||||
else
|
||||
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удаление объекта по индексу {pos}", pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка: отсутствует объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка: неправильная позиция");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -157,10 +180,11 @@ 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);
|
||||
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@ -170,7 +194,9 @@ public partial class FormTruckCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
@ -182,20 +208,15 @@ public partial class FormTruckCollection : Form
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
|
||||
string selectedCollection = listBoxCollection.SelectedItem.ToString();
|
||||
|
||||
if (MessageBox.Show($"Удалить коллекцию {selectedCollection}?", "Удаление коллекции",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(selectedCollection);
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
@ -242,7 +263,7 @@ public partial class FormTruckCollection : Form
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
/// Обработка нажания "Сохранение"
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
@ -250,18 +271,18 @@ public partial class FormTruckCollection : 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Загрузка"
|
||||
@ -272,16 +293,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);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_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,17 +1,44 @@
|
||||
namespace ProjectCleaningCar
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectCleaningCar;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectSportCar;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
internal static class Program
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ServiceCollection serviceCollection = new();
|
||||
ConfigureService(serviceCollection);
|
||||
ApplicationConfiguration.Initialize();
|
||||
using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
|
||||
}
|
||||
|
||||
private static void ConfigureService(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormTruckCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormTruckCollection());
|
||||
}
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: "C:\\Users\\danil\\Source\\Repos\\PIbd-12_Smolin_D.S._Simple\\ProjectCleaningCar\\ProjectCleaningCar\\appSetting.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
@ -8,6 +8,16 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
20
ProjectCleaningCar/ProjectCleaningCar/appSetting.json
Normal file
20
ProjectCleaningCar/ProjectCleaningCar/appSetting.json
Normal 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": "Battleship"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user