7 Commits
lab4 ... lab8

Author SHA1 Message Date
4db8b7f4d3 Готовая 8 лабораторная 2023-12-15 22:40:13 +04:00
fbf00076a0 revert 8e06837ec5
revert Готовая 8 лабораторная
2023-12-15 22:27:39 +04:00
8e06837ec5 Готовая 8 лабораторная 2023-12-15 22:21:46 +04:00
6b4b8d72bf Замена класса Exception на его наследников 2023-12-15 21:35:14 +04:00
193940f62c Готовая 7 лабораторная 2023-12-15 21:24:09 +04:00
6d86c591d1 Готовая 6 лабораторная 2023-12-01 19:22:27 +04:00
0d223f8de8 Готовая 5 лабораторная 2023-11-24 20:27:04 +04:00
22 changed files with 1396 additions and 86 deletions

View File

@@ -17,11 +17,11 @@ namespace DumpTruck.DrawingObjects
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public int _pictureHeight;
/// <summary>
/// Левая координата прорисовки грузовика
/// </summary>
@@ -56,7 +56,7 @@ namespace DumpTruck.DrawingObjects
/// </summary>
public int GetHeight => _truckHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingTruck
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectTruck(this);

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.Entities;
namespace DumpTruck.DrawingObjects
{
public static class ExtentionDrawingTruck
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingTruck? CreateDrawingTruck(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawingDumpTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Convert.ToBoolean(strs[3]),
Convert.ToBoolean(strs[4]),
Color.FromName(strs[5]),
Color.FromName(strs[6]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingTruck">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingTruck drawingTruck, char separatorForObject)
{
var truck = drawingTruck.EntityTruck;
if (truck == null)
{
return string.Empty;
}
var str = $"{truck.Speed}{separatorForObject}{truck.Weight}{separatorForObject}{truck.BodyColor.Name}";
if (truck is not EntityDumpTruck dumpTruck)
{
return str;
}
return
$"{str}{separatorForObject}{dumpTruck.Tent}{separatorForObject}{dumpTruck.DumpBox}{separatorForObject}{dumpTruck.TentColor.Name}{separatorForObject}{dumpTruck.DumpBoxColor.Name}";
}
}
}

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" 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>

View File

@@ -19,11 +19,11 @@ namespace DumpTruck.Entities
/// <summary>
/// Цвет кузова
/// </summary>
public Color DumpBoxColor { get; private set; }
public Color DumpBoxColor { get; set; }
/// <summary>
/// Цвет тента
/// </summary>
public Color TentColor { get; private set; }
public Color TentColor { get; set; }
/// <summary>
/// Конструктор
/// </summary>

View File

@@ -19,7 +19,7 @@ namespace DumpTruck.Entities
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг
/// </summary>

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception)
: base(message, exception) { }
protected StorageOverflowException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Exceptions
{
[Serializable]
internal class TruckNotFoundException : ApplicationException
{
public TruckNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public TruckNotFoundException() : base() { }
public TruckNotFoundException(string message) : base(message) { }
public TruckNotFoundException(string message, Exception exception) : base(message, exception) { }
protected TruckNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -40,9 +40,18 @@
this.labelTools = new System.Windows.Forms.Label();
this.buttonRemoveTruck = new System.Windows.Forms.Button();
this.buttonAddTruck = new System.Windows.Forms.Button();
this.menuStripFile = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItemFile = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemSave = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemLoad = new System.Windows.Forms.ToolStripMenuItem();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.panelTools.SuspendLayout();
this.panelStorages.SuspendLayout();
this.menuStripFile.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout();
//
@@ -50,6 +59,8 @@
//
this.panelTools.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.panelTools.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelTools.Controls.Add(this.buttonSortByColor);
this.panelTools.Controls.Add(this.buttonSortByType);
this.panelTools.Controls.Add(this.panelStorages);
this.panelTools.Controls.Add(this.maskedTextBoxNumber);
this.panelTools.Controls.Add(this.buttonRefreshCollection);
@@ -70,7 +81,7 @@
this.panelStorages.Controls.Add(this.listBoxStorages);
this.panelStorages.Location = new System.Drawing.Point(3, 18);
this.panelStorages.Name = "panelStorages";
this.panelStorages.Size = new System.Drawing.Size(200, 221);
this.panelStorages.Size = new System.Drawing.Size(200, 215);
this.panelStorages.TabIndex = 5;
//
// labelStorages
@@ -121,14 +132,14 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 302);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 339);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(150, 23);
this.maskedTextBoxNumber.TabIndex = 4;
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(28, 395);
this.buttonRefreshCollection.Location = new System.Drawing.Point(28, 404);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(150, 30);
this.buttonRefreshCollection.TabIndex = 3;
@@ -148,7 +159,7 @@
//
// buttonRemoveTruck
//
this.buttonRemoveTruck.Location = new System.Drawing.Point(28, 336);
this.buttonRemoveTruck.Location = new System.Drawing.Point(28, 368);
this.buttonRemoveTruck.Name = "buttonRemoveTruck";
this.buttonRemoveTruck.Size = new System.Drawing.Size(150, 30);
this.buttonRemoveTruck.TabIndex = 2;
@@ -158,7 +169,7 @@
//
// buttonAddTruck
//
this.buttonAddTruck.Location = new System.Drawing.Point(28, 257);
this.buttonAddTruck.Location = new System.Drawing.Point(28, 303);
this.buttonAddTruck.Name = "buttonAddTruck";
this.buttonAddTruck.Size = new System.Drawing.Size(150, 30);
this.buttonAddTruck.TabIndex = 1;
@@ -166,14 +177,77 @@
this.buttonAddTruck.UseVisualStyleBackColor = true;
this.buttonAddTruck.Click += new System.EventHandler(this.buttonAddTruck_Click);
//
// menuStripFile
//
this.menuStripFile.Dock = System.Windows.Forms.DockStyle.None;
this.menuStripFile.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemFile});
this.menuStripFile.Location = new System.Drawing.Point(9, 4);
this.menuStripFile.Name = "menuStripFile";
this.menuStripFile.Size = new System.Drawing.Size(56, 24);
this.menuStripFile.TabIndex = 2;
this.menuStripFile.Text = "menuStripFile";
//
// toolStripMenuItemFile
//
this.toolStripMenuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemSave,
this.toolStripMenuItemLoad});
this.toolStripMenuItemFile.Name = "toolStripMenuItemFile";
this.toolStripMenuItemFile.Size = new System.Drawing.Size(48, 20);
this.toolStripMenuItemFile.Text = "Файл";
//
// toolStripMenuItemSave
//
this.toolStripMenuItemSave.Name = "toolStripMenuItemSave";
this.toolStripMenuItemSave.Size = new System.Drawing.Size(133, 22);
this.toolStripMenuItemSave.Text = "Сохранить";
this.toolStripMenuItemSave.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// toolStripMenuItemLoad
//
this.toolStripMenuItemLoad.Name = "toolStripMenuItemLoad";
this.toolStripMenuItemLoad.Size = new System.Drawing.Size(133, 22);
this.toolStripMenuItemLoad.Text = "Загрузить";
this.toolStripMenuItemLoad.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(2, 3);
this.pictureBoxCollection.Location = new System.Drawing.Point(2, 31);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(588, 445);
this.pictureBoxCollection.Size = new System.Drawing.Size(588, 417);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(28, 238);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(150, 25);
this.buttonSortByType.TabIndex = 6;
this.buttonSortByType.Text = "Сортировка по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(28, 269);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(150, 25);
this.buttonSortByColor.TabIndex = 7;
this.buttonSortByColor.Text = "Сортировка по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// FormTruckCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -181,14 +255,19 @@
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.panelTools);
this.Controls.Add(this.menuStripFile);
this.MainMenuStrip = this.menuStripFile;
this.Name = "FormTruckCollection";
this.Text = "FormTruckCollection";
this.panelTools.ResumeLayout(false);
this.panelTools.PerformLayout();
this.panelStorages.ResumeLayout(false);
this.panelStorages.PerformLayout();
this.menuStripFile.ResumeLayout(false);
this.menuStripFile.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -207,5 +286,13 @@
private ListBox listBoxStorages;
private Label labelStorages;
private TextBox textBoxStorageName;
private MenuStrip menuStripFile;
private ToolStripMenuItem toolStripMenuItemFile;
private ToolStripMenuItem toolStripMenuItemSave;
private ToolStripMenuItem toolStripMenuItemLoad;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -10,6 +10,8 @@ using System.Windows.Forms;
using DumpTruck.Generics;
using DumpTruck.DrawingObjects;
using DumpTruck.MovementStrategy;
using DumpTruck.Exceptions;
using Microsoft.Extensions.Logging;
namespace DumpTruck
{
@@ -23,13 +25,19 @@ namespace DumpTruck
/// </summary>
private readonly TrucksGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTruckCollection()
public FormTruckCollection(ILogger<FormTruckCollection> logger)
{
InitializeComponent();
_storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
@@ -38,7 +46,7 @@ namespace DumpTruck
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
@@ -66,6 +74,7 @@ namespace DumpTruck
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
@@ -87,10 +96,52 @@ namespace DumpTruck
{
return;
}
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
private void AddTruck(DrawingTruck truck)
{
truck._pictureWidth = pictureBoxCollection.Image.Width;
truck._pictureHeight = pictureBoxCollection.Image.Height;
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
return;
}
try
{
if (obj + truck != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Объект добавлен {truck}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
@@ -98,37 +149,25 @@ namespace DumpTruck
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Не удалось добавить объект: не выбран набор");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormDumpTruck form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (obj + form.SelectedTruck != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
var formTruckConfig = new FormTruckConfig();
formTruckConfig.AddEvent(AddTruck);
formTruckConfig.Show();
}
private void buttonRemoveTruck_Click(object sender, EventArgs e)
private void buttonRemoveTruck_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Не удалось удалить объект: не выбран набор");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось удалить объект: набор пуст");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
@@ -137,18 +176,27 @@ namespace DumpTruck
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrucks();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
try
{
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Удален объект на позиции: {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch (TruckNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
}
}
private void buttonRefreshCollection_Click(object sender, EventArgs e)
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
@@ -161,6 +209,84 @@ namespace DumpTruck
}
pictureBoxCollection.Image = obj.ShowTrucks();
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение прошло успешно: {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTrucks(new TruckCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTrucks(new TruckCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareTrucks(IComparer<DrawingTruck?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTrucks();
}
}
}

View File

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

405
DumpTruck/FormTruckConfig.Designer.cs generated Normal file
View File

@@ -0,0 +1,405 @@
namespace DumpTruck
{
partial class FormTruckConfig
{
/// <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()
{
this.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxTent = new System.Windows.Forms.CheckBox();
this.checkBoxDumpBox = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.PanelObject = new System.Windows.Forms.Panel();
this.labelTentColor = new System.Windows.Forms.Label();
this.labelDumpBoxColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.PanelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColors);
this.groupBoxParameters.Controls.Add(this.checkBoxTent);
this.groupBoxParameters.Controls.Add(this.checkBoxDumpBox);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(12, 12);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Size = new System.Drawing.Size(463, 246);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(335, 158);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(100, 23);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(229, 158);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(100, 23);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(229, 38);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(206, 100);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(136, 55);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(30, 30);
this.panelPurple.TabIndex = 2;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(100, 55);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(30, 30);
this.panelBlack.TabIndex = 2;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(64, 55);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(30, 30);
this.panelGray.TabIndex = 2;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(28, 55);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(30, 30);
this.panelWhite.TabIndex = 2;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(136, 19);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(30, 30);
this.panelYellow.TabIndex = 2;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(100, 19);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(30, 30);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(64, 19);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(30, 30);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(28, 19);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(30, 30);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxTent
//
this.checkBoxTent.AutoSize = true;
this.checkBoxTent.Location = new System.Drawing.Point(23, 158);
this.checkBoxTent.Name = "checkBoxTent";
this.checkBoxTent.Size = new System.Drawing.Size(155, 19);
this.checkBoxTent.TabIndex = 5;
this.checkBoxTent.Text = "Признак наличия тента";
this.checkBoxTent.UseVisualStyleBackColor = true;
//
// checkBoxDumpBox
//
this.checkBoxDumpBox.AutoSize = true;
this.checkBoxDumpBox.Location = new System.Drawing.Point(23, 119);
this.checkBoxDumpBox.Name = "checkBoxDumpBox";
this.checkBoxDumpBox.Size = new System.Drawing.Size(162, 19);
this.checkBoxDumpBox.TabIndex = 4;
this.checkBoxDumpBox.Text = "Признак наличия кузова";
this.checkBoxDumpBox.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(71, 62);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(82, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(71, 19);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(82, 23);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(6, 64);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(26, 15);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 19);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(59, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(46, 56);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(226, 131);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// PanelObject
//
this.PanelObject.AllowDrop = true;
this.PanelObject.Controls.Add(this.labelTentColor);
this.PanelObject.Controls.Add(this.labelDumpBoxColor);
this.PanelObject.Controls.Add(this.labelBaseColor);
this.PanelObject.Controls.Add(this.pictureBoxObject);
this.PanelObject.Location = new System.Drawing.Point(481, 12);
this.PanelObject.Name = "PanelObject";
this.PanelObject.Size = new System.Drawing.Size(307, 196);
this.PanelObject.TabIndex = 2;
this.PanelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.PanelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelTentColor
//
this.labelTentColor.AllowDrop = true;
this.labelTentColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelTentColor.Location = new System.Drawing.Point(202, 13);
this.labelTentColor.Name = "labelTentColor";
this.labelTentColor.Size = new System.Drawing.Size(70, 40);
this.labelTentColor.TabIndex = 4;
this.labelTentColor.Text = "Цвет тента";
this.labelTentColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelTentColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelTentColor_DragDrop);
this.labelTentColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// labelDumpBoxColor
//
this.labelDumpBoxColor.AllowDrop = true;
this.labelDumpBoxColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDumpBoxColor.Location = new System.Drawing.Point(124, 13);
this.labelDumpBoxColor.Name = "labelDumpBoxColor";
this.labelDumpBoxColor.Size = new System.Drawing.Size(70, 40);
this.labelDumpBoxColor.TabIndex = 3;
this.labelDumpBoxColor.Text = "Цвет кузова";
this.labelDumpBoxColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDumpBoxColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelDumpBoxColor_DragDrop);
this.labelDumpBoxColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(46, 13);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(70, 40);
this.labelBaseColor.TabIndex = 2;
this.labelBaseColor.Text = "Основной цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(527, 221);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(100, 30);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(653, 221);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(100, 30);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormTruckConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 271);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.PanelObject);
this.Controls.Add(this.groupBoxParameters);
this.Name = "FormTruckConfig";
this.Text = "Создание объекта";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.PanelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private CheckBox checkBoxTent;
private CheckBox checkBoxDumpBox;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private PictureBox pictureBoxObject;
private Panel PanelObject;
private Label labelDumpBoxColor;
private Label labelBaseColor;
private Button buttonAdd;
private Button buttonCancel;
private Label labelTentColor;
}
}

View File

@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DumpTruck.DrawingObjects;
using DumpTruck.Entities;
namespace DumpTruck
{
public partial class FormTruckConfig : Form
{
/// <summary>
/// Переменная-выбранный грузовик
/// </summary>
DrawingTruck? _truck = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingTruck>? EventAddTruck;
/// <summary>
/// Конструктор
/// </summary>
public FormTruckConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (object sender, EventArgs e) => Close();
}
/// <summary>
/// Отрисовать грузовик
/// </summary>
private void DrawTruck()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_truck?.SetPosition(5, 5);
_truck?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawingTruck> ev)
{
if (EventAddTruck == null)
{
EventAddTruck = ev;
}
else
{
EventAddTruck += ev;
}
}
/// <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, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = 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":
_truck = new DrawingTruck((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_truck = new DrawingDumpTruck((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, checkBoxTent.Checked,
checkBoxDumpBox.Checked, Color.Black, Color.Gray, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawTruck();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_truck != null)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
_truck.EntityTruck.BodyColor = (Color)e.Data.GetData(typeof(Color));
}
DrawTruck();
}
}
private void labelDumpBoxColor_DragDrop(object sender, DragEventArgs e)
{
if (_truck != null && _truck.EntityTruck is EntityDumpTruck entityDumpTruck)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
entityDumpTruck.DumpBoxColor = (Color)e.Data.GetData(typeof(Color));
}
DrawTruck();
}
}
private void labelTentColor_DragDrop(object sender, DragEventArgs e)
{
if (_truck != null && _truck.EntityTruck is EntityDumpTruck entityDumpTruck)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
entityDumpTruck.TentColor = (Color)e.Data.GetData(typeof(Color));
}
DrawTruck();
}
}
/// <summary>
/// Добавление грузовика
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddTruck?.Invoke(_truck);
Close();
}
}
}

