This commit is contained in:
dyakonovr 2023-12-02 17:11:04 +04:00
parent e6406130fd
commit 2468f39500
10 changed files with 166 additions and 76 deletions

View File

@ -0,0 +1,15 @@
using System.Runtime.Serialization;
namespace ProjectTank.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,16 @@
using System.Runtime.Serialization;
namespace ProjectTank.Exceptions
{
[Serializable]
internal class TankNotFoundException : ApplicationException
{
public TankNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public TankNotFoundException() : base() { }
public TankNotFoundException(string message) : base(message) { }
public TankNotFoundException(string message, Exception exception) :
base(message, exception) { }
protected TankNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -33,12 +33,12 @@
deleteTankButton = new Button(); deleteTankButton = new Button();
addTankButton = new Button(); addTankButton = new Button();
maskedTextBoxNumber = new TextBox(); maskedTextBoxNumber = new TextBox();
objectsLabel = new Label(); label2 = new Label();
textBoxStorageName = new TextBox(); textBoxStorageName = new TextBox();
addObjectButton = new Button(); addObjectButton = new Button();
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
deleteObjectButton = new Button(); deleteObjectButton = new Button();
toolsGroupBox = new GroupBox(); groupBox1 = new GroupBox();
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem(); fileToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
@ -46,7 +46,7 @@
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsGroupBox.SuspendLayout(); groupBox1.SuspendLayout();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
@ -95,14 +95,14 @@
maskedTextBoxNumber.Size = new Size(139, 27); maskedTextBoxNumber.Size = new Size(139, 27);
maskedTextBoxNumber.TabIndex = 7; maskedTextBoxNumber.TabIndex = 7;
// //
// objectsLabel // label2
// //
objectsLabel.AutoSize = true; label2.AutoSize = true;
objectsLabel.Location = new Point(6, 30); label2.Location = new Point(6, 30);
objectsLabel.Name = "objectsLabel"; label2.Name = "label2";
objectsLabel.Size = new Size(66, 20); label2.Size = new Size(66, 20);
objectsLabel.TabIndex = 8; label2.TabIndex = 8;
objectsLabel.Text = "Наборы"; label2.Text = "Наборы";
// //
// textBoxStorageName // textBoxStorageName
// //
@ -141,23 +141,23 @@
deleteObjectButton.UseVisualStyleBackColor = true; deleteObjectButton.UseVisualStyleBackColor = true;
deleteObjectButton.Click += ButtonDelObject_Click; deleteObjectButton.Click += ButtonDelObject_Click;
// //
// toolsGroupBox // groupBox1
// //
toolsGroupBox.Controls.Add(objectsLabel); groupBox1.Controls.Add(label2);
toolsGroupBox.Controls.Add(refreshObjectsButton); groupBox1.Controls.Add(refreshObjectsButton);
toolsGroupBox.Controls.Add(deleteTankButton); groupBox1.Controls.Add(deleteTankButton);
toolsGroupBox.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(maskedTextBoxNumber);
toolsGroupBox.Controls.Add(deleteObjectButton); groupBox1.Controls.Add(deleteObjectButton);
toolsGroupBox.Controls.Add(addTankButton); groupBox1.Controls.Add(addTankButton);
toolsGroupBox.Controls.Add(textBoxStorageName); groupBox1.Controls.Add(textBoxStorageName);
toolsGroupBox.Controls.Add(listBoxStorages); groupBox1.Controls.Add(listBoxStorages);
toolsGroupBox.Controls.Add(addObjectButton); groupBox1.Controls.Add(addObjectButton);
toolsGroupBox.Location = new Point(775, 32); groupBox1.Location = new Point(775, 32);
toolsGroupBox.Name = "toolsGroupBox"; groupBox1.Name = "groupBox1";
toolsGroupBox.Size = new Size(154, 472); groupBox1.Size = new Size(154, 472);
toolsGroupBox.TabIndex = 13; groupBox1.TabIndex = 13;
toolsGroupBox.TabStop = false; groupBox1.TabStop = false;
toolsGroupBox.Text = "Инструменты"; groupBox1.Text = "Инструменты";
// //
// menuStrip // menuStrip
// //
@ -204,15 +204,15 @@
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(935, 516); ClientSize = new Size(935, 516);
Controls.Add(toolsGroupBox); Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Name = "FormTankCollection"; Name = "FormTankCollection";
Text = "Набор танков"; Text = "Набор танков";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
toolsGroupBox.ResumeLayout(false); groupBox1.ResumeLayout(false);
toolsGroupBox.PerformLayout(); groupBox1.PerformLayout();
menuStrip.ResumeLayout(false); menuStrip.ResumeLayout(false);
menuStrip.PerformLayout(); menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
@ -226,12 +226,12 @@
private Button deleteTankButton; private Button deleteTankButton;
private Button addTankButton; private Button addTankButton;
private TextBox maskedTextBoxNumber; private TextBox maskedTextBoxNumber;
private Label objectsLabel; private Label label2;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private Button addObjectButton; private Button addObjectButton;
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Button deleteObjectButton; private Button deleteObjectButton;
private GroupBox toolsGroupBox; private GroupBox groupBox1;
private MenuStrip menuStrip; private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem; private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;

View File

@ -2,6 +2,10 @@
using ProjectTank.Generics; using ProjectTank.Generics;
using ProjectTank.MovementStrategy; using ProjectTank.MovementStrategy;
using System.Windows.Forms; using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using ProjectTank.Exceptions;
using Serilog;
using Log = Serilog.Log;
namespace ProjectTank namespace ProjectTank
{ {
@ -22,17 +26,18 @@ namespace ProjectTank
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i]);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{ {
listBoxStorages.SelectedIndex = 0; listBoxStorages.SelectedIndex = 0;
} }
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count) else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{ {
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
} }
@ -48,6 +53,7 @@ namespace ProjectTank
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
@ -66,9 +72,10 @@ namespace ProjectTank
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Log.Information($"Удален набор: {name}");
} }
} }
@ -87,15 +94,18 @@ namespace ProjectTank
form.Show(); form.Show();
Action<DrawningTankBase>? tankDelegate = new((t) => Action<DrawningTankBase>? tankDelegate = new((t) =>
{ {
if (obj + t) try
{ {
bool q = (obj + t);
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowTanks(); pictureBoxCollection.Image = obj.ShowTanks();
t.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); t.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
@ -120,13 +130,25 @@ namespace ProjectTank
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTanks(); pictureBoxCollection.Image = obj.ShowTanks();
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
}
catch (TankNotFoundException exception)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(exception.Message);
}
catch (FormatException ex)
{
Log.Warning("Было введено не-число при удалении объекта из набора");
MessageBox.Show("Введите число");
} }
else MessageBox.Show("Не удалось удалить объект");
} }
/// <summary> /// <summary>
@ -148,14 +170,17 @@ namespace ProjectTank
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch (Exception exception)
{ {
MessageBox.Show("Не сохранилось", "Результат", Log.Warning("Не удалось сохранить файл");
MessageBox.Show($"Не сохранилось: {exception.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -169,18 +194,21 @@ namespace ProjectTank
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }
} }
else catch (Exception exception)
{ {
MessageBox.Show("Не загрузилось", "Результат", Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {exception.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -143,7 +143,7 @@
// //
// orangePanel // orangePanel
// //
orangePanel.BackColor = Color.FromArgb(255, 128, 0); orangePanel.BackColor = Color.DarkOrange;
orangePanel.Location = new Point(78, 84); orangePanel.Location = new Point(78, 84);
orangePanel.Name = "orangePanel"; orangePanel.Name = "orangePanel";
orangePanel.Size = new Size(49, 48); orangePanel.Size = new Size(49, 48);
@ -183,7 +183,7 @@
// //
// yellowPanel // yellowPanel
// //
yellowPanel.BackColor = Color.FromArgb(255, 255, 128); yellowPanel.BackColor = Color.Gold;
yellowPanel.Location = new Point(12, 26); yellowPanel.Location = new Point(12, 26);
yellowPanel.Name = "yellowPanel"; yellowPanel.Name = "yellowPanel";
yellowPanel.Size = new Size(49, 48); yellowPanel.Size = new Size(49, 48);

View File

@ -1,3 +1,5 @@
using ProjectTank.Exceptions;
namespace ProjectTank.Generics namespace ProjectTank.Generics
{ {
/// <summary> /// <summary>
@ -28,23 +30,27 @@ namespace ProjectTank.Generics
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
/// </summary> /// </summary>
/// <param name="tank">Добавляемый автомобиль</param> /// <param name="tank">Добавляемый танк</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T tank) public bool Insert(T tank)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
return false; throw new StorageOverflowException(_maxCount);
return Insert(tank, 0);
Insert(tank, 0);
return true;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
/// </summary> /// </summary>
/// <param name="tank">Добавляемый автомобиль</param> /// <param name="tank">Добавляемый танк</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T tank, int position) public bool Insert(T tank, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false; return false;
_places.Insert(position, tank); _places.Insert(position, tank);
return true; return true;
@ -57,7 +63,7 @@ namespace ProjectTank.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
if (!(position >= 0 && position < Count)) if (!(position >= 0 && position < Count))
return false; throw new TankNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -4,7 +4,7 @@ using ProjectTank.MovementStrategy;
namespace ProjectTank.Generics namespace ProjectTank.Generics
{ {
/// <summary> /// <summary>
/// Параметризованный класс для набора объектов DrawningCar /// Параметризованный класс для набора объектов DrawningTankBase
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam> /// <typeparam name="U"></typeparam>
@ -70,14 +70,9 @@ namespace ProjectTank.Generics
pos) pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos); collect._collection.Remove(pos);
}
return obj; return obj;
} }
/// <summary> /// <summary>
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject
/// </summary> /// </summary>

View File

@ -107,9 +107,10 @@ namespace ProjectTank.Generics
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
string toWrite = $"TanksStorage{Environment.NewLine}{data}"; string toWrite = $"TanksStorage{Environment.NewLine}{data}";
@ -134,7 +135,7 @@ namespace ProjectTank.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new IOException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
@ -143,11 +144,13 @@ namespace ProjectTank.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("TanksStorage")) if (!strs[0].StartsWith("TanksStorage"))
{ {
return false; //если нет такой записи, то это не те данные
throw new IOException("Неверный формат данных");
} }
_tankStorages.Clear(); _tankStorages.Clear();
@ -161,7 +164,8 @@ namespace ProjectTank.Generics
continue; continue;
} }
TanksGenericCollection<DrawningTankBase, DrawningObjectTank> collection = new(_pictureWidth, _pictureHeight); TanksGenericCollection<DrawningTankBase, DrawningObjectTank> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
DrawningTankBase? tank = DrawningTankBase? tank =

View File

@ -1,3 +1,18 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Log = Serilog.Log;
namespace ProjectTank namespace ProjectTank
{ {
internal static class Program internal static class Program
@ -8,9 +23,13 @@ namespace ProjectTank
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, Log.Logger = new LoggerConfiguration()
// see https://aka.ms/applicationconfiguration. .WriteTo.File("log.txt")
ApplicationConfiguration.Initialize(); .MinimumLevel.Debug()
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormTankCollection()); Application.Run(new FormTankCollection());
} }
} }

View File

@ -8,4 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project> </Project>