Lab7-ready

This commit is contained in:
Kankistodor 2024-04-24 23:26:19 +04:00
parent 4cab399d4b
commit c50ddb14a2
21 changed files with 564 additions and 225 deletions

View File

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

View File

@ -1,4 +1,6 @@
namespace ProjectElectroTrans.CollectionGenericObjects; using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -43,28 +45,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<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);
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)
{ {
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= _collection.Count || position < 0) return null; if (position >= _collection.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;

View File

@ -1,4 +1,5 @@
 using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans.CollectionGenericObjects; namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary> /// <summary>
@ -17,10 +18,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int MaxCount public int MaxCount
{ {
get get { return _collection.Length; }
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -49,14 +47,11 @@ 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(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
// вставка в свободное место набора // вставка в свободное место набора
@ -69,16 +64,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
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(position);
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то // проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
@ -111,7 +103,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (!pushed) if (!pushed)
{ {
return position; throw new CollectionOverflowException(Count);
} }
} }
@ -123,12 +115,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Remove(int position) public T? Remove(int position)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{
return null;
}
if (_collection[position] == null) return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position]; T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;

View File

@ -1,6 +1,9 @@
using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Drawnings;
using System.Text; using System.Text;
using ProjectElectroTrans.CollectionGenericObjects; using ProjectElectroTrans.CollectionGenericObjects;
using ProjectElectroTrans.Exceptions;
using FileFormatException = ProjectElectroTrans.Exceptions.FileFormatException;
using FileNotFoundException = ProjectElectroTrans.Exceptions.FileNotFoundException;
namespace ProjectElectroTrans.CollectionGenericObjects; namespace ProjectElectroTrans.CollectionGenericObjects;
@ -51,9 +54,9 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (_storages.ContainsKey(name)) return; if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name);
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции");
else if (collectionType == CollectionType.Massive) if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[name] = new ListGenericObjects<T>();
@ -67,6 +70,7 @@ public class StorageCollection<T>
{ {
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
_storages.Remove(name); _storages.Remove(name);
} }
/// <summary> /// <summary>
@ -93,7 +97,7 @@ public class StorageCollection<T>
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new EmptyFileExeption();
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -154,14 +158,15 @@ public class StorageCollection<T>
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 (string.IsNullOrEmpty(str))
{ {
return false; throw new FileNotFoundException(filename);
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new FileFormatException(filename);
} }
_storages.Clear(); _storages.Clear();
@ -178,7 +183,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 CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -186,10 +191,71 @@ public class StorageCollection<T>
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTrans() is T ship) if (elem?.CreateDrawningTrans() is T ship)
{
try
{
collection.Insert(ship);
}
catch (Exception ex)
{
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
if (!File.Exists(filename))
{
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (string.IsNullOrEmpty(str))
{
throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrans() is T ship)
{
try
{ {
if (collection.Insert(ship) == -1) if (collection.Insert(ship) == -1)
{ {
return false; throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw ex.InnerException!;
} }
} }
} }

View File

@ -1,6 +1,7 @@
using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Entities; using ProjectElectroTrans.Entities;
using System; using System;
using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans.CollectionGenericObjects; namespace ProjectElectroTrans.CollectionGenericObjects;
@ -15,7 +16,8 @@ public class TransDepoService : AbstractCompany
/// <param name="picWidth"></param> /// <param name="picWidth"></param>
/// <param name="picHeight"></param> /// <param name="picHeight"></param>
/// <param name="collection"></param> /// <param name="collection"></param>
public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(picWidth, picHeight, collection) public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(
picWidth, picHeight, collection)
{ {
} }
@ -26,13 +28,15 @@ public class TransDepoService : AbstractCompany
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{ {
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j)); g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
} g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
} }
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
@ -41,15 +45,27 @@ public class TransDepoService : AbstractCompany
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
try
{ {
DrawingTrans? drawingTrans = _collection?.Get(n); DrawingTrans? drawingTrans = _collection?.Get(n);
n++;
if (drawingTrans != null) if (drawingTrans != null)
{ {
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight); drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
} }
} }
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
n++;
}
} }
} }
} }

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class CollectionInsertException : Exception
{
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception) { }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,31 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions
{
[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)
{
}
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectElectroTrans.Exceptions;
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception) { }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

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

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class EmptyStorageException : Exception
{
public EmptyStorageException() : base() { }
public EmptyStorageException(string message) : base(message) { }
public EmptyStorageException(string message, Exception exception) :
base(message, exception) { }
protected EmptyStorageException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class FileFormatException : Exception
{
public FileFormatException() : base() { }
public FileFormatException(string message) : base(message) { }
public FileFormatException(string name, Exception exception) :
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { }
protected FileFormatException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.Exceptions;
public class FileNotFoundException : Exception
{
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
public FileNotFoundException() : base() { }
public FileNotFoundException(string name, string message) : base(message) { }
public FileNotFoundException(string name, string message, Exception exception) :
base(message, exception) { }
protected FileNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace ProjectElectroTrans.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,27 @@
using System.Runtime.Serialization;
[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

@ -1,6 +1,7 @@
using ProjectElectroTrans.CollectionGenericObjects; using ProjectElectroTrans.CollectionGenericObjects;
using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Drawnings;
using System.Windows.Forms; using Microsoft.Extensions.Logging;
using ProjectElectroTrans.Exceptions;
namespace ProjectElectroTrans; namespace ProjectElectroTrans;
@ -19,13 +20,19 @@ public partial class FormTransCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTransCollection() public FormTransCollection(ILogger<FormTransCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -62,15 +69,18 @@ public partial class FormTransCollection : Form
{ {
return; return;
} }
try
if (_company + drawingTrans != -1)
{ {
var res = _company + drawingTrans;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (Exception ex)
{ {
_ = MessageBox.Show(drawingTrans.ToString()); MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -93,14 +103,18 @@ public partial class FormTransCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null) try
{ {
var res = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -179,9 +193,19 @@ public partial class FormTransCollection : Form
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -203,6 +227,7 @@ public partial class FormTransCollection : Form
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -247,6 +272,7 @@ public partial class FormTransCollection : Form
{ {
case "Хранилище": case "Хранилище":
_company = new TransDepoService(pictureBox.Width, pictureBox.Height, collection); _company = new TransDepoService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break; break;
} }
@ -263,15 +289,19 @@ public partial class FormTransCollection : 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($"Ошибка: {ex.Message}", ex.Message);
} }
} }
} }
@ -285,16 +315,20 @@ public partial class FormTransCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загружено", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -43,7 +43,6 @@
panelRed = new Panel(); panelRed = new Panel();
checkBoxBulldozerDump = new CheckBox(); checkBoxBulldozerDump = new CheckBox();
checkBoxSupport = new CheckBox(); checkBoxSupport = new CheckBox();
checkBoxBucket = new CheckBox();
numericUpDownWeight = new NumericUpDown(); numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown(); numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label(); labelWeight = new Label();
@ -73,7 +72,6 @@
groupBoxConfig.Controls.Add(groupBoxColors); groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxBulldozerDump); groupBoxConfig.Controls.Add(checkBoxBulldozerDump);
groupBoxConfig.Controls.Add(checkBoxSupport); groupBoxConfig.Controls.Add(checkBoxSupport);
groupBoxConfig.Controls.Add(checkBoxBucket);
groupBoxConfig.Controls.Add(numericUpDownWeight); groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed); groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight); groupBoxConfig.Controls.Add(labelWeight);
@ -377,7 +375,6 @@
private Label labelSpeed; private Label labelSpeed;
private CheckBox checkBoxBulldozerDump; private CheckBox checkBoxBulldozerDump;
private CheckBox checkBoxSupport; private CheckBox checkBoxSupport;
private CheckBox checkBoxBucket;
private GroupBox groupBoxColors; private GroupBox groupBoxColors;
private Panel panelPurple; private Panel panelPurple;
private Panel panelYellow; private Panel panelYellow;

View File

@ -102,7 +102,7 @@ namespace ProjectElectroTrans
case "labelModifiedObject": case "labelModifiedObject":
_trans = new DrawingElectroTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, _trans = new DrawingElectroTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
Color.White, Color.White,
Color.Black, checkBoxBucket.Checked, Color.Black, checkBoxBulldozerDump.Checked,
checkBoxSupport.Checked); checkBoxSupport.Checked);
break; break;
} }

View File

@ -1,20 +1,45 @@
using System.Drawing; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectElectroTrans namespace ProjectElectroTrans
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// 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 FormTransCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTransCollection>());
} }
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTransCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
} }

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework> <TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
@ -23,4 +23,14 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0-preview.3.24172.9" />
<PackageReference Include="Serilog" Version="4.0.0-dev-02160" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10389" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1-dev-00582" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00972" />
</ItemGroup>
</Project> </Project>

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}"
}
}, {"Name": "Console"}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotives"
}
}
}