2 Commits

Author SHA1 Message Date
f990ff490f лабораторная работа 5 исправленная 2024-04-14 19:01:10 +04:00
9a51457f08 исправление 2024-04-14 18:59:22 +04:00
21 changed files with 209 additions and 798 deletions

View File

@@ -38,8 +38,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) -4 ;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -52,7 +51,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
@@ -61,10 +60,11 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedCar trackedCar)
public static int operator +(AbstractCompany company, DrawningTrackedCar TrackedCar)
{
return company._collection.Insert(trackedCar);
return company._collection.Insert(TrackedCar);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
@@ -99,19 +99,13 @@ 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) { }
DrawningTrackedCar? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@@ -14,7 +14,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
@@ -43,15 +43,5 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
T? Get(int position);
}

View File

@@ -1,7 +1,5 @@

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

View File

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

View File

@@ -1,16 +1,12 @@

using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
using System.Text;
namespace ProjectByldozer.CollectionGenericObjects;
// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningTrackedCar
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@@ -21,20 +17,7 @@ public class StorageCollection<T>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@@ -69,6 +52,7 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
@@ -88,142 +72,4 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
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;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
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)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}

View File

@@ -1,7 +1,5 @@

using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
namespace ProjectByldozer.CollectionGenericObjects;
public class TrackedCarGarage : AbstractCompany
{
@@ -37,30 +35,29 @@ public class TrackedCarGarage : AbstractCompany
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = 0;
int curHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 2);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException) { }
if (curWidth > 0)
curWidth--;
else
{
curWidth = width - 1;
curHeight++;
curHeight--;
}
if (curHeight > height)
if (curHeight < 0)
{
return;
}
}
}

View File

@@ -22,23 +22,6 @@ public class DrawningByldozer : DrawningTrackedCar
{
EntityTrackedCar = new EntityByldozer(speed, weight, bodyColor, additionalColor, dump, bakingpowder, pipe);
}
/// <summary>
/// Конструктор для
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="pin"></param>
/// <param name="rokets"></param>
/// <param name="symbolism"></param>
public DrawningByldozer(EntityTrackedCar entityTrackedCar)
{
if (entityTrackedCar != null)
{
EntityTrackedCar = entityTrackedCar;
}
}
public override void DrawTransport(Graphics g)
{

View File

@@ -67,7 +67,7 @@ public class DrawningTrackedCar
/// Высота объекта
/// </summary>
public int GetHeight => _drawningTrackedCarHeight;
public DrawningTrackedCar()
private DrawningTrackedCar()
{
_pictureWidth = null;
_pictureHeight = null;
@@ -95,16 +95,7 @@ public class DrawningTrackedCar
this._drawningTrackedCarWidth = _drawningShipWidth;
this._drawningTrackedCarHeight = _drawnShipHeight;
}
/// <summary>
/// Конструктор для Drawning
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public DrawningTrackedCar(EntityTrackedCar entityTrackedCar)
{
EntityTrackedCar = entityTrackedCar;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@@ -1,56 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectByldozer.Entities;
namespace ProjectByldozer.Drawnings;
public static class ExtensionDrawningTrackedCar
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedCar? CreateDrawningTrackedCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedCar? Trackedcar = EntityByldozer.CreateEntityByldozer(strs);
if (Trackedcar != null)
{
return new DrawningByldozer(Trackedcar);
}
Trackedcar = EntityTrackedCar.CreateEntityTrackedCar(strs);
if (Trackedcar != null)
{
return new DrawningTrackedCar(Trackedcar);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedCar drawningTrackedCar)
{
string[]? array = drawningTrackedCar?.EntityTrackedCar?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -52,28 +52,4 @@ public class EntityByldozer : EntityTrackedCar
Bakingpowder = bakingpowder;
Pipe = pipe;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityByldozer), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Dump.ToString(), Bakingpowder.ToString(), Pipe.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityByldozer? CreateEntityByldozer(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityByldozer))
{
return null;
}
return new EntityByldozer(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

@@ -43,30 +43,5 @@ public class EntityTrackedCar
BodyColor = bodyColor;
}
//TODO Прописать метод
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrackedCar), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrackedCar? CreateEntityTrackedCar(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrackedCar))
{
return null;
}
return new EntityTrackedCar(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -1,18 +0,0 @@
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

@@ -1,16 +0,0 @@
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

@@ -1,17 +0,0 @@
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,12 +29,6 @@
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();
@@ -45,100 +39,32 @@
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();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panelCompanyTools = new Panel();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
panelCompanyTools.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(comboBoxSelectionCompany);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(778, 24);
groupBoxTools.Location = new Point(778, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(209, 494);
groupBoxTools.Size = new Size(209, 501);
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;
@@ -243,76 +169,98 @@
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 181);
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, 149);
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, 120);
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(3, 91);
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.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(778, 494);
pictureBox.Size = new Size(778, 501);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
// panelCompanyTools
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(987, 24);
menuStrip.TabIndex = 10;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.FileName = "txt file | *.txt";
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(776, 293);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(208, 208);
panelCompanyTools.TabIndex = 9;
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(987, 518);
ClientSize = new Size(987, 501);
Controls.Add(panelCompanyTools);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCarCollection";
Text = "коллекция бульдозеров";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -335,11 +283,5 @@
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

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

View File

@@ -117,16 +117,4 @@
<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, 3</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 3</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 3</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@@ -14,7 +14,8 @@ public partial class FormCarConfig : Form
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningTrackedCar>? TrackedCarDelegate;
private event Action<DrawningTrackedCar>? TrackedCarDelegate;
/// <summary>
/// конструктор
/// </summary>
@@ -40,7 +41,7 @@ public partial class FormCarConfig : Form
{
TrackedCarDelegate += TrackedcarDelegate;
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
@@ -48,7 +49,7 @@ public partial class FormCarConfig : Form
// TODO отправка цвета в Drag&Drop
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)

View File

@@ -1,9 +1,3 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectByldozer
{
internal static class Program
@@ -17,31 +11,8 @@ namespace ProjectByldozer
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
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());
});
Application.Run(new FormCarCollection());
}
}
}
}

View File

@@ -8,18 +8,6 @@
<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>
@@ -35,10 +23,4 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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