лабораторная 7

This commit is contained in:
SVETLANA_8 2024-05-21 19:34:17 +04:00
parent 787d8972d4
commit b116e7870c
15 changed files with 387 additions and 229 deletions

View File

@ -38,7 +38,8 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) -4 ;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -98,13 +99,19 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningTrackedCar? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningTrackedCar? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
} }
return bitmap; return bitmap;
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -43,7 +43,7 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T Get(int position);
/// <summary> /// <summary>
/// Получение типа коллекции /// Получение типа коллекции
/// </summary> /// </summary>

View File

@ -1,5 +1,7 @@
 
using ProjectByldozer.Exceptions;
namespace ProjectByldozer.CollectionGenericObjects; namespace ProjectByldozer.CollectionGenericObjects;
/// <summary> /// <summary>
@ -18,6 +20,7 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
/// Максимально допустимое число объектов в списке /// Максимально допустимое число объектов в списке
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public CollectionType GetCollectionType => CollectionType.List;
public int Count => _collection.Count; public int Count => _collection.Count;
@ -32,7 +35,6 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -44,27 +46,25 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции //TODO выброс ошибки если выход за границу
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)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO выброс ошибки если переполнение
// TODO вставка в конец набора if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) return -1;
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO выброс ошибки если переполнение
// TODO проверка позиции // TODO выброс ошибки если за границу
// TODO вставка по позиции if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -72,9 +72,8 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO если выброс за границу
// TODO удаление объекта из списка if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
@ -84,7 +83,7 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < _collection.Count; ++i) for (int i = 0; i < Count; ++i)
{ {
yield return _collection[i]; yield return _collection[i];
} }

View File

@ -1,4 +1,6 @@
namespace ProjectByldozer.CollectionGenericObjects; using ProjectByldozer.Exceptions;
namespace ProjectByldozer.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
@ -10,6 +12,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public CollectionType GetCollectionType => CollectionType.Massive;
public int Count => _collection.Length; public int Count => _collection.Length;
@ -35,7 +38,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -47,14 +49,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) // TODO выброс ошибки если объект пустой
{ return null; } if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO выброс ошибки если переполнение
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@ -65,52 +69,48 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
++index; ++index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если переполнение
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то // TODO выброс ошибки если выход за границу
// ищется свободное место после этой позиции и идет вставка туда if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
int index; int index = position + 1;
while (index < _collection.Length)
for (index = position + 1; index < _collection.Length; ++index)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
_collection[position] = obj; _collection[index] = obj;
return position; return index;
} }
++index;
} }
index = position - 1;
for (index = position - 1; index >= 0; --index) while (index >= 0)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
_collection[position] = obj; _collection[index] = obj;
return position; return index;
} }
--index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если выход за границу
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
{ return null; } if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;

View File

@ -1,6 +1,7 @@
 
using ProjectByldozer.Drawnings; using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
using System.Text; using System.Text;
namespace ProjectByldozer.CollectionGenericObjects; namespace ProjectByldozer.CollectionGenericObjects;
@ -99,11 +100,11 @@ public class StorageCollection<T>
/// </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))
{ {
@ -114,19 +115,17 @@ public class StorageCollection<T>
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); writer.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); writer.Write(value.Key);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); writer.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); writer.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;
@ -134,15 +133,11 @@ public class StorageCollection<T>
{ {
continue; continue;
} }
sb.Append(data); writer.Write(data);
sb.Append(_separatorItems); writer.Write(_separatorItems);
} }
writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -155,32 +150,28 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
//по идее этого произойти не должно
//if (strs == null)
//{
// return false;
//}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
@ -190,7 +181,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 Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -198,16 +189,21 @@ public class StorageCollection<T>
{ {
if (elem?.CreateDrawningTrackedCar() is T TrackedCar) if (elem?.CreateDrawningTrackedCar() is T TrackedCar)
{ {
if (collection.Insert(TrackedCar) == -1) try
{ {
return false; if (collection.Insert(TrackedCar) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }

View File

@ -1,5 +1,7 @@
 
using ProjectByldozer.Drawnings; using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
namespace ProjectByldozer.CollectionGenericObjects; namespace ProjectByldozer.CollectionGenericObjects;
public class TrackedCarGarage : AbstractCompany public class TrackedCarGarage : AbstractCompany
{ {
@ -35,29 +37,30 @@ public class TrackedCarGarage : AbstractCompany
int height = _pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1; int curWidth = width - 1;
int curHeight = height - 1; int curHeight = 0;
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 + 20, curHeight * _placeSizeHeight + 2); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4);
} }
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException) { }
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else
{ {
curWidth = width - 1; curWidth = width - 1;
curHeight--; curHeight++;
} }
if (curHeight > height)
if (curHeight < 0)
{ {
return; return;
} }
} }
} }

