думаю это самая завершенная лаба 7
This commit is contained in:
parent
3264a8ed5d
commit
90437759da
@ -8,6 +8,16 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" 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" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
|
22
AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs
Normal file
22
AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace AircraftCarrier.Exceptions
|
||||||
|
{
|
||||||
|
[Serializable]
|
||||||
|
internal class AircraftNotFoundException : ApplicationException
|
||||||
|
{
|
||||||
|
public AircraftNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||||
|
public AircraftNotFoundException() : base() { }
|
||||||
|
public AircraftNotFoundException(string message) : base(message) { }
|
||||||
|
public AircraftNotFoundException(string message, Exception exception) :
|
||||||
|
base(message, exception)
|
||||||
|
{ }
|
||||||
|
protected AircraftNotFoundException(SerializationInfo info,
|
||||||
|
StreamingContext contex) : base(info, contex) { }
|
||||||
|
}
|
||||||
|
}
|
@ -64,7 +64,7 @@ namespace AircraftCarrier.Generics
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Сохранение информации по автомобилям в хранилище в файл
|
/// Сохранение информации по автомобилям в хранилище в файл
|
||||||
public bool SaveData(string filename)
|
public void SaveData(string filename)
|
||||||
{
|
{
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
@ -83,56 +83,69 @@ namespace AircraftCarrier.Generics
|
|||||||
}
|
}
|
||||||
if (data.Length == 0)
|
if (data.Length == 0)
|
||||||
{
|
{
|
||||||
return false;
|
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||||
}
|
}
|
||||||
using StreamWriter sw = new(filename);
|
using FileStream fs = new(filename, FileMode.Create);
|
||||||
sw.Write($"AircraftStorage{Environment.NewLine}{data}");
|
byte[] info = new
|
||||||
return true;
|
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
|
||||||
|
fs.Write(info, 0, info.Length);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
/// Загрузка информации по автомобилям в хранилище из файла
|
/// Загрузка информации по автомобилям в хранилище из файла
|
||||||
public bool LoadData(string filename)
|
public void LoadData(string filename)
|
||||||
{
|
{
|
||||||
if (!File.Exists(filename))
|
if (!File.Exists(filename))
|
||||||
{
|
{
|
||||||
return false;
|
throw new FileNotFoundException("Файл не найден");
|
||||||
}
|
}
|
||||||
using (StreamReader sr = new(filename))
|
string bufferTextFromFile = "";
|
||||||
|
using (FileStream fs = new(filename, FileMode.Open))
|
||||||
{
|
{
|
||||||
string str = sr.ReadLine();
|
byte[] b = new byte[fs.Length];
|
||||||
if (str == null || str.Length == 0)
|
UTF8Encoding temp = new(true);
|
||||||
|
while (fs.Read(b, 0, b.Length) > 0)
|
||||||
{
|
{
|
||||||
return false;
|
bufferTextFromFile += temp.GetString(b);
|
||||||
}
|
}
|
||||||
if (!str.StartsWith("AircraftStorage"))
|
}
|
||||||
|
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||||
|
StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (strs == null || strs.Length == 0)
|
||||||
|
{
|
||||||
|
throw new FileNotFoundException("Нет данных для загрузки");
|
||||||
|
}
|
||||||
|
if (!strs[0].StartsWith("CarStorage"))
|
||||||
{
|
{
|
||||||
//если нет такой записи, то это не те данные
|
//если нет такой записи, то это не те данные
|
||||||
return false;
|
throw new FileNotFoundException("Неверный формат данных");
|
||||||
}
|
}
|
||||||
_AircraftStorages.Clear();
|
_AircraftStorages.Clear();
|
||||||
while ((str = sr.ReadLine()) != null)
|
foreach (string data in strs)
|
||||||
{
|
{
|
||||||
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
string[] record = data.Split(_separatorForKeyValue,
|
||||||
|
StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (record.Length != 2)
|
if (record.Length != 2)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> collection = new(_pictureWidth, _pictureHeight);
|
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft>
|
||||||
|
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.Reverse())
|
foreach (string elem in set)
|
||||||
{
|
{
|
||||||
DrawningAircraft? aircraft = elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
|
DrawningAircraft? aircraft =
|
||||||
|
elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||||
if (aircraft != null)
|
if (aircraft != null)
|
||||||
{
|
{
|
||||||
if (collection + aircraft == -1)
|
if (collection + aircraft == -1)
|
||||||
{
|
{
|
||||||
return false;
|
throw new ApplicationException("Ошибка добавления в коллекцию");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_AircraftStorages.Add(record[0], collection);
|
_AircraftStorages.Add(record[0], collection);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
20
AircraftCarrier/AircraftCarrier/AppSettings.json
Normal file
20
AircraftCarrier/AircraftCarrier/AppSettings.json
Normal 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": "Aircraft"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -10,15 +10,21 @@ using System.Windows.Forms;
|
|||||||
using AircraftCarrier.DrawningObjects;
|
using AircraftCarrier.DrawningObjects;
|
||||||
using AircraftCarrier.Generics;
|
using AircraftCarrier.Generics;
|
||||||
using AircraftCarrier.MovementStrategy;
|
using AircraftCarrier.MovementStrategy;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using AircraftCarrier.Exceptions;
|
||||||
|
|
||||||
namespace AircraftCarrier
|
namespace AircraftCarrier
|
||||||
{
|
{
|
||||||
public partial class FormAircraftCollection : Form
|
public partial class FormAircraftCollection : Form
|
||||||
{
|
{
|
||||||
private readonly AircraftsGenericStorage _storage;
|
private readonly AircraftsGenericStorage _storage;
|
||||||
public FormAircraftCollection()
|
private readonly ILogger _logger;
|
||||||
|
public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_storage = new AircraftsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
_storage = new AircraftsGenericStorage(pictureBoxCollection.Width,
|
||||||
|
pictureBoxCollection.Height);
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
/// Заполнение listBoxObjects
|
/// Заполнение listBoxObjects
|
||||||
private void ReloadObjects()
|
private void ReloadObjects()
|
||||||
@ -43,10 +49,12 @@ namespace AircraftCarrier
|
|||||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning("Неудачная попытка добавить набор: заполнены не все данные");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_storage.AddSet(textBoxStorageName.Text);
|
_storage.AddSet(textBoxStorageName.Text);
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Набор добавлен: {textBoxStorageName.Text}");
|
||||||
}
|
}
|
||||||
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
|
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
@ -56,20 +64,23 @@ namespace AircraftCarrier
|
|||||||
{
|
{
|
||||||
if (listBoxStorage.SelectedIndex == -1)
|
if (listBoxStorage.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning($"Неудачная попытка удалить набор: набор не выбран");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show($"Удалить объект{listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
|
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
|
||||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
|
||||||
|
if (MessageBox.Show($"Удалить набор {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||||
{
|
{
|
||||||
_storage.DelSet(listBoxStorage.SelectedItem.ToString()
|
_storage.DelSet(name);
|
||||||
?? string.Empty);
|
|
||||||
ReloadObjects();
|
ReloadObjects();
|
||||||
|
_logger.LogInformation($"Удаленный набор: {name}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void ButtonAddAircraft_Click(object sender, EventArgs e)
|
private void ButtonAddAircraft_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (listBoxStorage.SelectedIndex == -1)
|
if (listBoxStorage.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning($"Неудачная попытка добавить объект: набор не выбран");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var formMonorailConfig = new FormAircraftConfig();
|
var formMonorailConfig = new FormAircraftConfig();
|
||||||
@ -87,44 +98,64 @@ namespace AircraftCarrier
|
|||||||
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
|
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning($"Неудачная попытка добавить объект: значение set равно null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
if (obj + aircraft != -1)
|
if (obj + aircraft != -1)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Добавленный объект");
|
||||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||||
|
_logger.LogInformation($"Добавленный объект {aircraft}");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Неудачная попытка добавить объект");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(ApplicationException ex)
|
||||||
|
{
|
||||||
|
MessageBox.Show(ex.Message);
|
||||||
|
_logger.LogWarning($"Неудачная попытка добавить объект: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void ButtonRemoveAircraft_Click(object sender, EventArgs e)
|
private void ButtonRemoveAircraft_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (listBoxStorage.SelectedIndex == -1)
|
if (listBoxStorage.SelectedIndex == -1)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning($"Неудачная попытка удалить объект: набор не выбран");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var obj = _storage[listBoxStorage.SelectedItem.ToString() ??
|
var obj = _storage[listBoxStorage.SelectedItem.ToString() ??
|
||||||
string.Empty];
|
string.Empty];
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning($"Неудачная попытка удалить объект: значение set равно null");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pos = Convert.ToInt32(MaskedTextBoxNumber.Text);
|
int pos = Convert.ToInt32(MaskedTextBoxNumber.Text);
|
||||||
if (obj - pos != null)
|
try
|
||||||
|
{
|
||||||
|
if (obj - pos)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удален");
|
MessageBox.Show("Объект удален");
|
||||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||||
|
_logger.LogInformation($"Удаленный объект на месте: {pos}");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Неудачная попытка удалить объект");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (AircraftNotFoundException 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)
|
||||||
@ -146,36 +177,41 @@ namespace AircraftCarrier
|
|||||||
{
|
{
|
||||||
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);
|
||||||
|
_logger.LogInformation($"Файл успешно сохранен {saveFileDialog.FileName}");
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не сохранилось", "Результат",
|
MessageBox.Show($"Сохранить не удалось: {ex.Message}", "Результат",
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
_logger.LogWarning($"Не удалось сохранить файл: {ex.Message}");
|
||||||
}
|
|
||||||
}
|
|
||||||
/// Обработка нажатия "Загрузка"
|
|
||||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
|
||||||
{
|
|
||||||
if (_storage.LoadData(openFileDialog.FileName))
|
|
||||||
{
|
|
||||||
MessageBox.Show("Загрузка прошла успешно",
|
|
||||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
||||||
ReloadObjects();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
MessageBox.Show("Не загрузилось", "Результат",
|
|
||||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
/// Обработка нажатия "Загрузка"
|
||||||
|
private void LoadToolStripMenuItem_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);
|
||||||
|
_logger.LogWarning($"Не удалось загрузить файл: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,8 @@
|
|||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Serilog;
|
||||||
|
|
||||||
namespace AircraftCarrier
|
namespace AircraftCarrier
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -6,10 +11,32 @@ namespace AircraftCarrier
|
|||||||
[STAThread]
|
[STAThread]
|
||||||
static void Main()
|
static void Main()
|
||||||
{
|
{
|
||||||
// To customize application configuration such as set high DPI settings or default font,
|
|
||||||
// see https://aka.ms/applicationconfiguration.
|
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
Application.Run(new FormAircraftCollection());
|
var services = new ServiceCollection();
|
||||||
|
ConfigureServices(services);
|
||||||
|
using (ServiceProvider serviceProvider =
|
||||||
|
services.BuildServiceProvider())
|
||||||
|
{
|
||||||
|
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormAircraftCollection>().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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
@ -1,4 +1,5 @@
|
|||||||
using System;
|
using AircraftCarrier.Exceptions;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@ -28,8 +29,10 @@ namespace AircraftCarrier.Generics
|
|||||||
/// Добавление объекта в набор на конкретную позицию
|
/// Добавление объекта в набор на конкретную позицию
|
||||||
public int Insert(T Aircraft, int position)
|
public int Insert(T Aircraft, int position)
|
||||||
{
|
{
|
||||||
if (position < 0 || position > Count || Count >= _maxCount)
|
if (position < 0 || position > Count)
|
||||||
return -1;
|
throw new AircraftNotFoundException("Impossible to insert");
|
||||||
|
if (Count >= _maxCount)
|
||||||
|
throw new StorageOverflowException(_maxCount);
|
||||||
|
|
||||||
_places.Insert(position, Aircraft);
|
_places.Insert(position, Aircraft);
|
||||||
return position;
|
return position;
|
||||||
@ -38,7 +41,7 @@ namespace AircraftCarrier.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 AircraftNotFoundException(position);
|
||||||
_places.RemoveAt(position);
|
_places.RemoveAt(position);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
21
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal file
21
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal 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 AircraftCarrier
|
||||||
|
{
|
||||||
|
[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) { }
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user