лаба 7, я так полагаю, возможно, кто знает, не уверена, готовая лаба

This commit is contained in:
a.puchkina 2023-12-19 22:59:17 +04:00
parent e016aa1b8e
commit d177de49ad
5 changed files with 77 additions and 81 deletions

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.Exceptoins; using AirplaneWithRadar.Exceptoins;
using System.Numerics;
namespace AirplaneWithRadar.Generics namespace AirplaneWithRadar.Generics
{ {
@ -115,7 +116,7 @@ namespace AirplaneWithRadar.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new ArgumentException("Невалиданя операция, нет данных для сохранения"); throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
@ -132,62 +133,47 @@ namespace AirplaneWithRadar.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не найден"); throw new FileNotFoundException($"Файл {filename} не найден");
} }
string bufferTextFromFile = "";
using (StreamReader reader = new StreamReader(filename))
{
string str;
while ((str = reader.ReadLine()) != null)
{
bufferTextFromFile += str + '\r' + '\n';
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new ArgumentException("Нет данных для загрузки");
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("AirplaneStorage")) if (!str.StartsWith("AirplaneStorage"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
throw new InvalidDataException("Неверный формат данных"); throw new FormatException("Неверный формат данных");
} }
_airplaneStorages.Clear(); _airplaneStorages.Clear();
foreach (string data in strs) string strs = "";
while ((strs = fs.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, if (strs == null)
StringSplitOptions.RemoveEmptyEntries); {
throw new NullReferenceException("Нет данных для загрузки");
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
continue; continue;
} }
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = new(_pictureWidth, _pictureHeight);
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)
{ {
DrawningAirplane? airplane = DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null) if (airplane != null)
{ {
if (!(collection + airplane)) if (!(collection + airplane))
{ {
try throw new InvalidOperationException("Ошибка добавления в коллекцию");
{
_ = collection + airplane;
}
catch (AirplaneNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
} }
} }
} }
@ -196,3 +182,4 @@ namespace AirplaneWithRadar.Generics
} }
} }
} }
}

View File

@ -185,14 +185,14 @@
// сохранениеToolStripMenuItem // сохранениеToolStripMenuItem
// //
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(180, 22); сохранениеToolStripMenuItem.Size = new Size(141, 22);
сохранениеToolStripMenuItem.Text = "Сохранение"; сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// загрузкаToolStripMenuItem // загрузкаToolStripMenuItem
// //
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem"; загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(180, 22); загрузкаToolStripMenuItem.Size = new Size(141, 22);
загрузкаToolStripMenuItem.Text = "Загрузка"; загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //
@ -210,6 +210,11 @@
// openFileDialog // openFileDialog
// //
openFileDialog.FileName = "openFileDialog1"; openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
// //
// FormAirplaneCollection // FormAirplaneCollection
// //

View File

@ -84,6 +84,7 @@ namespace AirplaneWithRadar
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла"); _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла");
} }
} }
ReloadObjects();
} }
/// <summary> /// <summary>
@ -144,6 +145,7 @@ namespace AirplaneWithRadar
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Коллекция не выбрана");
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
@ -164,6 +166,7 @@ namespace AirplaneWithRadar
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Коллекция не выбрана");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -175,31 +178,23 @@ namespace AirplaneWithRadar
var formAirplaneConfig = new FormAirplaneConfig(); var formAirplaneConfig = new FormAirplaneConfig();
formAirplaneConfig.Show(); formAirplaneConfig.Show();
formAirplaneConfig.AddEvent(AddAirplane); Action<DrawningAirplane>? airplaneDelegate = new((m) =>
}
private void AddAirplane(DrawningAirplane airplane)
{ {
if (listBoxStorages.SelectedIndex == -1) bool isAddSuccessful = (obj + m);
if (isAddSuccessful)
{ {
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
_ = obj + airplane;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowAirplanes(); pictureBoxCollection.Image = obj.ShowAirplanes();
_logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); _logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
catch (Exception ex) else
{ {
MessageBox.Show(ex.Message); MessageBox.Show("Набор переполнен! Не удалось добавить объект");
_logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}");
} }
});
formAirplaneConfig.AddEvent(airplaneDelegate);
} }
/// <summary> /// <summary>
@ -222,6 +217,7 @@ namespace AirplaneWithRadar
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
_logger.LogWarning("Отмена удаления объекта");
return; return;
} }
try try
@ -230,13 +226,13 @@ namespace AirplaneWithRadar
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowAirplanes();
_logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}");
pictureBoxCollection.Image = obj.ShowAirplanes();
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
catch (AirplaneNotFoundException ex) catch (AirplaneNotFoundException ex)
@ -244,6 +240,11 @@ namespace AirplaneWithRadar
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); _logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
}
} }
/// <summary> /// <summary>

View File

@ -120,6 +120,9 @@
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value> <value>132, 17</value>
</metadata> </metadata>

View File

@ -75,7 +75,7 @@ namespace AirplaneWithRadar.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position >= Count || position < 0) if (position >= Count || position < 0 || position > _maxCount)
{ {
throw new AirplaneNotFoundException("Невалидная операция"); throw new AirplaneNotFoundException("Невалидная операция");
} }