View File

@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace ProjectByldozer.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException: ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectByldozer.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[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 exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectByldozer.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
public 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

@ -29,6 +29,12 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddTrackedCar = new Button();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
maskedTextBox = new MaskedTextBox();
buttonDelCar = new Button();
comboBoxSelectionCompany = new ComboBox(); comboBoxSelectionCompany = new ComboBox();
buttonCreateCompany = new Button(); buttonCreateCompany = new Button();
panelStorage = new Panel(); panelStorage = new Panel();
@ -39,13 +45,7 @@
radioButtonMassiv = new RadioButton(); radioButtonMassiv = new RadioButton();
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonDelCar = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddTrackedCar = new Button();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
panelCompanyTools = new Panel();
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem(); файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem(); saveToolStripMenuItem = new ToolStripMenuItem();
@ -53,9 +53,9 @@
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
@ -68,11 +68,77 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(778, 24); groupBoxTools.Location = new Point(778, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(209, 472); groupBoxTools.Size = new Size(209, 494);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddTrackedCar);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelCar);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 293);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(208, 176);
panelCompanyTools.TabIndex = 9;
//
// buttonAddTrackedCar
//
buttonAddTrackedCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrackedCar.Location = new Point(3, 17);
buttonAddTrackedCar.Name = "buttonAddTrackedCar";
buttonAddTrackedCar.Size = new Size(205, 31);
buttonAddTrackedCar.TabIndex = 1;
buttonAddTrackedCar.Text = "Добавление машины";
buttonAddTrackedCar.UseVisualStyleBackColor = true;
buttonAddTrackedCar.Click += ButtonAddTrackedCar_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(2, 144);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(208, 25);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 112);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(205, 26);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(6, 54);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(205, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonDelCar
//
buttonDelCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelCar.Location = new Point(3, 83);
buttonDelCar.Name = "buttonDelCar";
buttonDelCar.Size = new Size(205, 23);
buttonDelCar.TabIndex = 4;
buttonDelCar.Text = "Удаление машины";
buttonDelCar.UseVisualStyleBackColor = true;
buttonDelCar.Click += ButtonDelCar_Click;
//
// comboBoxSelectionCompany // comboBoxSelectionCompany
// //
comboBoxSelectionCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectionCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -177,81 +243,15 @@
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции"; labelCollectionName.Text = "Название коллекции";
// //
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(2, 144);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(208, 25);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 112);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(205, 26);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonDelCar
//
buttonDelCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelCar.Location = new Point(3, 83);
buttonDelCar.Name = "buttonDelCar";
buttonDelCar.Size = new Size(205, 23);
buttonDelCar.TabIndex = 4;
buttonDelCar.Text = "Удаление машины";
buttonDelCar.UseVisualStyleBackColor = true;
buttonDelCar.Click += ButtonDelCar_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(6, 54);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(205, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonAddTrackedCar
//
buttonAddTrackedCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrackedCar.Location = new Point(3, 17);
buttonAddTrackedCar.Name = "buttonAddTrackedCar";
buttonAddTrackedCar.Size = new Size(205, 31);
buttonAddTrackedCar.TabIndex = 1;
buttonAddTrackedCar.Text = "Добавление машины";
buttonAddTrackedCar.UseVisualStyleBackColor = true;
buttonAddTrackedCar.Click += ButtonAddTrackedCar_Click;
//
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(778, 472); pictureBox.Size = new Size(778, 494);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddTrackedCar);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelCar);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 293);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(208, 176);
panelCompanyTools.TabIndex = 9;
//
// menuStrip // menuStrip
// //
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
@ -296,7 +296,7 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(987, 496); ClientSize = new Size(987, 518);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -304,11 +304,11 @@
Name = "FormCarCollection"; Name = "FormCarCollection";
Text = "коллекция бульдозеров"; Text = "коллекция бульдозеров";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
menuStrip.ResumeLayout(false); menuStrip.ResumeLayout(false);
menuStrip.PerformLayout(); menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);

