Генерация ошибок

This commit is contained in:
devil_1nc 2022-11-19 20:07:56 +04:00
parent 88dcfeef92
commit d583f3c9af
5 changed files with 104 additions and 48 deletions

View File

@ -120,15 +120,27 @@ namespace ProjectPlane
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{ {
MessageBox.Show("Object removed"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); {
MessageBox.Show("Object removed");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Error with object removing");
}
} }
else catch(PlaneNotFoundException ex)
{ {
MessageBox.Show("Error with object removing"); MessageBox.Show($"Ошибка удаления: {ex.Message}");
} }
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
} }
/// <summary> /// <summary>
/// Вывод набора /// Вывод набора
@ -235,16 +247,19 @@ namespace ProjectPlane
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Succesfull loading", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Succesfull loading", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Loading failed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Loading failed {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
} }
@ -252,13 +267,14 @@ namespace ProjectPlane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Succesfull saving", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Succesfull saving", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Savingfailed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Saving failed {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -84,69 +84,69 @@ namespace ProjectPlane
byte[] info = new UTF8Encoding(true).GetBytes(text); byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length); stream.Write(info, 0, info.Length);
} }
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 (FileStream fs = new(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{ {
WriteToFile($"MapsCollection{Environment.NewLine}", fs); sw.WriteLine("MapsCollection");
foreach (var storage in _mapStorages) foreach (var storage in _mapStorages)
{ {
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs);
sw.WriteLine(
$"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"
);
} }
} }
return true; 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 Exception("File not found");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{ {
byte[] b = new byte[fs.Length]; string curLine = sr.ReadLine();
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0) if (!curLine.Contains("MapsCollection"))
{ {
bufferTextFromFile += temp.GetString(b); throw new Exception("Incorrect format");
} }
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); _mapStorages.Clear();
if (!strs[0].Contains("MapsCollection")) while ((curLine = sr.ReadLine()) != null)
{
//если нет такой записи, то это не те данные
return false;
}
//очищаем записи
_mapStorages.Clear();
for (int i = 1; i < strs.Length; ++i)
{
var elem = strs[i].Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{ {
case "SimpleMap": var elem = curLine.Split(separatorDict);
map = new SimpleMap(); AbstractMap map = null;
break; switch (elem[1])
case "SkyMap": {
map = new SkyMap(); case "SimpleMap":
break; map = new SimpleMap();
break;
case "SkyMap":
map = new SkyMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetPlanesGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
_mapStorages.Add(elem[0], new MapWithSetPlanesGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
return true;
} }
} }
} }

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectPlane
{
internal class PlaneNotFoundException : ApplicationException
{
public PlaneNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public PlaneNotFoundException() : base() { }
public PlaneNotFoundException(string message) : base(message) { }
public PlaneNotFoundException(string message, Exception exception) : base(message, exception)
{ }
protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -43,7 +43,7 @@ namespace ProjectPlane
/// <returns></returns> /// <returns></returns>
public int Insert(T plane, int position) public int Insert(T plane, int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, plane); _places.Insert(position, plane);
return position; return position;
} }
@ -54,7 +54,7 @@ namespace ProjectPlane
/// <returns></returns> /// <returns></returns>
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _maxCount) return null; if (position < 0 || position >= _maxCount) throw new PlaneNotFoundException(position);
T temp = _places[position]; T temp = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);
return temp; return temp;

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectPlane
{
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) { }
}
}