лабораторная 7
This commit is contained in:
parent
787d8972d4
commit
b116e7870c
@ -38,7 +38,8 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) -4 ;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -97,14 +98,20 @@ public abstract class AbstractCompany
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawningTrackedCar? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
|
@ -43,7 +43,7 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
T Get(int position);
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
|
@ -1,5 +1,7 @@
|
||||
|
||||
|
||||
using ProjectByldozer.Exceptions;
|
||||
|
||||
namespace ProjectByldozer.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -18,6 +20,7 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
@ -32,7 +35,6 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -44,27 +46,25 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0) return null;
|
||||
//TODO выброс ошибки если выход за границу
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
if (Count == _maxCount) return -1;
|
||||
// TODO выброс ошибки если переполнение
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (Count == _maxCount) return -1;
|
||||
if (position >= Count || position < 0) return -1;
|
||||
// TODO выброс ошибки если переполнение
|
||||
// TODO выброс ошибки если за границу
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
|
||||
@ -72,9 +72,8 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
if (position >= Count || position < 0) return null;
|
||||
// TODO если выброс за границу
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
@ -84,7 +83,7 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
for (int i = 0; i < Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
namespace ProjectByldozer.CollectionGenericObjects;
|
||||
using ProjectByldozer.Exceptions;
|
||||
|
||||
namespace ProjectByldozer.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
@ -10,6 +12,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
@ -35,7 +38,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -47,14 +49,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return null; }
|
||||
// TODO выброс ошибки если выход за границу
|
||||
// TODO выброс ошибки если объект пустой
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO выброс ошибки если переполнение
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
@ -65,52 +69,48 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
++index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return -1; }
|
||||
|
||||
// TODO выброс ошибки если переполнение
|
||||
// TODO выброс ошибки если выход за границу
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index;
|
||||
|
||||
for (index = position + 1; index < _collection.Length; ++index)
|
||||
int index = position + 1;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
++index;
|
||||
}
|
||||
|
||||
for (index = position - 1; index >= 0; --index)
|
||||
index = position - 1;
|
||||
while (index >= 0)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
--index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return null; }
|
||||
// TODO выброс ошибки если выход за границу
|
||||
// TODO выброс ошибки если объект пустой
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
|
@ -1,6 +1,7 @@
|
||||
|
||||
|
||||
using ProjectByldozer.Drawnings;
|
||||
using ProjectByldozer.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectByldozer.CollectionGenericObjects;
|
||||
@ -99,11 +100,11 @@ public class StorageCollection<T>
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -114,19 +115,17 @@ public class StorageCollection<T>
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
writer.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.GetCollectionType);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
@ -134,15 +133,11 @@ public class StorageCollection<T>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
writer.Write(data);
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
writer.Write(sb);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -155,32 +150,28 @@ public class StorageCollection<T>
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
//по идее этого произойти не должно
|
||||
//if (strs == null)
|
||||
//{
|
||||
// return false;
|
||||
//}
|
||||
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
@ -190,24 +181,29 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTrackedCar() is T TrackedCar)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(TrackedCar) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,7 @@
|
||||
|
||||
using ProjectByldozer.Drawnings;
|
||||
using ProjectByldozer.Exceptions;
|
||||
|
||||
namespace ProjectByldozer.CollectionGenericObjects;
|
||||
public class TrackedCarGarage : AbstractCompany
|
||||
{
|
||||
@ -35,29 +37,30 @@ public class TrackedCarGarage : AbstractCompany
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = height - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
try
|
||||
{
|
||||
_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)
|
||||
curWidth--;
|
||||
else
|
||||
{
|
||||
curWidth = width - 1;
|
||||
curHeight--;
|
||||
curHeight++;
|
||||
}
|
||||
|
||||
if (curHeight < 0)
|
||||
if (curHeight > height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -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) { }
|
||||
|
||||
}
|
||||
|
@ -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) { }
|
||||
}
|
||||
|
@ -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) { }
|
||||
}
|
@ -29,6 +29,12 @@
|
||||
private void InitializeComponent()
|
||||
{
|
||||
groupBoxTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonAddTrackedCar = new Button();
|
||||
buttonRefresh = new Button();
|
||||
buttonGoToCheck = new Button();
|
||||
maskedTextBox = new MaskedTextBox();
|
||||
buttonDelCar = new Button();
|
||||
comboBoxSelectionCompany = new ComboBox();
|
||||
buttonCreateCompany = new Button();
|
||||
panelStorage = new Panel();
|
||||
@ -39,13 +45,7 @@
|
||||
radioButtonMassiv = new RadioButton();
|
||||
textBoxCollectionName = new TextBox();
|
||||
labelCollectionName = new Label();
|
||||
buttonRefresh = new Button();
|
||||
buttonGoToCheck = new Button();
|
||||
buttonDelCar = new Button();
|
||||
maskedTextBox = new MaskedTextBox();
|
||||
buttonAddTrackedCar = new Button();
|
||||
pictureBox = new PictureBox();
|
||||
panelCompanyTools = new Panel();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
@ -53,9 +53,9 @@
|
||||
openFileDialog = new OpenFileDialog();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
@ -68,11 +68,77 @@
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(778, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(209, 472);
|
||||
groupBoxTools.Size = new Size(209, 494);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
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.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
@ -177,81 +243,15 @@
|
||||
labelCollectionName.TabIndex = 0;
|
||||
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.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(778, 472);
|
||||
pictureBox.Size = new Size(778, 494);
|
||||
pictureBox.TabIndex = 1;
|
||||
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.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
@ -296,7 +296,7 @@
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(987, 496);
|
||||
ClientSize = new Size(987, 518);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
@ -304,11 +304,11 @@
|
||||
Name = "FormCarCollection";
|
||||
Text = "коллекция бульдозеров";
|
||||
groupBoxTools.ResumeLayout(false);
|
||||
panelCompanyTools.ResumeLayout(false);
|
||||
panelCompanyTools.PerformLayout();
|
||||
panelStorage.ResumeLayout(false);
|
||||
panelStorage.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
panelCompanyTools.ResumeLayout(false);
|
||||
panelCompanyTools.PerformLayout();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
|
@ -1,6 +1,7 @@
|
||||
using ProjectByldozer.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectByldozer.CollectionGenericObjects;
|
||||
using ProjectByldozer.Drawnings;
|
||||
|
||||
using ProjectByldozer.Exceptions;
|
||||
|
||||
namespace ProjectByldozer;
|
||||
/// <summary>
|
||||
@ -9,23 +10,24 @@ namespace ProjectByldozer;
|
||||
|
||||
public partial class FormCarCollection : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningTrackedCar> _storageCollection;
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningTrackedCar> _storageCollection;
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormCarCollection()
|
||||
public FormCarCollection(ILogger<FormCarCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -33,19 +35,14 @@ public partial class FormCarCollection : Form
|
||||
panelCompanyTools.Enabled = false;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// /// Добавление машины
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddTrackedCar_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
|
||||
FormCarConfig form = new();
|
||||
// TODO передать метод
|
||||
|
||||
form.Show();
|
||||
form.AddEvent(SetTrackedCar);
|
||||
|
||||
@ -55,6 +52,9 @@ public partial class FormCarCollection : Form
|
||||
/// </summary>
|
||||
/// <param name=" Trackedcar"></param>
|
||||
private void SetTrackedCar(DrawningTrackedCar? Trackedcar)
|
||||
{
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_company == null || Trackedcar == null)
|
||||
{
|
||||
@ -64,12 +64,23 @@ public partial class FormCarCollection : Form
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: " + Trackedcar.GetDataForSave());
|
||||
}
|
||||
else
|
||||
}
|
||||
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)
|
||||
@ -79,20 +90,25 @@ public partial class FormCarCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
try
|
||||
{
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
@ -106,6 +122,8 @@ public partial class FormCarCollection : Form
|
||||
|
||||
DrawningTrackedCar? trackedcar = null;
|
||||
int counter = 100;
|
||||
try
|
||||
{
|
||||
while (trackedcar == null)
|
||||
{
|
||||
trackedcar = _company.GetRandomObject();
|
||||
@ -115,16 +133,16 @@ public partial class FormCarCollection : Form
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (trackedcar == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormByldozer form = new()
|
||||
{
|
||||
SetTrackedCar = trackedcar
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -150,6 +168,8 @@ public partial class FormCarCollection : Form
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassiv.Checked)
|
||||
{
|
||||
@ -161,6 +181,12 @@ public partial class FormCarCollection : Form
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void RerfreshListBoxItems()
|
||||
@ -187,12 +213,20 @@ public partial class FormCarCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
@ -228,13 +262,16 @@ public partial class FormCarCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
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 (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -48,7 +48,7 @@ public partial class FormCarConfig : Form
|
||||
// TODO отправка цвета в Drag&Drop
|
||||
}
|
||||
|
||||
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
|
||||
|
||||
|
||||
|
||||
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
|
||||
|
@ -1,3 +1,9 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
|
||||
namespace ProjectByldozer
|
||||
{
|
||||
internal static class Program
|
||||
@ -12,7 +18,30 @@ namespace ProjectByldozer
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
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());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,18 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +35,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
15
ProjectByldozer/ProjectByldozer/serilog.json
Normal file
15
ProjectByldozer/ProjectByldozer/serilog.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user