View File

@ -1,6 +1,7 @@
using ProjectByldozer.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectByldozer.CollectionGenericObjects;
using ProjectByldozer.Drawnings; using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
namespace ProjectByldozer; namespace ProjectByldozer;
/// <summary> /// <summary>
@ -9,23 +10,24 @@ namespace ProjectByldozer;
public partial class FormCarCollection : Form public partial class FormCarCollection : Form
{ {
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningTrackedCar> _storageCollection;
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary> /// <summary>
/// Конструктор /// Хранилище коллекций
/// </summary> /// </summary>
public FormCarCollection() private readonly StorageCollection<DrawningTrackedCar> _storageCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormCarCollection(ILogger<FormCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -33,19 +35,14 @@ public partial class FormCarCollection : Form
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
/// /// Добавление машины /// /// Добавление машины
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddTrackedCar_Click(object sender, EventArgs e) private void ButtonAddTrackedCar_Click(object sender, EventArgs e)
{ {
FormCarConfig form = new(); FormCarConfig form = new();
// TODO передать метод // TODO передать метод
form.Show(); form.Show();
form.AddEvent(SetTrackedCar); form.AddEvent(SetTrackedCar);
@ -56,22 +53,36 @@ public partial class FormCarCollection : Form
/// <param name=" Trackedcar"></param> /// <param name=" Trackedcar"></param>
private void SetTrackedCar(DrawningTrackedCar? Trackedcar) private void SetTrackedCar(DrawningTrackedCar? Trackedcar)
{ {
if (_company == null || Trackedcar == null)
{ {
return; try
} {
if (_company + Trackedcar != -1) if (_company == null || Trackedcar == null)
{ {
MessageBox.Show("Объект добавлен"); return;
pictureBox.Image = _company.Show(); }
} if (_company + Trackedcar != -1)
else {
{ MessageBox.Show("Объект добавлен");
MessageBox.Show("Не удалось добавить объект"); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + Trackedcar.GetDataForSave());
}
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
} }
private void ButtonDelCar_Click(object sender, EventArgs e) private void ButtonDelCar_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
@ -79,20 +90,25 @@ public partial class FormCarCollection : Form
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -106,25 +122,27 @@ public partial class FormCarCollection : Form
DrawningTrackedCar? trackedcar = null; DrawningTrackedCar? trackedcar = null;
int counter = 100; int counter = 100;
while (trackedcar == null) try
{ {
trackedcar = _company.GetRandomObject(); while (trackedcar == null)
counter--;
if (counter <= 0)
{ {
break; trackedcar = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
} }
FormByldozer form = new()
{
SetTrackedCar = trackedcar
};
form.ShowDialog();
} }
catch (Exception ex)
if (trackedcar == null)
{ {
return; MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
FormByldozer form = new()
{
SetTrackedCar = trackedcar
};
form.ShowDialog();
} }
@ -150,17 +168,25 @@ public partial class FormCarCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; try
if (radioButtonMassiv.Checked)
{ {
collectionType = CollectionType.Massive; CollectionType collectionType = CollectionType.None;
if (radioButtonMassiv.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
} }
else if (radioButtonList.Checked) catch (Exception ex)
{ {
collectionType = CollectionType.List; _logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
@ -187,12 +213,20 @@ public partial class FormCarCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) try
{ {
return; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// ///
@ -228,13 +262,16 @@ public partial class FormCarCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -244,14 +281,17 @@ public partial class FormCarCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -48,7 +48,7 @@ public partial class FormCarConfig : Form
// TODO отправка цвета в Drag&Drop // TODO отправка цвета в Drag&Drop
} }
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void labelBodyColor_DragEnter(object sender, DragEventArgs e) private void labelBodyColor_DragEnter(object sender, DragEventArgs e)

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectByldozer namespace ProjectByldozer
{ {
internal static class Program internal static class Program
@ -12,7 +18,30 @@ namespace ProjectByldozer
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCarCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormCarCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormCarCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
} }
} }
} }

View File

@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +35,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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