Compare commits

..

No commits in common. "e25dcc5567466d75dc20e6652166aaede9de554d" and "e0295b4b65b475e1f338547bf2af72d5545e3580" have entirely different histories.

24 changed files with 191 additions and 1366 deletions

View File

@ -1,8 +0,0 @@
using ProjectGasolineTanker.Drawnings;
namespace ProjectGasolineTanker;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="car"></param>
public delegate void TankerDelegate(DrawningTanker car);

View File

@ -15,7 +15,7 @@ public abstract class AbstractCompany
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 97;
protected readonly int _placeSizeHeight = 80;
/// <summary>
/// Ширина окна
@ -35,7 +35,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
@ -96,13 +96,8 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningTanker? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
DrawningTanker? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;

View File

@ -17,6 +17,8 @@ public class CarPark : AbstractCompany
protected override void DrawBackground(Graphics g)
{
Pen pen = new Pen(Color.Brown, 3);
int offsetX = 10, offsetY = -12;
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
@ -47,12 +49,8 @@ public class CarPark : AbstractCompany
int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--)
{
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
if (col == 1)
{
col = numCols + 1;

View File

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

View File

@ -1,6 +1,4 @@

using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -9,19 +7,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
@ -33,24 +19,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
if (position >= 0 && position < Count)
{
return _collection[position];
}
else
{
return null;
}
}
public int Insert(T obj)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) { return -1; }
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
_collection.Insert(position, obj);
return position;
@ -58,17 +50,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
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 < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}
}

View File

@ -1,6 +1,4 @@
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.CollectionGenericObjects;
namespace ProjectGasolineTanker.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@ -10,14 +8,10 @@ where T : class
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int Count => _collection.Length;
public int MaxCount
public int SetMaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -34,8 +28,6 @@ where T : class
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -46,9 +38,12 @@ where T : class
public T? Get(int position)
{
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
}
public int Insert(T obj)
@ -61,14 +56,14 @@ where T : class
return i;
}
}
throw new CollectionOverflowException(Count);
return -1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
return -1;
}
if (_collection[position] == null)
{
@ -93,26 +88,21 @@ where T : class
}
}
throw new CollectionOverflowException(Count);
return -1;
}
public T Remove(int position)
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
return null;
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
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];
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
}

View File

@ -1,10 +1,7 @@
using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
using System.Text;

