Лабоарторная работа №7
This commit is contained in:
parent
b9afd42e2e
commit
914633077e
@ -57,6 +57,7 @@ public abstract class AbstractCompany
|
|||||||
/// <param name="truck">Добавляемый объект</param>
|
/// <param name="truck">Добавляемый объект</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static int operator +(AbstractCompany company, DrawingTruck truck)
|
public static int operator +(AbstractCompany company, DrawingTruck truck)
|
||||||
|
|
||||||
{
|
{
|
||||||
return company._collection.Insert(truck);
|
return company._collection.Insert(truck);
|
||||||
}
|
}
|
||||||
@ -93,10 +94,14 @@ public abstract class AbstractCompany
|
|||||||
DrawBackgound(graphics);
|
DrawBackgound(graphics);
|
||||||
SetObjectsPosition();
|
SetObjectsPosition();
|
||||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
DrawingTruck? obj = _collection?.Get(i);
|
DrawingTruck? obj = _collection?.Get(i);
|
||||||
obj?.DrawTransport(graphics);
|
obj?.DrawTransport(graphics);
|
||||||
}
|
}
|
||||||
|
catch (Exception) { }
|
||||||
|
}
|
||||||
return bitmap;
|
return bitmap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
using ProjectGasolineTanker.Exceptions;
|
||||||
|
using System.CodeDom;
|
||||||
|
|
||||||
|
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
@ -45,19 +48,20 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
// проверка позиции
|
// проверка позиции
|
||||||
if (position >= Count || position < 0)
|
// выброс ошибки, если выход за границы массива
|
||||||
{
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
|
// выброс ошибки если переполнение
|
||||||
if (Count == _maxCount) return -1;
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
@ -65,15 +69,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
// проверка, что не превышено максимальное количество элементов
|
// проверка, что не превышено максимальное количество элементов
|
||||||
// проверка позиции
|
// проверка позиции
|
||||||
// вставка по позиции
|
// вставка по позиции
|
||||||
|
// выброс ошибки, если переполнение
|
||||||
|
// выброс ошибки если выход за границу
|
||||||
|
|
||||||
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
|
|
||||||
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
|
|
||||||
if (position >= Count || position < 0)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
if (Count == _maxCount)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return position;
|
return position;
|
||||||
|
|
||||||
@ -83,11 +85,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
{
|
{
|
||||||
// проверка позиции
|
// проверка позиции
|
||||||
// удаление объекта из списка
|
// удаление объекта из списка
|
||||||
if (position >= Count || position < 0) return null;
|
//выброс ошибки, если выход за границы массива
|
||||||
|
|
||||||
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
T obj = _collection[position];
|
T obj = _collection[position];
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return obj;
|
return obj;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<T?> GetItems()
|
public IEnumerable<T?> GetItems()
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
using ProjectGasolineTanker.Exceptions;
|
||||||
|
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
@ -47,19 +48,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
_collection = Array.Empty<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];
|
return _collection[position];
|
||||||
|
|
||||||
}
|
}
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
// вставка в свободное место набора
|
// вставка в свободное место набора
|
||||||
for (int i = 0; i < Count; ++i)
|
// выброс ошибки, если переполнение
|
||||||
|
//выброс ошибки, если выход за границы массива
|
||||||
|
for (int i = 0; i < Count; i++)
|
||||||
{
|
{
|
||||||
if (_collection[i] == null)
|
if (_collection[i] == null)
|
||||||
{
|
{
|
||||||
@ -67,7 +71,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException(Count);
|
||||||
|
|
||||||
}
|
}
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
@ -76,11 +80,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||||
// ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до
|
// ищется свободное место после этой позиции и идет вставка туда, если нет после, ищем до
|
||||||
// вставка
|
// вставка
|
||||||
|
//выброс ошибки, если переполнение
|
||||||
if (position >= Count || position < 0)
|
//выброс ошибки, если выход за границы массива
|
||||||
{
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_collection[position] == null)
|
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
|
//// удаление объекта из массива, присвоив элементу массива значение 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];
|
T temp = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return temp;
|
return temp;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public IEnumerable<T?> GetItems()
|
public IEnumerable<T?> GetItems()
|
||||||
{
|
{
|
||||||
for (int i = 0; i < _collection.Length; ++i)
|
for (int i = 0; i < _collection.Length; ++i)
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using ProjectGasolineTanker.Drawings;
|
using ProjectGasolineTanker.Drawings;
|
||||||
|
using ProjectGasolineTanker.Exceptions;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
namespace ProjectGasolineTanker.CollectionGenericObjects;
|
||||||
@ -108,12 +109,12 @@ public class StorageCollection<T>
|
|||||||
/// Сохранение информации по автомобилям в хранилище в файл
|
/// Сохранение информации по автомобилям в хранилище в файл
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename">Путь и имя файла</param>
|
/// <param name="filename">Путь и имя файла</param>
|
||||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
public void SaveData(string filename)
|
||||||
public bool SaveData(string filename)
|
|
||||||
{
|
{
|
||||||
if (_storages.Count == 0)
|
if (_storages.Count == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||||
|
|
||||||
}
|
}
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
@ -151,30 +152,29 @@ public class StorageCollection<T>
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
// /// Загрузка информации по грузовикам в хранилище из файла
|
// /// Загрузка информации по грузовикам в хранилище из файла
|
||||||
// /// </summary>
|
// /// </summary>
|
||||||
// /// <param name="filename">Путь и имя файла</param>
|
// /// <param name="filename">Путь и имя файла</param>
|
||||||
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
public void LoadData(string filename)
|
||||||
public bool LoadData(string filename)
|
|
||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Файл не существует");
|
||||||
}
|
}
|
||||||
using (StreamReader fs = File.OpenText(filename))
|
using (StreamReader fs = File.OpenText(filename))
|
||||||
{
|
{
|
||||||
string str = fs.ReadLine();
|
string str = fs.ReadLine();
|
||||||
if (str == null || str.Length == 0)
|
if (str == null || str.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("В файле нет данных");
|
||||||
|
|
||||||
}
|
}
|
||||||
if (!str.StartsWith(_collectionKey))
|
if (!str.StartsWith(_collectionKey))
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("В файле неверные данные");
|
||||||
}
|
}
|
||||||
_storages.Clear();
|
_storages.Clear();
|
||||||
string strs = "";
|
string strs = "";
|
||||||
@ -189,23 +189,31 @@ public class StorageCollection<T>
|
|||||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||||
if (collection == null)
|
if (collection == null)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Не удалось создать коллекцию");
|
||||||
|
|
||||||
}
|
}
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (string elem in set)
|
foreach (string elem in set)
|
||||||
{
|
{
|
||||||
if (elem?.CreateDrawingTruck() is T truck)
|
if (elem?.CreateDrawingTruck() is T truck)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (collection.Insert(truck) == -1)
|
if (collection.Insert(truck) == -1)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
|
{
|
||||||
|
throw new Exception("Коллекция переполнена", ex);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_storages.Add(record[0], collection);
|
_storages.Add(record[0], collection);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -44,11 +44,12 @@ public class TruckSharingService : AbstractCompany
|
|||||||
{
|
{
|
||||||
for (int i = 0; i < (_collection.Count); i++)
|
for (int i = 0; i < (_collection.Count); i++)
|
||||||
{
|
{
|
||||||
if (_collection.Get(i) != null)
|
try
|
||||||
{
|
{
|
||||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||||
_collection.Get(i).SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
|
_collection.Get(i).SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
|
||||||
}
|
}
|
||||||
|
catch (Exception) { }
|
||||||
|
|
||||||
if (positionWidth < width - 1)
|
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 ProjectGasolineTanker.Drawings;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
@ -19,13 +21,20 @@ public partial class FormTruckCollection : Form
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private AbstractCompany? _company = null;
|
private AbstractCompany? _company = null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Логер
|
||||||
|
/// </summary>
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormTruckCollection()
|
public FormTruckCollection(ILogger<FormTruckCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
|
_logger.LogInformation("Форма загрузилась");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -55,6 +64,8 @@ public partial class FormTruckCollection : Form
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="truck"></param>
|
/// <param name="truck"></param>
|
||||||
private void SetTruck(DrawingTruck truck)
|
private void SetTruck(DrawingTruck truck)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
if (_company == null || truck == null)
|
if (_company == null || truck == null)
|
||||||
{
|
{
|
||||||
@ -64,10 +75,14 @@ public partial class FormTruckCollection : Form
|
|||||||
{
|
{
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Добавлен объект: " + truck.GetDataForSave());
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
|
catch (CollectionOverflowException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,14 +103,19 @@ public partial class FormTruckCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||||
|
try
|
||||||
|
{
|
||||||
if (_company - pos != null)
|
if (_company - pos != null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
MessageBox.Show("Объект удален");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,6 +147,8 @@ public partial class FormTruckCollection : Form
|
|||||||
}
|
}
|
||||||
DrawingTruck? truck = null;
|
DrawingTruck? truck = null;
|
||||||
int counter = 100;
|
int counter = 100;
|
||||||
|
try
|
||||||
|
{
|
||||||
while (truck == null)
|
while (truck == null)
|
||||||
{
|
{
|
||||||
truck = _company.GetRandomObject();
|
truck = _company.GetRandomObject();
|
||||||
@ -136,16 +158,18 @@ public partial class FormTruckCollection : Form
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (truck == null)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
FormGasolineTanker form = new()
|
FormGasolineTanker form = new()
|
||||||
{
|
{
|
||||||
SetTruck = truck
|
SetTruck = truck
|
||||||
};
|
};
|
||||||
form.ShowDialog();
|
form.ShowDialog();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление коллекции
|
/// Добавление коллекции
|
||||||
@ -156,10 +180,11 @@ public partial class FormTruckCollection : Form
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
CollectionType collectionType = CollectionType.None;
|
CollectionType collectionType = CollectionType.None;
|
||||||
if (radioButtonMassive.Checked)
|
if (radioButtonMassive.Checked)
|
||||||
{
|
{
|
||||||
@ -171,6 +196,12 @@ public partial class FormTruckCollection : Form
|
|||||||
}
|
}
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -189,13 +220,22 @@ public partial class FormTruckCollection : Form
|
|||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
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());
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обновление списка в listBoxCollection
|
/// Обновление списка в listBoxCollection
|
||||||
@ -252,14 +292,18 @@ public partial class FormTruckCollection : Form
|
|||||||
{
|
{
|
||||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
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 (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
MessageBox.Show("Загрузка прошла успешно",
|
_storageCollection.LoadData(openFileDialog.FileName);
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
|
_logger.LogInformation("Сохранение в файл: {filename}", openFileDialog.FileName);
|
||||||
}
|
}
|
||||||
else
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат",
|
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
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
|
namespace ProjectGasolineTanker
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -10,8 +15,38 @@ namespace ProjectGasolineTanker
|
|||||||
{
|
{
|
||||||
// To customize application configuration such as set high DPI settings or default font,
|
// To customize application configuration such as set high DPI settings or default font,
|
||||||
// see https://aka.ms/applicationconfiguration.
|
// see https://aka.ms/applicationconfiguration.
|
||||||
|
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new 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>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</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>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<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