This commit is contained in:
Максим 2024-08-29 02:16:35 +04:00
parent 6871b197bf
commit e9955216f8
17 changed files with 485 additions and 159 deletions

View File

@ -1,4 +1,5 @@
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -35,7 +36,7 @@ namespace ProjectTrain.CollectionGenericObjects
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -95,10 +96,17 @@ namespace ProjectTrain.CollectionGenericObjects
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
{ {
DrawningTrain? obj = _collection?.Get(i); DrawningTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap; return bitmap;
} }
/// <summary> /// <summary>

View File

@ -1,4 +1,6 @@
namespace ProjectTrain.CollectionGenericObjects using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects
{ {
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -40,15 +42,17 @@
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= Count || position < 0) return null; // TODO выброc позиций, если выход за границы массива
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)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO вставка в конец набора // TODO вставка в конец набора
if (Count == _maxCount) return -1; if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
@ -58,8 +62,8 @@
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции // TODO проверка позиции
// TODO вставка по позиции // TODO вставка по позиции
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;
@ -69,7 +73,8 @@
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из списка // TODO удаление объекта из списка
if (position >= Count || position < 0) return null; // TODO выбром позиций, если выход за границы массива
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,5 +1,5 @@
using ProjectTrain.Drawnings; using ProjectTrain.Exceptions;
using ProjectTrain.CollectionGenericObjects;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -48,26 +48,30 @@ namespace ProjectTrain.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если выход за границы массива
{ return null; } // TODO выбром позиций, если объект пустой
if (position < 0 || position >= Count) 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)
{ {
// TODO вставка в свободное место набора // TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
int index = 0; int index = 0;
while (index < _collection.Length) while (index < Count && _collection[index] != null)
{ {
if (_collection[index] == null) index++;
}
if (index < Count)
{ {
_collection[index] = obj; _collection[index] = obj;
return index; return index;
} }
index++; throw new CollectionOverflowException(Count);
}
return -1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
@ -77,45 +81,59 @@ namespace ProjectTrain.CollectionGenericObjects
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
// TODO вставка // TODO вставка
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если переполнение
{ return -1; } // TODO выбром позиций, если выход за границы массива
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] != null)
{ {
_collection[position] = obj; bool pushed = false;
return position; for (int index = position + 1; index < Count; index++)
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
_collection[position] = obj; position = index;
return position; pushed = true;
break;
} }
} }
for (index = position - 1; index >= 0; --index) if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
}
return -1;
}
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0) // TODO выбром позиций, если выход за границы массива
{ return null; } // TODO выбром позиций, если объект пустой
T obj = _collection[position]; if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectTrain.Drawnings; using ProjectTrain.Exceptions;
using ProjectTrain.Drawnings;
using System.Text; using System.Text;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
@ -92,35 +93,40 @@ namespace ProjectTrain.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using (StreamWriter writer = new StreamWriter(filename))
{ using FileStream fs = new(filename, FileMode.Create);
writer.Write(_collectionKey); using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); streamWriter.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); streamWriter.Write(value.Key);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); streamWriter.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); streamWriter.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -128,42 +134,35 @@ namespace ProjectTrain.CollectionGenericObjects
{ {
continue; continue;
} }
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
}
/// <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 (StreamReader fs = File.OpenText(filename))
using (StreamReader sr = new StreamReader(filename))
{ {
string str = fs.ReadLine(); string? str;
if (str == null || str.Length == 0) str = sr.ReadLine();
{ if (str != _collectionKey.ToString())
return false; throw new FormatException("В файле неверные данные");
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear(); _storages.Clear();
string strs = ""; while ((str = sr.ReadLine()) != null)
while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 4)
{ {
continue; continue;
@ -172,24 +171,31 @@ namespace ProjectTrain.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
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?.CreateDrawningTrain() is T train) if (elem?.CreateDrawningTrain() is T aircraft)
{ {
if (collection.Insert(train) == -1) try
{ {
return false; if (collection.Insert(aircraft) == -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;
} }
} }
@ -207,6 +213,5 @@ namespace ProjectTrain.CollectionGenericObjects
_ => null, _ => null,
}; };
} }
} }
} }

