Лабораторная 7

This commit is contained in:
evasina2312@gmail.com 2022-12-08 00:18:59 +04:00
parent 005be6f825
commit a72551c597
9 changed files with 190 additions and 75 deletions

View File

@ -70,9 +70,9 @@
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddTank); this.groupBoxTools.Controls.Add(this.buttonAddTank);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(819, 28); this.groupBoxTools.Location = new System.Drawing.Point(799, 28);
this.groupBoxTools.Name = "groupBoxTools"; this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(233, 738); this.groupBoxTools.Size = new System.Drawing.Size(233, 758);
this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false; this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты"; this.groupBoxTools.Text = "Инструменты";
@ -150,7 +150,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::ProjectMachine.Properties.Resources.лево; this.buttonLeft.BackgroundImage = global::ProjectMachine.Properties.Resources.лево;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(69, 683); this.buttonLeft.Location = new System.Drawing.Point(69, 703);
this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(34, 30); this.buttonLeft.Size = new System.Drawing.Size(34, 30);
this.buttonLeft.TabIndex = 13; this.buttonLeft.TabIndex = 13;
@ -163,7 +163,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::ProjectMachine.Properties.Resources.вверх; this.buttonUp.BackgroundImage = global::ProjectMachine.Properties.Resources.вверх;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(105, 647); this.buttonUp.Location = new System.Drawing.Point(105, 667);
this.buttonUp.Name = "buttonUp"; this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(34, 30); this.buttonUp.Size = new System.Drawing.Size(34, 30);
this.buttonUp.TabIndex = 12; this.buttonUp.TabIndex = 12;
@ -176,7 +176,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::ProjectMachine.Properties.Resources.право; this.buttonRight.BackgroundImage = global::ProjectMachine.Properties.Resources.право;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(141, 683); this.buttonRight.Location = new System.Drawing.Point(141, 703);
this.buttonRight.Name = "buttonRight"; this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(34, 30); this.buttonRight.Size = new System.Drawing.Size(34, 30);
this.buttonRight.TabIndex = 11; this.buttonRight.TabIndex = 11;
@ -189,7 +189,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::ProjectMachine.Properties.Resources.вниз; this.buttonDown.BackgroundImage = global::ProjectMachine.Properties.Resources.вниз;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(105, 683); this.buttonDown.Location = new System.Drawing.Point(105, 703);
this.buttonDown.Name = "buttonDown"; this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(34, 30); this.buttonDown.Size = new System.Drawing.Size(34, 30);
this.buttonDown.TabIndex = 10; this.buttonDown.TabIndex = 10;
@ -256,7 +256,7 @@
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 28); this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Name = "pictureBox"; this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(819, 738); this.pictureBox.Size = new System.Drawing.Size(799, 758);
this.pictureBox.TabIndex = 1; this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false; this.pictureBox.TabStop = false;
// //
@ -267,7 +267,7 @@
this.файлToolStripMenuItem}); this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip"; this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1052, 28); this.menuStrip.Size = new System.Drawing.Size(1032, 28);
this.menuStrip.TabIndex = 2; this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1"; this.menuStrip.Text = "menuStrip1";
// //
@ -283,14 +283,14 @@
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26); this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
// //
// LoadToolStripMenuItem // LoadToolStripMenuItem
// //
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26); this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
// //
@ -306,7 +306,7 @@
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1052, 766); this.ClientSize = new System.Drawing.Size(1032, 786);
this.Controls.Add(this.pictureBox); this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools); this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip); this.Controls.Add(this.menuStrip);

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -26,11 +27,16 @@ namespace ProjectMachine
/// </summary> /// </summary>
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetTank() public FormMapWithSetTank(ILogger<FormMapWithSetTank> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@ -70,15 +76,18 @@ namespace ProjectMachine
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Карта была не выбрана" : "Карта была не названа");
return; return;
} }
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
/// <summary> /// <summary>
/// Выбор карты /// Выбор карты
@ -88,6 +97,7 @@ namespace ProjectMachine
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
} }
/// <summary> /// <summary>
/// Удаление карты /// Удаление карты
@ -104,6 +114,7 @@ namespace ProjectMachine
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Была удалена карта под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
} }
} }
@ -119,6 +130,8 @@ namespace ProjectMachine
formTankConfig.Show(); formTankConfig.Show();
} }
private void AddTank(DrawningMachine tank) private void AddTank(DrawningMachine tank)
{
try
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
@ -127,11 +140,20 @@ namespace ProjectMachine
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(tank) != -1) else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(tank) != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект:", tank);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
/// <summary> /// <summary>
@ -154,16 +176,31 @@ namespace ProjectMachine
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{
var deletedTank = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedTank != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@tank}", deletedTank);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
_logger.LogInformation("Не удалось удалить объект по позиции {0}", pos);
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (TankNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary> /// <summary>
/// Вывод набора /// Вывод набора
/// </summary> /// </summary>
@ -230,13 +267,16 @@ namespace ProjectMachine
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
} }
} }
} }
@ -249,14 +289,16 @@ namespace ProjectMachine
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка файла '{0}' прошла успешно", openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось загрузить файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
} }
} }
} }

View File

@ -94,56 +94,44 @@ namespace ProjectMachine
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using (FileStream fs = new(filename, FileMode.Create)) using (StreamWriter f = new(filename))
{ {
WriteToFile($"MapsCollection{Environment.NewLine}", fs); f.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages) foreach (var storage in _mapStorages)
{ {
f.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}");
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка нформации по автомобилям на парковках из файла /// Загрузка нформации по автомобилям на парковках из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
string bufferTextFromFile = ""; using (StreamReader f = new(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; if (!f.ReadLine().Contains("MapsCollection"))
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (!strs[0].Contains("MapsCollection"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
return false; throw new Exception("Формат данных в файле не правильный");
} }
//очищаем записи //очищаем записи
_mapStorages.Clear(); _mapStorages.Clear();
for (int i = 1; i < strs.Length; ++i) while (!f.EndOfStream)
{ {
var elem = strs[i].Split(separatorDict); var elem = f.ReadLine().Split(separatorDict);
AbstractMap map = null; AbstractMap map = null;
switch (elem[1]) switch (elem[1])
{ {
@ -154,11 +142,10 @@ namespace ProjectMachine
map = new TownMap(); map = new TownMap();
break; break;
} }
_mapStorages.Add(elem[0], new _mapStorages.Add(elem[0], new MapWithSetTankGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
MapWithSetTankGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
return true; }
} }
} }
} }

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectMachine namespace ProjectMachine
{ {
internal static class Program internal static class Program
@ -11,7 +15,21 @@ namespace ProjectMachine
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetTank()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetTank>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetTank>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -8,6 +8,23 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -50,6 +50,8 @@ namespace ProjectMachine
/// <returns></returns> /// <returns></returns>
public int Insert(T tank, int position) public int Insert(T tank, int position)
{ {
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return -1; return -1;
_places.Insert(position, tank); _places.Insert(position, tank);
@ -65,6 +67,8 @@ namespace ProjectMachine
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
return null; return null;
var result = _places[position]; var result = _places[position];
if (result == null)
throw new TankNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return result; return result;
} }

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectMachine
{
[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 ProjectMachine
{
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

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>