View File

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

@@ -0,0 +1,65 @@
using DumpTruck.DrawingObjects;
using DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class DrawiningCarEqutables : IEqualityComparer<DrawingTruck?>
{
public bool Equals(DrawingTruck? x, DrawingTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
{
return false;
}
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
{
return false;
}
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
{
return false;
}
if (x is DrawingDumpTruck && y is DrawingDumpTruck)
{
EntityDumpTruck xDumpTruck = (EntityDumpTruck)x.EntityTruck;
EntityDumpTruck yDumpTruck = (EntityDumpTruck)y.EntityTruck;
if (xDumpTruck.DumpBoxColor != yDumpTruck.DumpBoxColor)
return false;
if (xDumpTruck.TentColor != yDumpTruck.TentColor)
return false;
if (xDumpTruck.Tent != yDumpTruck.Tent)
return false;
if (xDumpTruck.DumpBox != yDumpTruck.DumpBox)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTruck obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using DumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -25,11 +26,17 @@ namespace DumpTruck.Generics
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
@@ -39,9 +46,9 @@ namespace DumpTruck.Generics
/// </summary>
/// <param name="truck">Добавляемый грузовик</param>
/// <returns></returns>
public int Insert(T truck)
public int Insert(T truck, IEqualityComparer<T?>? equal = null)
{
return Insert(truck, 0);
return Insert(truck, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@@ -49,9 +56,14 @@ namespace DumpTruck.Generics
/// <param name="truck">Добавляемый грузовик</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T truck, int position)
public int Insert(T truck, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position > Count || Count >= _maxCount) return -1;
if (position < 0 || position > Count)
throw new TruckNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(truck, equal))
throw new ArgumentException("Данный объект уже есть в коллекции");
_places.Insert(position, truck);
return position;
}
@@ -62,7 +74,7 @@ namespace DumpTruck.Generics
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count) return false;
if (position < 0 || position >= Count) throw new TruckNotFoundException(position);
_places.RemoveAt(position);
return true;
}

View File

@@ -0,0 +1,49 @@
using DumpTruck.DrawingObjects;
using DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TruckCompareByColor : IComparer<DrawingTruck?>
{
public int Compare(DrawingTruck? x, DrawingTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityTruck.BodyColor.Name.CompareTo(y.EntityTruck.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityTruck is EntityDumpTruck xEntityDumpTruck && y.EntityTruck is EntityDumpTruck yEntityDumpTruck)
{
var dumpBoxColorCompare = xEntityDumpTruck.DumpBoxColor.Name.CompareTo(yEntityDumpTruck.DumpBoxColor.Name);
if (dumpBoxColorCompare != 0)
{
return dumpBoxColorCompare;
}
var tentColorCompare = xEntityDumpTruck.TentColor.Name.CompareTo(yEntityDumpTruck.TentColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}
}

View File

@@ -0,0 +1,35 @@
using DumpTruck.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TruckCompareByType : IComparer<DrawingTruck?>
{
public int Compare(DrawingTruck? x, DrawingTruck? y)
{
if (x == null || x.EntityTruck == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTruck == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Generics
{
internal class TrucksCollectionInfo : IEquatable<TrucksCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TrucksCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TrucksCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@@ -37,6 +37,16 @@ namespace DumpTruck.Generics
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTrucks => _collection.GetTrucks();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Конструктор
/// </summary>
@@ -62,7 +72,7 @@ namespace DumpTruck.Generics
{
return -1;
}
return collect._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawiningCarEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания
@@ -70,15 +80,11 @@ namespace DumpTruck.Generics
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(TrucksGenericCollection<T, U> collect, int pos)
public static bool operator -(TrucksGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
return collect._collection.Remove(pos);
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
@@ -128,11 +134,11 @@ namespace DumpTruck.Generics
{
int index = 0;
foreach (var truck in _collection.GetTrucks())
{
{
if (truck != null)
{
truck.SetPosition(index % (_pictureWidth / _placeSizeWidth) * _placeSizeWidth, index / (_pictureWidth / _placeSizeWidth) * _placeSizeHeight);
truck.DrawTransport(g);
truck.SetPosition(index % (_pictureWidth / _placeSizeWidth) * _placeSizeWidth, index / (_pictureWidth / _placeSizeWidth) * _placeSizeHeight);
truck.DrawTransport(g);
}
index++;
}

View File

@@ -13,14 +13,26 @@ namespace DumpTruck.Generics
/// </summary>
internal class TrucksGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> _truckStorages;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> _truckStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _truckStorages.Keys.ToList();
public List<TrucksCollectionInfo> Keys => _truckStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@@ -36,7 +48,7 @@ namespace DumpTruck.Generics
/// <param name="pictureHeight"></param>
public TrucksGenericStorage(int pictureWidth, int pictureHeight)
{
_truckStorages = new Dictionary<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>>();
_truckStorages = new Dictionary<TrucksCollectionInfo, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -46,7 +58,7 @@ namespace DumpTruck.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_truckStorages.ContainsKey(name)) _truckStorages.Add(name, new TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
if (!_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty))) _truckStorages.Add(new TrucksCollectionInfo(name, string.Empty), new TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@@ -54,7 +66,7 @@ namespace DumpTruck.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_truckStorages.ContainsKey(name)) _truckStorages.Remove(name);
if (_truckStorages.ContainsKey(new TrucksCollectionInfo(name, string.Empty))) _truckStorages.Remove(new TrucksCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@@ -63,12 +75,88 @@ namespace DumpTruck.Generics
/// <returns></returns>
public TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>?
this[string ind]
{
get
{
get
{
if (_truckStorages.ContainsKey(ind)) return _truckStorages[ind];
if (_truckStorages.ContainsKey(new TrucksCollectionInfo(ind, string.Empty)))
return _truckStorages[new TrucksCollectionInfo(ind, string.Empty)];
return null;
}
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<TrucksCollectionInfo, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> record in _truckStorages)
{
StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTrucks)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TruckStorage{Environment.NewLine}{data}");
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("TruckStorage"))
{
throw new InvalidDataException("Неверный формат данных");
}
_truckStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
TrucksGenericCollection < DrawingTruck, DrawningObjectTruck > collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{
DrawingTruck? truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null)
{
if (collection + truck == -1)
{
throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}
_truckStorages.Add(new TrucksCollectionInfo(record[0], string.Empty), collection);
}
}
}
}
}

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace DumpTruck
{
internal static class Program
@@ -11,7 +16,28 @@ namespace DumpTruck
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTruckCollection());
}
}
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTruckCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "DumpTruck"
}
}
}