супер пупер завершенная лаба 7

This commit is contained in:
Extrimal 2023-12-12 18:38:26 +03:00
parent 90437759da
commit 57e628eca5
3 changed files with 48 additions and 63 deletions

View File

@ -47,11 +47,7 @@ namespace AircraftCarrier.Generics
public static bool operator -(AircraftsGenericCollection<T, U> collect, int pos) public static bool operator -(AircraftsGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null) return collect._collection.Remove(pos);
{
return collect._collection.Remove(pos);
}
return false;
} }
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject
public U? GetU(int pos) public U? GetU(int pos)

View File

@ -87,7 +87,7 @@ namespace AircraftCarrier.Generics
} }
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
byte[] info = new byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}"); UTF8Encoding(true).GetBytes($"AircraftStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length); fs.Write(info, 0, info.Length);
return; return;
} }
@ -98,54 +98,45 @@ namespace AircraftCarrier.Generics
{ {
throw new FileNotFoundException("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
string bufferTextFromFile = ""; using (StreamReader sr = new(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string str = sr.ReadLine();
UTF8Encoding temp = new(true); if (str == null || str.Length == 0)
while (fs.Read(b, 0, b.Length) > 0)
{ {
bufferTextFromFile += temp.GetString(b); throw new NullReferenceException("Нет данных для загрузки");
} }
} 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"))
{
//если нет такой записи, то это не те данные
throw new FileNotFoundException("Неверный формат данных");
}
_AircraftStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{ {
continue; //если нет такой записи, то это не те данные
throw new InvalidDataException("Неверный формат данных");
} }
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> _AircraftStorages.Clear();
collection = new(_pictureWidth, _pictureHeight); while ((str = sr.ReadLine()) != null)
string[] set = record[1].Split(_separatorRecords,StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{ {
DrawningAircraft? aircraft = string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight); if (record.Length != 2)
if (aircraft != null)
{ {
if (collection + aircraft == -1) continue;
}
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{
DrawningAircraft? aircraft = elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
if (aircraft != null)
{ {
throw new ApplicationException("Ошибка добавления в коллекцию"); if (collection + aircraft == -1)
{
throw new ApplicationException("Ошибка добавления в коллекцию");
}
} }
} }
_AircraftStorages.Add(record[0], collection);
} }
_AircraftStorages.Add(record[0], collection);
} }
} }
} }
} }

View File

@ -149,7 +149,7 @@ namespace AircraftCarrier
} }
else else
{ {
MessageBox.Show("Неудачная попытка удалить объект"); MessageBox.Show("Неудачная попытка удалить объект");
} }
} }
catch (AircraftNotFoundException ex) catch (AircraftNotFoundException ex)
@ -175,41 +175,39 @@ namespace AircraftCarrier
/// Обработка нажатия "Сохранение" /// Обработка нажатия "Сохранение"
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) try
{ {
try _storage.SaveData(saveFileDialog.FileName);
{ MessageBox.Show("Сохранение прошло успешно",
_storage.SaveData(saveFileDialog.FileName); "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Сохранение прошло успешно", _logger.LogInformation($"File saved successfully: {saveFileDialog.FileName}");
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); }
_logger.LogInformation($"Файл успешно сохранен {saveFileDialog.FileName}"); catch (Exception ex)
} {
catch (Exception ex) MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
{ MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Сохранить не удалось: {ex.Message}", "Результат", _logger.LogWarning($"File saving failed: {ex.Message}");
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить файл: {ex.Message}");
}
} }
} }
/// Обработка нажатия "Загрузка" /// Обработка нажатия "Загрузка"
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try try
{ {
_storage.SaveData(saveFileDialog.FileName); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл успешно сохранен: {saveFileDialog.FileName}"); ReloadObjects();
_logger.LogInformation($"File loaded successfully: {openFileDialog.FileName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Сбой загрузки: {ex.Message}", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить файл: {ex.Message}"); _logger.LogWarning($"File loading failed: {ex.Message}");
} }
} }
} }