View File

@ -1,4 +1,5 @@
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -41,11 +42,14 @@ namespace ProjectTrain.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null)
try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
} }
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth < width - 1) if (curWidth < width - 1)
curWidth++; curWidth++;

View 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 ProjectTrain.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) { }
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.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) { }
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -30,7 +30,6 @@
{ {
groupBoxConfing = new GroupBox(); groupBoxConfing = new GroupBox();
groupBoxColors = new GroupBox(); groupBoxColors = new GroupBox();
pictureBox1 = new PictureBox();
panelPurple = new Panel(); panelPurple = new Panel();
panelBlack = new Panel(); panelBlack = new Panel();
panelGray = new Panel(); panelGray = new Panel();
@ -56,7 +55,6 @@
labelBodyColor = new Label(); labelBodyColor = new Label();
groupBoxConfing.SuspendLayout(); groupBoxConfing.SuspendLayout();
groupBoxColors.SuspendLayout(); groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
@ -87,7 +85,6 @@
// //
// groupBoxColors // groupBoxColors
// //
groupBoxColors.Controls.Add(pictureBox1);
groupBoxColors.Controls.Add(panelPurple); groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack); groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray); groupBoxColors.Controls.Add(panelGray);
@ -105,14 +102,6 @@
groupBoxColors.TabStop = false; groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета"; groupBoxColors.Text = "Цвета";
// //
// pictureBox1
//
pictureBox1.Location = new Point(188, 18);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(100, 50);
pictureBox1.TabIndex = 2;
pictureBox1.TabStop = false;
//
// panelPurple // panelPurple
// //
panelPurple.BackColor = Color.Purple; panelPurple.BackColor = Color.Purple;
@ -195,7 +184,6 @@
checkBoxHeadlight.TabIndex = 8; checkBoxHeadlight.TabIndex = 8;
checkBoxHeadlight.Text = "Признак наличие фонаря"; checkBoxHeadlight.Text = "Признак наличие фонаря";
checkBoxHeadlight.UseVisualStyleBackColor = true; checkBoxHeadlight.UseVisualStyleBackColor = true;
checkBoxHeadlight.CheckedChanged += checkBoxHeadlight_CheckedChanged;
// //
// checkBoxElectro // checkBoxElectro
// //
@ -270,6 +258,7 @@
labelModifiedObject.TabIndex = 1; labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый"; labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter; labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.Click += labelModifiedObject_Click;
labelModifiedObject.MouseDown += labelObject_MouseDown; labelModifiedObject.MouseDown += labelObject_MouseDown;
// //
// labelSimpleObject // labelSimpleObject
@ -365,11 +354,9 @@
Margin = new Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainConfing"; Name = "FormTrainConfing";
Text = "Создание объекта"; Text = "Создание объекта";
Load += FormTrainConfing_Load;
groupBoxConfing.ResumeLayout(false); groupBoxConfing.ResumeLayout(false);
groupBoxConfing.PerformLayout(); groupBoxConfing.PerformLayout();
groupBoxColors.ResumeLayout(false); groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
@ -404,6 +391,5 @@
private Panel panelObject; private Panel panelObject;
private Label labelBodyColor; private Label labelBodyColor;
private Label labelAdditionalColor; private Label labelAdditionalColor;
private PictureBox pictureBox1;
} }
} }

View File

