лабораторная работа №7
This commit is contained in:
parent
744a9cec65
commit
5d47765f02
@ -1,5 +1,6 @@
|
|||||||
using ProjectMonorail.CollectionGenericObject;
|
using ProjectMonorail.CollectionGenericObject;
|
||||||
using ProjectMonorail.Drawings;
|
using ProjectMonorail.Drawings;
|
||||||
|
using ProjectMonorail.Exceptions;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@ -41,7 +42,7 @@ public abstract class AbstractCompany
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Вычисление максимального количества элементов, которые можно разместить в окне
|
/// Вычисление максимального количества элементов, которые можно разместить в окне
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
private int GetMaxCount => (_pictureHeight / _placeSizeHeight) * (_pictureWidth / _placeSizeWidth);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
@ -106,8 +107,12 @@ public abstract class AbstractCompany
|
|||||||
SetObjectsPosition();
|
SetObjectsPosition();
|
||||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||||
{
|
{
|
||||||
DrawingTrain? obj = _collection?.Get(i);
|
try
|
||||||
obj?.DrawTransport(graphics);
|
{
|
||||||
|
DrawingTrain? obj = _collection?.Get(i);
|
||||||
|
obj?.DrawTransport(graphics);
|
||||||
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
}
|
}
|
||||||
return bitmap;
|
return bitmap;
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
using ProjectMonorail.CollectionGenericObject;
|
using ProjectMonorail.CollectionGenericObject;
|
||||||
using System;
|
using ProjectMonorail.Exceptions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace ProjectMonorail.CollectionGenericObjects;
|
namespace ProjectMonorail.CollectionGenericObjects;
|
||||||
|
|
||||||
@ -40,28 +36,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
|
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count) { return null; }
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
{
|
{
|
||||||
if (obj == null || Count + 1 > _maxCount) { return -1; }
|
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
|
||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count + 1;
|
return Count + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (obj == null || Count + 1 > _maxCount) { return -1; }
|
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
|
||||||
if (position < 0 || position >= Count) { return -1; }
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return Count + 1;
|
return Count + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public T Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count) { return null; }
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
T tmp = _collection[position];
|
T tmp = _collection[position];
|
||||||
_collection.RemoveAt(position);
|
_collection.RemoveAt(position);
|
||||||
return tmp;
|
return tmp;
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
using ProjectMonorail.CollectionGenericObjects;
|
using ProjectMonorail.CollectionGenericObjects;
|
||||||
using System;
|
using ProjectMonorail.Exceptions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace ProjectMonorail.CollectionGenericObject;
|
namespace ProjectMonorail.CollectionGenericObject;
|
||||||
|
|
||||||
@ -55,11 +51,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
|
|
||||||
public T? Get(int position)
|
public T? Get(int position)
|
||||||
{
|
{
|
||||||
if (position >= 0 && position < Count)
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
{
|
if (_collection[position] == null) { throw new ObjectNotFoundException(); }
|
||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj)
|
public int Insert(T obj)
|
||||||
@ -72,15 +66,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position)
|
public int Insert(T obj, int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count)
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
for (int i = position; i < Count; i++)
|
for (int i = position; i < Count; i++)
|
||||||
{
|
{
|
||||||
if (_collection[i] == null)
|
if (_collection[i] == null)
|
||||||
@ -97,15 +88,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
throw new CollectionOverflowException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public T Remove(int position)
|
public T Remove(int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position >= Count)
|
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
|
||||||
{
|
if (_collection == null) { throw new ObjectNotFoundException(); }
|
||||||
return null;
|
|
||||||
}
|
|
||||||
T tmp = _collection[position];
|
T tmp = _collection[position];
|
||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return tmp;
|
return tmp;
|
||||||
|
@ -1,10 +1,6 @@
|
|||||||
using ProjectMonorail.CollectionGenericObject;
|
using ProjectMonorail.CollectionGenericObject;
|
||||||
using ProjectMonorail.Drawings;
|
using ProjectMonorail.Drawings;
|
||||||
using System;
|
using ProjectMonorail.Exceptions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace ProjectMonorail.CollectionGenericObjects;
|
namespace ProjectMonorail.CollectionGenericObjects;
|
||||||
|
|
||||||
@ -97,12 +93,11 @@ 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 ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
@ -142,19 +137,17 @@ public class StorageCollection<T>
|
|||||||
streamWriter.Write(_separatorItems);
|
streamWriter.Write(_separatorItems);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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 FileNotFoundException("Данный файл не существует");
|
||||||
}
|
}
|
||||||
|
|
||||||
using FileStream fs = new(filename, FileMode.Open);
|
using FileStream fs = new(filename, FileMode.Open);
|
||||||
@ -162,12 +155,11 @@ public class StorageCollection<T>
|
|||||||
string firstString = streamReader.ReadLine();
|
string firstString = streamReader.ReadLine();
|
||||||
if (firstString != _collectionKey || firstString.Length == 0)
|
if (firstString != _collectionKey || firstString.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new ArgumentException("В файле нет данных");
|
||||||
}
|
}
|
||||||
if (!firstString.Equals(_collectionKey))
|
if (!firstString.Equals(_collectionKey))
|
||||||
{
|
{
|
||||||
//если нет такой записи, то это не те данные
|
throw new InvalidDataException("В файле неверные данные");
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_storages.Clear();
|
_storages.Clear();
|
||||||
@ -182,7 +174,7 @@ 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("Не удалось создать коллекцию");
|
||||||
}
|
}
|
||||||
|
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||||
@ -192,18 +184,22 @@ public class StorageCollection<T>
|
|||||||
{
|
{
|
||||||
if (elem?.CreateDrawingTrain() is T train)
|
if (elem?.CreateDrawingTrain() is T train)
|
||||||
{
|
{
|
||||||
if (collection.Insert(train) == -1)
|
try
|
||||||
{
|
{
|
||||||
return false;
|
if (collection.Insert(train) == -1)
|
||||||
|
{
|
||||||
|
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>
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
using ProjectMonorail.CollectionGenericObject;
|
using ProjectMonorail.CollectionGenericObject;
|
||||||
using ProjectMonorail.Drawings;
|
using ProjectMonorail.Drawings;
|
||||||
|
using ProjectMonorail.Exceptions;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@ -45,9 +46,14 @@ public class TrainSharingService : AbstractCompany
|
|||||||
{
|
{
|
||||||
for (int x = 10; x + _placeSizeWidth < _pictureWidth; x += _placeSizeWidth)
|
for (int x = 10; x + _placeSizeWidth < _pictureWidth; x += _placeSizeWidth)
|
||||||
{
|
{
|
||||||
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
try
|
||||||
_collection?.Get(counter)?.SetPosition(x, y);
|
{
|
||||||
counter++;
|
_collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||||
|
_collection?.Get(counter)?.SetPosition(x, y);
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
catch (ObjectNotFoundException) { }
|
||||||
|
catch (PositionOutOfCollectionException) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
25
ProjectMonorail/Exceptions/CollectionOverflowException.cs
Normal file
25
ProjectMonorail/Exceptions/CollectionOverflowException.cs
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMonorail.Exceptions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Класс, описывающий ошибку переполнения коллекции
|
||||||
|
/// </summary>
|
||||||
|
[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 context) : base(info, context) { }
|
||||||
|
}
|
25
ProjectMonorail/Exceptions/ObjectNotFoundException.cs
Normal file
25
ProjectMonorail/Exceptions/ObjectNotFoundException.cs
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMonorail.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 context) : base(info, context) { }
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectMonorail.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 context) : base(info, context) { }
|
||||||
|
}
|
@ -1,14 +1,7 @@
|
|||||||
using ProjectMonorail.CollectionGenericObject;
|
using Microsoft.Extensions.Logging;
|
||||||
using ProjectMonorail.CollectionGenericObjects;
|
using ProjectMonorail.CollectionGenericObjects;
|
||||||
using ProjectMonorail.Drawings;
|
using ProjectMonorail.Drawings;
|
||||||
using System;
|
using ProjectMonorail.Exceptions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.ComponentModel;
|
|
||||||
using System.Data;
|
|
||||||
using System.Drawing;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace ProjectMonorail;
|
namespace ProjectMonorail;
|
||||||
@ -28,13 +21,19 @@ public partial class FormTrainCollection : Form
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private AbstractCompany? _company = null;
|
private AbstractCompany? _company = null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Логер
|
||||||
|
/// </summary>
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Конструктор
|
/// Конструктор
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public FormTrainCollection()
|
public FormTrainCollection(ILogger<FormTrainCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storageCollection = new();
|
_storageCollection = new();
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -70,14 +69,17 @@ public partial class FormTrainCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_company + train != -1)
|
try
|
||||||
{
|
{
|
||||||
|
var set = _company + train;
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
|
_logger.LogInformation($"Добавлен объект: {train.GetDataForSave()}");
|
||||||
pictureBox.Image = _company.Show();
|
pictureBox.Image = _company.Show();
|
||||||
}
|
}
|
||||||
else
|
catch (CollectionOverflowException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Коллекция переполнена");
|
||||||
|
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,6 +92,7 @@ public partial class FormTrainCollection : Form
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,15 +101,30 @@ public partial class FormTrainCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
try
|
||||||
if (_company - pos != null)
|
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||||
pictureBox.Image = _company.Show();
|
if (_company - pos != null)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Объект удален");
|
||||||
|
pictureBox.Image = _company.Show();
|
||||||
|
_logger.LogInformation("Удаление объекта по индексу {pos}", pos);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
|
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
catch (ObjectNotFoundException ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Ошибка: отсутствует объект");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
catch (PositionOutOfCollectionException ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show("Ошибка: неправильная позиция");
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,11 +144,17 @@ public partial class FormTrainCollection : Form
|
|||||||
int counter = 100;
|
int counter = 100;
|
||||||
while (train == null)
|
while (train == null)
|
||||||
{
|
{
|
||||||
train = _company.GetRandomObject();
|
try
|
||||||
counter--;
|
|
||||||
if (counter <= 0)
|
|
||||||
{
|
{
|
||||||
break;
|
train = _company.GetRandomObject();
|
||||||
|
}
|
||||||
|
catch (ObjectNotFoundException)
|
||||||
|
{
|
||||||
|
counter--;
|
||||||
|
if (counter <= 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -171,6 +195,7 @@ public partial class FormTrainCollection : Form
|
|||||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning("Создание компании без данных");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,6 +210,7 @@ public partial class FormTrainCollection : Form
|
|||||||
}
|
}
|
||||||
|
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||||
|
_logger.LogInformation($"Добавлена коллекция {textBoxCollectionName.Text}");
|
||||||
RefreshListBoxItems();
|
RefreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,13 +224,16 @@ public partial class FormTrainCollection : Form
|
|||||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||||
{
|
{
|
||||||
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}");
|
||||||
RefreshListBoxItems();
|
RefreshListBoxItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -234,13 +263,15 @@ public partial class FormTrainCollection : Form
|
|||||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
|
_logger.LogWarning("Создание компании, не выбрав коллекцию");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ICollectionGenericObjects<DrawingTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
CollectionGenericObject.ICollectionGenericObjects<DrawingTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||||
if (collection == null)
|
if (collection == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не проинициализирована");
|
MessageBox.Show("Коллекция не проинициализирована");
|
||||||
|
_logger.LogWarning("Не далось иницализировать коллекцию");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -248,6 +279,7 @@ public partial class FormTrainCollection : Form
|
|||||||
{
|
{
|
||||||
case "Хранилище":
|
case "Хранилище":
|
||||||
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
|
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||||
|
_logger.LogInformation("Компания создана");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -264,13 +296,16 @@ public partial class FormTrainCollection : 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -284,14 +319,17 @@ public partial class FormTrainCollection : Form
|
|||||||
{
|
{
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||||
{
|
{
|
||||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
try
|
||||||
{
|
{
|
||||||
|
_storageCollection.LoadData(openFileDialog.FileName);
|
||||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
|
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
|
||||||
RefreshListBoxItems();
|
RefreshListBoxItems();
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось загрузить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,10 @@
|
|||||||
namespace ProjectMonorail
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ProjectMonorail;
|
||||||
|
using Serilog;
|
||||||
|
|
||||||
|
namespace ProjectAirFighter
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
@ -10,8 +16,30 @@ namespace ProjectMonorail
|
|||||||
{
|
{
|
||||||
// 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.
|
||||||
|
ServiceCollection serviceCollection = new();
|
||||||
|
ConfigureService(serviceCollection);
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormTrainCollection());
|
using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConfigureService(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormTrainCollection>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
var configuration = new ConfigurationBuilder()
|
||||||
|
.SetBasePath(Directory.GetCurrentDirectory())
|
||||||
|
.AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
var logger = new LoggerConfiguration()
|
||||||
|
.ReadFrom.Configuration(configuration)
|
||||||
|
.CreateLogger();
|
||||||
|
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddSerilog(logger);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -8,4 +8,17 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</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="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
|
||||||
|
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
20
ProjectMonorail/appSettings.json
Normal file
20
ProjectMonorail/appSettings.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": "ProjectMonorail"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user