This commit is contained in:
PIBD14CHERTOVANDREY 2024-06-16 21:08:24 +04:00
parent 0628d80e97
commit 6fa14836d1
20 changed files with 656 additions and 456 deletions

View File

@ -1,12 +1,13 @@
using Microsoft.VisualBasic;
using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectRoadTrain.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
@ -41,7 +42,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@ -63,9 +64,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrain trains)
public static int operator +(AbstractCompany company, DrawningTrain train)
{
return company._collection.Insert(trains);
return company._collection.Insert(train);
}
/// <summary>
@ -78,9 +79,6 @@ public abstract class AbstractCompany
{
return company._collection?.Remove(position);
}
public static bool operator <(AbstractCompany company1, AbstractCompany company2) => company1._collection.Count < company2._collection.Count;
public static bool operator >(AbstractCompany company1, AbstractCompany company2) => company1._collection.Count > company2._collection.Count;
/// <summary>
@ -106,8 +104,19 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
}
return bitmap;

View File

@ -1,11 +1,12 @@
using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectroTrans.CollectionGenericObjects;
namespace ProjectRoadTrain.CollectionGenericObjects;
public class AutoParkService : AbstractCompany
@ -43,13 +44,25 @@ public class AutoParkService : AbstractCompany
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningTrain? drawningTrain = _collection?.Get(n);
n++;
if (drawningTrain != null)
try
{
drawningTrain.SetPictureSize(_pictureWidth, _pictureHeight);
drawningTrain.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
DrawningTrain? drawingTrans = _collection?.Get(n);
if (drawingTrans != null)
{
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
// Relax Man ;)
}
catch (PositionOutOfCollectionException e)
{
// Relax Man ;)
}
n++;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectRoadTrain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -21,10 +22,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int MaxCount
{
get
{
return Count;
}
get { return Count; }
set
{
if (value > 0)
@ -44,22 +42,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
if (position < 0 || position > _collection.Count - 1)
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (_collection.Count + 1 > _maxCount) { return 0; }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return 1;
return Count;
}
public IEnumerable<T?> GetItems()
{
@ -70,23 +63,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj, int position)
{
if (_collection.Count + 1 < _maxCount) { return 0; }
if (position > _collection.Count || position < 0)
{
return 0;
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T Remove(int position)
{
if (position > _collection.Count || position < 0)
{
return null;
}
T temp = _collection[position];
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return temp;
return obj;
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectRoadTrain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -45,16 +46,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -64,17 +63,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position < 0 || position >= Count)
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
{
bool pushed = false;
@ -103,20 +102,26 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (!pushed)
{
return position;
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
if (position >= Count || position < 0) return null;
T? myObject = _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;
return myObject;
return temp;
}
public IEnumerable<T?> GetItems()
{

View File

@ -1,5 +1,6 @@
using ProjectRoadTrain.CollectionGenericObjects;
using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -22,18 +23,18 @@ public class StorageCollection<T>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name);
if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции");
if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
public ICollectionGenericObjects<T>? this[string name]
@ -58,7 +59,7 @@ public class StorageCollection<T>
{
if (_storages.Count == 0)
{
return false;
throw new EmptyFileExeption();
}
if (File.Exists(filename))
@ -119,14 +120,17 @@ public class StorageCollection<T>
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
if (string.IsNullOrEmpty(str))
{
return false;
throw new FileNotFoundException(filename);
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new FileFormatException(filename);
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
@ -136,29 +140,37 @@ public class StorageCollection<T>
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateTrain() is T machine)
if (elem?.CreateTrain() is T ship)
{
if (collection.Insert(machine) == -1)
try
{
return false;
collection.Insert(ship);
}
catch (Exception ex)
{
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
return true;
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
[Serializable]
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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое кол-во: count " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception innerException) : base(message, innerException) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
[Serializable]
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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
[Serializable]
public class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception innerException) : base(message, innerException) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

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

View File

@ -48,10 +48,17 @@ namespace ProjectRoadTrain
labelCollectionName = new Label();
comboBoxSelectCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -61,63 +68,12 @@ namespace ProjectRoadTrain
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(820, 0);
groupBoxTools.Location = new Point(952, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(218, 780);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
// menuStrip
//
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
PerformLayout();
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(980, 28);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// panelCompanyTools
//
@ -295,17 +251,60 @@ namespace ProjectRoadTrain
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(820, 780);
pictureBox.Size = new Size(952, 780);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(952, 28);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormTrainCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1038, 780);
ClientSize = new Size(1170, 780);
Controls.Add(menuStrip);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
MainMenuStrip = menuStrip;
Name = "FormTrainCollection";
Text = "Коллекция камазов";
groupBoxTools.ResumeLayout(false);
@ -314,7 +313,10 @@ namespace ProjectRoadTrain
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion

View File

@ -1,7 +1,8 @@
using ProjectElectroTrans.CollectionGenericObjects;
using ProjectRoadTrain.CollectionGenericObjects;
using ProjectRoadTrain.CollectionGenericObjects;
using ProjectRoadTrain.Drawnings;
using System;
using Microsoft.Extensions.Logging;
using ProjectRoadTrain.Exceptions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -11,331 +12,298 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectRoadTrain
namespace ProjectRoadTrain;
public partial class FormTrainCollection : Form
{
public partial class FormTrainCollection : Form
private readonly StorageCollection<DrawningTrain> _storageCollection;
private AbstractCompany? _company = null;
private readonly ILogger _logger;
public FormTrainCollection(ILogger<FormTrainCollection> logger)
{
private readonly StorageCollection<DrawningTrain> _storageCollection;
private AbstractCompany? _company = null;
public FormTrainCollection()
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
InitializeComponent();
_storageCollection = new();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
listBoxCollection.Items.Add(colName);
}
}
private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectCompany.Text)
{
case "Хранилище":
_company = new AutoParkService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTrain>());
break;
}
}
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
FormTrainConfig form = new();
form.Show();
form.AddEvent(SetTrains);
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTrans_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningTrain? train = null;
int counter = 100;
while (train == null)
{
train = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (train == null)
{
return;
}
FormRoadTrain form = new()
{
SetTrain = train
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningTrain drawningTrain;
switch (type)
{
case nameof(DrawningTrain):
drawningTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningRoadTrain):
// вызов диалогового окна для выбора цвета
drawningTrain = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTrain != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
_ = MessageBox.Show(drawningTrain.ToString());
}
}
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void SetTrains(DrawningTrain? drawningTrain)
{
if (_company == null || drawningTrain == null)
{
return;
}
if (_company + drawningTrain != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
_ = MessageBox.Show(drawningTrain.ToString());
}
}
private void ButtonDelTrain_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectCompany.Text)
{
case "хранилище":
_company = new AutoParkService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
}
private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectCompany.Text)
{
case "Хранилище":
_company = new AutoParkService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTrain>());
break;
}
}
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
FormTrainConfig form = new();
form.Show();
form.AddEvent(SetTrains);
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningTrain? car = null;
int counter = 100;
while (car == null)
{
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (car == null)
{
return;
}
FormRoadTrain form = new()
{
SetTrain = car
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void SetTrains(DrawningTrain? drawningTrain)
{
if (_company == null || drawningTrain == null)
{
return;
}
try
{
var res = _company + drawningTrain;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonDelTrain_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
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($"Ошибка: {ex.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);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTrain>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectCompany.Text)
{
case "хранилище":
_company = new AutoParkService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>302, 17</value>
</metadata>
</root>

View File

@ -18,7 +18,7 @@ public partial class FormTrainConfig : Form
private DrawningTrain? _train;
private event TrainDelegate? TrainDelegate;
private event Action<DrawningTrain>? RoadTrainDelegate;
public FormTrainConfig()
{
InitializeComponent();
@ -87,9 +87,9 @@ public partial class FormTrainConfig : Form
e.Effect = DragDropEffects.None;
}
}
public void AddEvent(TrainDelegate trainDelegate)
public void AddEvent(Action<DrawningTrain> trainDelegate)
{
TrainDelegate += trainDelegate;
RoadTrainDelegate += trainDelegate;
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
@ -124,7 +124,7 @@ public partial class FormTrainConfig : Form
{
if (_train != null)
{
TrainDelegate?.Invoke(_train);
RoadTrainDelegate?.Invoke(_train);
Close();
}
}

View File

@ -1,17 +1,36 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using NLog.Extensions.Logging;
namespace ProjectRoadTrain
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTrainCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTrainCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="4.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,15 @@
<?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="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}