@ -62,8 +62,8 @@ namespace ProjectTrain
/// <summary> /// <summary>
/// Передаем информацию при нажатии на Label /// Передаем информацию при нажатии на Label
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>labelSimpleObject
/// <param name="e"></param> /// <param name="e"></param>labelSimpleObject
private void labelObject_MouseDown(object sender, MouseEventArgs e) private void labelObject_MouseDown(object sender, MouseEventArgs e)
{ {
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy); (sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
@ -152,9 +152,9 @@ namespace ProjectTrain
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e) private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{ {
if (_train.EntityTrain is EntityElectroTrain electroTrain) if (_train.EntityTrain is EntityElectroTrain militaryTrain)
{ {
electroTrain.setAdditionalColor((Color)e.Data.GetData(typeof(Color))); militaryTrain.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
} }
DrawObject(); DrawObject();
} }
@ -171,12 +171,6 @@ namespace ProjectTrain
TrainDelegate?.Invoke(_train); TrainDelegate?.Invoke(_train);
Close(); Close();
} }
}
private void checkBoxHorns_CheckedChanged(object sender, EventArgs e)
{
} }
private void checkBoxElectro_CheckedChanged(object sender, EventArgs e) private void checkBoxElectro_CheckedChanged(object sender, EventArgs e)
@ -184,12 +178,12 @@ namespace ProjectTrain
} }
private void FormTrainConfing_Load(object sender, EventArgs e) private void labelModifiedObject_Click(object sender, EventArgs e)
{ {
} }
private void checkBoxHeadlight_CheckedChanged(object sender, EventArgs e) private void checkBoxHorns_CheckedChanged(object sender, EventArgs e)
{ {
} }

View File