namespace ProjectGasolineTanker.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningTanker
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -16,21 +13,6 @@ 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>
@ -92,124 +74,4 @@ public class StorageCollection<T>
return null;
}
}
/// <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);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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?.CreateDrawningTanker() is T tanker)
{
try
{
if (collection.Insert(tanker) == -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

@ -17,14 +17,6 @@ public class DrawningGasolineTanker : DrawningTanker
{
EntityTanker = new EntityGasolineTanker(speed, weight, bodyColor, additionalColor, tank, signalbeacon);
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="car">Объект класса-сущность</param>
public DrawningGasolineTanker(EntityTanker entityTanker) : base()
{
EntityTanker = entityTanker;
}
public override void DrawTransport(Graphics g)
{

View File

@ -1,5 +1,5 @@
using ProjectGasolineTanker.Entities;
using ProjectGasolineTanker.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -67,7 +67,7 @@ public class DrawningTanker
/// <summary>
/// Пустой конструктор
/// </summary>
protected DrawningTanker()
private DrawningTanker()
{
_pictureWidth = null;
_pictureHeight = null;
@ -90,27 +90,17 @@ public class DrawningTanker
/// <summary>
/// <param name="drawingBusWidth">Ширина прорисовки танка</param>
/// <param name="drawingBusHeight">Высота прорисовки танка</param>
public DrawningTanker(int drawningCarWidth, int drawningCarHeight) : this()
protected DrawningTanker(int drawningCarWidth, int drawningCarHeight) : this()
{
_drawningCarWidth = drawningCarWidth;
_drawningCarHeight = drawningCarHeight;
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="car">Объект класса-сущность</param>
public DrawningTanker(EntityTanker entityTanker) : base()
{
EntityTanker = entityTanker;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена , нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{

View File

@ -1,55 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.Drawnings;
public static class ExtentionDrawningTanker
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTanker? CreateDrawningTanker(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTanker? tanker = EntityGasolineTanker.CreateEntityGasolineTanker(strs);
if (tanker != null)
{
return new DrawningGasolineTanker(tanker);
}
tanker = EntityTanker.CreateEntityCar(strs);
if (tanker != null)
{
return new DrawningTanker(tanker);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTanker">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTanker drawningTanker)
{
string[]? array = drawningTanker?.EntityTanker?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -9,16 +9,14 @@ public class EntityGasolineTanker : EntityTanker
/// Дополниетльный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
/// <summary>
/// Наличие безнобака
/// </summary>
public bool Signalbeacon { get; private set; }
public bool Tank { get; private set; }
/// <summary>
/// Наличие радара
/// </summary>
public bool Tank { get; private set; }
public bool Signalbeacon { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса зенитной установки
@ -30,33 +28,10 @@ public class EntityGasolineTanker : EntityTanker
/// <param name="tank">Признак</param>
/// <param name="signalbeacon">Признак </param>
public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool signalbeacon, bool tank) : base(speed, weight, bodyColor)
public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool signalbeacon) : base(speed, weight, bodyColor)
{
Signalbeacon = signalbeacon;
Tank = tank;
AdditionalColor = additionalColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityGasolineTanker), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Signalbeacon.ToString(), Tank.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityGasolineTanker? CreateEntityGasolineTanker(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityGasolineTanker))
{
return null;
}
return new EntityGasolineTanker(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -16,8 +16,6 @@ public class EntityTanker
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
public void SetBodyColor(Color color) => BodyColor = color;
/// <summary>
/// Перемещение бензовоза
/// </summary>
@ -35,27 +33,4 @@ public class EntityTanker
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTanker), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTanker? CreateEntityCar(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTanker))
{
return null;
}
return new EntityTanker(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

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

View File

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

View File

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

View File

@ -33,6 +33,7 @@ namespace ProjectGasolineTanker
Инструменты = new GroupBox();
panelCompanyTools = new Panel();
buttonAddTanker = new Button();
buttonAddGasolineTanker = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonRemoveTanker = new Button();
@ -48,17 +49,10 @@ namespace ProjectGasolineTanker
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Инструменты.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// Инструменты
@ -68,9 +62,9 @@ namespace ProjectGasolineTanker
Инструменты.Controls.Add(panelStorage);
Инструменты.Controls.Add(comboBoxSelectorCompany);
Инструменты.Dock = DockStyle.Right;
Инструменты.Location = new Point(861, 24);
Инструменты.Location = new Point(861, 0);
Инструменты.Name = "Инструменты";
Инструменты.Size = new Size(225, 627);
Инструменты.Size = new Size(225, 651);
Инструменты.TabIndex = 0;
Инструменты.TabStop = false;
Инструменты.Text = "Инструменты";
@ -78,26 +72,38 @@ namespace ProjectGasolineTanker
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddTanker);
panelCompanyTools.Controls.Add(buttonAddGasolineTanker);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveTanker);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 380);
panelCompanyTools.Location = new Point(3, 383);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(219, 244);
panelCompanyTools.Size = new Size(219, 265);
panelCompanyTools.TabIndex = 8;
//
// buttonAddTanker
//
buttonAddTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTanker.Location = new Point(3, 21);
buttonAddTanker.Location = new Point(3, 3);
buttonAddTanker.Name = "buttonAddTanker";
buttonAddTanker.Size = new Size(213, 37);
buttonAddTanker.TabIndex = 1;
buttonAddTanker.Text = "Добавление грузовика";
buttonAddTanker.UseVisualStyleBackColor = true;
buttonAddTanker.Click += ButtonAddTanker_Click;
buttonAddTanker.Click += buttonAddTanker_Click;
//
// buttonAddGasolineTanker
//
buttonAddGasolineTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddGasolineTanker.Location = new Point(3, 43);
buttonAddGasolineTanker.Name = "buttonAddGasolineTanker";
buttonAddGasolineTanker.Size = new Size(213, 37);
buttonAddGasolineTanker.TabIndex = 2;
buttonAddGasolineTanker.Text = "Добавление бензовоза\r\n";
buttonAddGasolineTanker.UseVisualStyleBackColor = true;
buttonAddGasolineTanker.Click += buttonAddGasolineTanker_Click;
//
// maskedTextBoxPosition
//
@ -126,7 +132,7 @@ namespace ProjectGasolineTanker
buttonRemoveTanker.Name = "buttonRemoveTanker";
buttonRemoveTanker.Size = new Size(213, 40);
buttonRemoveTanker.TabIndex = 4;
buttonRemoveTanker.Text = "Удаление автомобиль";
buttonRemoveTanker.Text = "Удаление машины";
buttonRemoveTanker.UseVisualStyleBackColor = true;
buttonRemoveTanker.Click += ButtonRemoveTanker_Click;
//
@ -248,101 +254,50 @@ namespace ProjectGasolineTanker
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(861, 627);
pictureBox.Size = new Size(861, 651);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1086, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormTankerCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
AutoScroll = true;
ClientSize = new Size(1086, 651);
Controls.Add(pictureBox);
Controls.Add(Инструменты);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTankerCollection";
Text = "Коллекция Грузовиков";
Text = "Коллекция лодок";
Инструменты.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox Инструменты;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddTanker;
private Button buttonRemoveTanker;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddGasolineTanker;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Button buttonRefresh;
private Button buttonRemoveTanker;
private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCollectionAdd;
private ListBox listBoxCollection;
private TextBox textBoxCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -1,7 +1,5 @@
using Microsoft.Extensions.Logging;
using ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Exceptions;
using System.Windows.Forms;
namespace ProjectGasolineTanker;
@ -21,16 +19,13 @@ public partial class FormTankerCollection : Form
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTankerCollection(ILogger<FormTankerCollection> logger)
public FormTankerCollection()
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -40,79 +35,101 @@ public partial class FormTankerCollection : Form
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new CarPark(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTanker>());
break;
}
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTanker_Click(object sender, EventArgs e)
private void CreateObject(string type)
{
FormTankerConfig form = new();
form.Show();
form.AddEvent(SetTanker);
}
/// <summary>
/// Добавление автомобиля в коллекцию
/// </summary>
/// <param name="tank"></param>
private void SetTanker(DrawningTanker? tank)
{
try
if (_company == null)
{
if (_company == null || tank == null)
{
return;
}
DrawningTanker _drawningTanker;
Random random = new();
switch (type)
{
case nameof(DrawningTanker):
_drawningTanker = new DrawningTanker(random.Next(30, 70), random.Next(100, 500),
GetColor(random));
break;
case nameof(DrawningGasolineTanker):
_drawningTanker = new DrawningGasolineTanker(random.Next(30, 70), random.Next(100, 500),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
}
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
if (_company + _drawningTanker != -1)
{
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Удаление объекта
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTanker));
/// <summary>
/// Добавление спортивного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddGasolineTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningGasolineTanker));
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void ButtonRemoveTanker_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
}
return;
}
catch (Exception ex)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
@ -128,34 +145,28 @@ public partial class FormTankerCollection : Form
return;
}
DrawningTanker? tanker = null;
DrawningTanker? car = null;
int counter = 100;
try
while (car == null)
{
while (tanker == null)
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
tanker = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
break;
}
if (tanker == null)
{
return;
}
FormGasolineTanker form = new FormGasolineTanker();
form.SetTanker = tanker;
form.ShowDialog();
}
catch (Exception ex)
if (car == null)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
FormGasolineTanker form = new()
{
SetTanker = car
};
form.ShowDialog();
}
/// <summary>
@ -179,28 +190,18 @@ public partial class FormTankerCollection : Form
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_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);
RefreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
@ -226,25 +227,14 @@ public partial class FormTankerCollection : 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());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
return;
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
@ -270,54 +260,4 @@ public partial class FormTankerCollection : Form
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@ -117,13 +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, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>255, 17</value>
</metadata>
</root>

View File

@ -1,357 +0,0 @@
namespace ProjectGasolineTanker
{
partial class FormTankerConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxSignalbeacon = new CheckBox();
checkBoxTanker = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxSignalbeacon);
groupBoxConfig.Controls.Add(checkBoxTanker);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(574, 219);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(315, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(227, 112);
groupBoxColors.TabIndex = 10;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(176, 66);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(34, 34);
panelPurple.TabIndex = 3;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(176, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(34, 34);
panelYellow.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(120, 66);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(34, 34);
panelBlack.TabIndex = 4;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(67, 66);
panelGray.Name = "panelGray";
panelGray.Size = new Size(34, 34);
panelGray.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(120, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(34, 34);
panelBlue.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 66);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(34, 34);
panelWhite.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(67, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(34, 34);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(34, 34);
panelRed.TabIndex = 0;
//
// checkBoxSignalbeacon
//
checkBoxSignalbeacon.AutoSize = true;
checkBoxSignalbeacon.Location = new Point(12, 168);
checkBoxSignalbeacon.Name = "checkBoxSignalbeacon";
checkBoxSignalbeacon.Size = new Size(232, 34);
checkBoxSignalbeacon.TabIndex = 9;
checkBoxSignalbeacon.Text = "Признак наличия сигнального маяка\r\n\r\n";
checkBoxSignalbeacon.UseVisualStyleBackColor = true;
//
// checkBoxTanker
//
checkBoxTanker.AutoSize = true;
checkBoxTanker.Location = new Point(12, 125);
checkBoxTanker.Name = "checkBoxTanker";
checkBoxTanker.Size = new Size(154, 19);
checkBoxTanker.TabIndex = 8;
checkBoxTanker.Text = "Признак наличия бака \r\n";
checkBoxTanker.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 65);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(96, 23);
numericUpDownWeight.TabIndex = 7;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 36);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(96, 23);
numericUpDownSpeed.TabIndex = 6;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 73);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 5;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 38);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 3;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(442, 160);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 33);
labelModifiedObject.TabIndex = 2;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(315, 160);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 33);
labelSimpleObject.TabIndex = 1;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(594, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(194, 164);
panelObject.TabIndex = 5;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(108, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(75, 33);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(13, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(75, 33);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(13, 52);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(170, 99);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(607, 184);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(702, 184);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormTankerConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 219);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormTankerConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private CheckBox checkBoxTanker;
private CheckBox checkBoxSignalbeacon;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelGray;
private Panel panelBlue;
private Panel panelWhite;
private Panel panelGreen;
private Panel panelRed;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -1,160 +0,0 @@
using ProjectGasolineTanker.Drawnings;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker;
public partial class FormTankerConfig : Form
{
private DrawningTanker? _tanker = null;
private event Action<DrawningTanker>? _TankerDelegate;
public FormTankerConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="tankerDelegate"></param>
public void AddEvent(Action<DrawningTanker> TankerDelegate)
{
_TankerDelegate += TankerDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_tanker?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_tanker?.SetPosition(15, 15);
_tanker?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_tanker = new DrawningTanker((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_tanker = new DrawningGasolineTanker((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxTanker.Checked, checkBoxSignalbeacon.Checked);
break;
}
labelBodyColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_tanker != null)
{
_tanker.EntityTanker.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_tanker is DrawningGasolineTanker)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_tanker?.EntityTanker is EntityGasolineTanker _gasolinetanker)
{
_gasolinetanker.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_tanker != null)
{
_TankerDelegate?.Invoke(_tanker);
Close();
}
}
}

View File

@ -1,120 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,8 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker
{
internal static class Program
@ -16,32 +11,7 @@ namespace ProjectGasolineTanker
// 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<FormTankerCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
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<FormTankerCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
Application.Run(new FormTankerCollection());
}
}
}

View File

@ -8,21 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<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>
<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": {
"Applicatoin": "Sample"
}
}
}