супер пупер завершенная лаба 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

@ -47,12 +47,8 @@ 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)
{ {

@ -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,43 +98,31 @@ 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("Неверный формат данных"); throw new InvalidDataException("Неверный формат данных");
} }
_AircraftStorages.Clear(); _AircraftStorages.Clear();
foreach (string data in strs) while ((str = sr.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
continue; continue;
} }
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> 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.Reverse())
{ {
DrawningAircraft? aircraft = DrawningAircraft? aircraft = elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
if (aircraft != null) if (aircraft != null)
{ {
if (collection + aircraft == -1) if (collection + aircraft == -1)
@ -145,7 +133,10 @@ namespace AircraftCarrier.Generics
} }
_AircraftStorages.Add(record[0], collection); _AircraftStorages.Add(record[0], collection);
} }
}
}
} }
} }
}

@ -174,42 +174,40 @@ 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); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл успешно сохранен {saveFileDialog.FileName}"); _logger.LogInformation($"File saved successfully: {saveFileDialog.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 saving failed: {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}");
} }
} }
} }