5 Commits
lab6 ... 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
14 changed files with 508 additions and 116 deletions

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

@@ -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

@@ -32,10 +32,6 @@
this.panelStorages = new System.Windows.Forms.Panel();
this.labelStorages = new System.Windows.Forms.Label();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
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.buttonDelObject = new System.Windows.Forms.Button();
this.buttonAddObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
@@ -44,9 +40,15 @@
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();
@@ -57,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);
@@ -72,13 +76,12 @@
//
this.panelStorages.Controls.Add(this.labelStorages);
this.panelStorages.Controls.Add(this.textBoxStorageName);
this.panelStorages.Controls.Add(this.menuStripFile);
this.panelStorages.Controls.Add(this.buttonDelObject);
this.panelStorages.Controls.Add(this.buttonAddObject);
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, 246);
this.panelStorages.Size = new System.Drawing.Size(200, 215);
this.panelStorages.TabIndex = 5;
//
// labelStorages
@@ -97,40 +100,6 @@
this.textBoxStorageName.Size = new System.Drawing.Size(150, 23);
this.textBoxStorageName.TabIndex = 3;
//
// 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(25, 222);
this.menuStripFile.Name = "menuStripFile";
this.menuStripFile.Size = new System.Drawing.Size(176, 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(180, 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(180, 22);
this.toolStripMenuItemLoad.Text = "Загрузить";
this.toolStripMenuItemLoad.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(25, 185);
@@ -163,14 +132,14 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(28, 306);
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;
@@ -190,7 +159,7 @@
//
// buttonRemoveTruck
//
this.buttonRemoveTruck.Location = new System.Drawing.Point(28, 335);
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;
@@ -200,7 +169,7 @@
//
// buttonAddTruck
//
this.buttonAddTruck.Location = new System.Drawing.Point(28, 270);
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;
@@ -208,11 +177,45 @@
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;
//
@@ -225,6 +228,26 @@
//
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);
@@ -232,6 +255,7 @@
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";
@@ -243,6 +267,7 @@
this.menuStripFile.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -267,5 +292,7 @@
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,13 @@ 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}");
}
}
@@ -105,16 +117,31 @@ namespace DumpTruck
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
return;
}
if (obj + truck != -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
if (obj + truck != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrucks();
_logger.LogInformation($"Объект добавлен {truck}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (ApplicationException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
@@ -122,6 +149,7 @@ namespace DumpTruck
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Не удалось добавить объект: не выбран набор");
return;
}
var formTruckConfig = new FormTruckConfig();
@@ -133,11 +161,13 @@ namespace DumpTruck
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Не удалось удалить объект: не выбран набор");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось удалить объект: набор пуст");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
@@ -146,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)
{
@@ -179,14 +218,16 @@ namespace DumpTruck
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение прошло успешно: {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@@ -200,18 +241,52 @@ namespace DumpTruck
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation($"Загрузка прошла успешно: {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
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

@@ -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

@@ -41,6 +41,12 @@ namespace DumpTruck.Generics
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTrucks => _collection.GetTrucks();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Конструктор
/// </summary>
@@ -66,7 +72,7 @@ namespace DumpTruck.Generics
{
return -1;
}
return collect._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawiningCarEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания
@@ -74,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>

View File

@@ -28,11 +28,11 @@ namespace DumpTruck.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> _truckStorages;
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>
@@ -48,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;
}
@@ -58,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>
/// Удаление набора
@@ -66,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>
/// Доступ к набору
@@ -75,10 +75,11 @@ 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;
}
}
@@ -87,51 +88,50 @@ namespace DumpTruck.Generics
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TrucksGenericCollection<DrawingTruck, DrawningObjectTruck>> record in _truckStorages)
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}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TruckStorage{Environment.NewLine}{data}");
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("TruckStorage"))
{
return false;
throw new InvalidDataException("Неверный формат данных");
}
_truckStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -143,21 +143,20 @@ namespace DumpTruck.Generics
}
TrucksGenericCollection < DrawingTruck, DrawningObjectTruck > collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
foreach (string elem in set.Reverse())
{
DrawingTruck? truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (truck != null)
{
if (collection + truck == -1)
{
return false;
}
throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}
_truckStorages.Add(record[0], collection);
_truckStorages.Add(new TrucksCollectionInfo(record[0], string.Empty), collection);
}
}
return true;
}
}
}

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"
}
}
}