@ -46,10 +46,17 @@
maskedTextBoxPosision = new MaskedTextBox(); maskedTextBoxPosision = new MaskedTextBox();
buttonGetToTest = new Button(); buttonGetToTest = new Button();
pictureBoxTrain = new PictureBox(); pictureBoxTrain = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -59,11 +66,11 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(522, 0); groupBoxTools.Location = new Point(552, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2); groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2); groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(182, 490); groupBoxTools.Size = new Size(194, 485);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты"; groupBoxTools.Text = "инструменты";
@ -92,7 +99,7 @@
panelStorage.Location = new Point(3, 18); panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2); panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(176, 212); panelStorage.Size = new Size(188, 212);
panelStorage.TabIndex = 6; panelStorage.TabIndex = 6;
// //
// buttonCollectionDel // buttonCollectionDel
@ -201,7 +208,7 @@
ButtonAddTrain.Location = new Point(16, 2); ButtonAddTrain.Location = new Point(16, 2);
ButtonAddTrain.Margin = new Padding(3, 2, 3, 2); ButtonAddTrain.Margin = new Padding(3, 2, 3, 2);
ButtonAddTrain.Name = "ButtonAddTrain"; ButtonAddTrain.Name = "ButtonAddTrain";
ButtonAddTrain.Size = new Size(163, 55); ButtonAddTrain.Size = new Size(163, 30);
ButtonAddTrain.TabIndex = 1; ButtonAddTrain.TabIndex = 1;
ButtonAddTrain.Text = "добваление поезда"; ButtonAddTrain.Text = "добваление поезда";
ButtonAddTrain.UseVisualStyleBackColor = true; ButtonAddTrain.UseVisualStyleBackColor = true;
@ -222,10 +229,10 @@
// ButtonRemoveTrain // ButtonRemoveTrain
// //
ButtonRemoveTrain.Anchor = AnchorStyles.Right; ButtonRemoveTrain.Anchor = AnchorStyles.Right;
ButtonRemoveTrain.Location = new Point(16, 88); ButtonRemoveTrain.Location = new Point(16, 104);
ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2); ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveTrain.Name = "ButtonRemoveTrain"; ButtonRemoveTrain.Name = "ButtonRemoveTrain";
ButtonRemoveTrain.Size = new Size(163, 46); ButtonRemoveTrain.Size = new Size(163, 30);
ButtonRemoveTrain.TabIndex = 3; ButtonRemoveTrain.TabIndex = 3;
ButtonRemoveTrain.Text = "удалить поезд"; ButtonRemoveTrain.Text = "удалить поезд";
ButtonRemoveTrain.UseVisualStyleBackColor = true; ButtonRemoveTrain.UseVisualStyleBackColor = true;
@ -233,7 +240,7 @@
// //
// maskedTextBoxPosision // maskedTextBoxPosision
// //
maskedTextBoxPosision.Location = new Point(16, 61); maskedTextBoxPosision.Location = new Point(15, 79);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2); maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision"; maskedTextBoxPosision.Name = "maskedTextBoxPosision";
@ -256,20 +263,65 @@
// pictureBoxTrain // pictureBoxTrain
// //
pictureBoxTrain.Dock = DockStyle.Fill; pictureBoxTrain.Dock = DockStyle.Fill;
pictureBoxTrain.Location = new Point(0, 0); pictureBoxTrain.Location = new Point(0, 24);
pictureBoxTrain.Margin = new Padding(3, 2, 3, 2); pictureBoxTrain.Margin = new Padding(3, 2, 3, 2);
pictureBoxTrain.Name = "pictureBoxTrain"; pictureBoxTrain.Name = "pictureBoxTrain";
pictureBoxTrain.Size = new Size(522, 490); pictureBoxTrain.Size = new Size(552, 485);
pictureBoxTrain.TabIndex = 1; pictureBoxTrain.TabIndex = 1;
pictureBoxTrain.TabStop = false; pictureBoxTrain.TabStop = false;
pictureBoxTrain.Click += pictureBoxTrain_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(746, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
// //
// FormTrainsCollection // FormTrainsCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(704, 490); ClientSize = new Size(746, 509);
Controls.Add(pictureBoxTrain); Controls.Add(pictureBoxTrain);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainsCollection"; Name = "FormTrainsCollection";
Text = "FormTrainsCollection"; Text = "FormTrainsCollection";
@ -279,7 +331,10 @@
panelCompanyTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout(); panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -302,5 +357,11 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@ -1,6 +1,6 @@
using ProjectTrain.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using System.Windows.Forms;
namespace ProjectTrain namespace ProjectTrain
{ {
@ -16,13 +16,19 @@ namespace ProjectTrain
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTrainsCollection() public FormTrainsCollection(ILogger<FormTrainsCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -35,6 +41,11 @@ namespace ProjectTrain
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
/// <summary>
/// добавление артиллерийской установки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrain_Click(object sender, EventArgs e) private void ButtonAddTrain_Click(object sender, EventArgs e)
{ {
FormTrainConfing form = new(); FormTrainConfing form = new();
@ -48,21 +59,24 @@ namespace ProjectTrain
/// Добавление артиллерийской установки в коллекцию /// Добавление артиллерийской установки в коллекцию
/// </summary> /// </summary>
/// <param name="train"></param> /// <param name="train"></param>
private void SetTrain(DrawningTrain train) private void SetTrain(DrawningTrain? train)
{ {
if (_company == null || train == null) if (_company == null || train == null)
{ {
return; return;
} }
try
if (_company + train != -1)
{ {
var res = _company + train;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxTrain.Image = _company.Show(); pictureBoxTrain.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -83,14 +97,18 @@ namespace ProjectTrain
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosision.Text); int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("объект удален"); var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxTrain.Image = _company.Show(); pictureBoxTrain.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("не удалось удалить объект"); MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -143,8 +161,7 @@ namespace ProjectTrain
{ {
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;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -156,9 +173,19 @@ namespace ProjectTrain
{ {
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>
/// Удаленние коллекции /// Удаленние коллекции
@ -177,6 +204,7 @@ namespace ProjectTrain
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -197,7 +225,7 @@ namespace ProjectTrain
} }
/// <summary> /// <summary>
/// /// Создание компании
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
@ -208,6 +236,7 @@ namespace ProjectTrain
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningTrain>? collection = ICollectionGenericObjects<DrawningTrain>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
@ -215,16 +244,68 @@ namespace ProjectTrain
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new TrainDockingService(pictureBoxTrain.Width, pictureBoxTrain.Height, collection); _company = new TrainDockingService(pictureBoxTrain.Width, pictureBoxTrain.Height, collection);
_logger.LogInformation("Компания создана");
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void pictureBoxTrain_Click(object sender, EventArgs e)
{
} }
} }
}

View File

@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 1</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 1</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 1</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectTrain namespace ProjectTrain
{ {
internal static class Program internal static class Program
@ -10,7 +15,31 @@ namespace ProjectTrain
{ {
// To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration. // To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTrainsCollection()); ServiceCollection services = new();
} ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTrainsCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTrainsCollection>().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

@ -8,4 +8,15 @@
<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.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.12" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="trainlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

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