Лабораторная работа №7

This commit is contained in:
ENDORFIT 2024-04-22 16:17:12 +04:00
parent 5c91dc45fd
commit e2b76217f9
8 changed files with 156 additions and 102 deletions

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ProjectMonorail.Scripts.Exceptions;
using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects; using ProjectMonorail.Scripts.Monorail.CollectionGenericObjects;
using ProjectMonorail.Scripts.Monorail.Drawnings; using ProjectMonorail.Scripts.Monorail.Drawnings;
@ -32,6 +33,7 @@ namespace ProjectMonorail
InitializeComponent(); InitializeComponent();
_storageCollection = new StorageCollection<DrawingMonorail>(); _storageCollection = new StorageCollection<DrawingMonorail>();
_logger = logger; _logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -66,12 +68,13 @@ namespace ProjectMonorail
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
@ -89,12 +92,13 @@ namespace ProjectMonorail
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
} }
} }
catch(Exception ex) catch(Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
@ -153,7 +157,7 @@ namespace ProjectMonorail
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; throw new Exception("Не все данные заполнены");
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
@ -164,24 +168,25 @@ namespace ProjectMonorail
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
collectionType); _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionDelete_Click(object sender, EventArgs e) private void ButtonCollectionDelete_Click(object sender, EventArgs e)
{ {
try { try
{
// TODO прописать логику удаления элемента из коллекции // TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция // нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
@ -193,11 +198,12 @@ namespace ProjectMonorail
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция с название: " + listBoxCollection.SelectedItem.ToString() + " удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
@ -213,14 +219,14 @@ namespace ProjectMonorail
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; throw new Exception("Коллекция не выбрана");
} }
ICollectionGenericObjects<DrawingMonorail>? collection = ICollectionGenericObjects<DrawingMonorail>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; throw new Exception("Коллекция не проинициализирована");
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
@ -233,7 +239,7 @@ namespace ProjectMonorail
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
@ -256,7 +262,7 @@ namespace ProjectMonorail
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка {Message}", ex.Message); LogException(ex);
} }
} }
@ -277,9 +283,37 @@ namespace ProjectMonorail
_logger.LogInformation("Загрузка успешна завершена"); _logger.LogInformation("Загрузка успешна завершена");
} }
} }
catch(Exception ex) catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
LogException(ex);
}
}
private void LogException(Exception ex)
{
if (ex is CollectionOverflowException)
{
_logger.LogError("Ошибка {Message}", ((CollectionOverflowException)ex).Message);
}
else if (ex is FileEmptyException)
{
_logger.LogError("Ошибка {Message}", ((FileEmptyException)ex).Message);
}
else if (ex is FileDoesNotExistException)
{
_logger.LogError("Ошибка {Message}", ((FileDoesNotExistException)ex).Message);
}
else if (ex is ObjectNotFoundException)
{
_logger.LogError("Ошибка {Message}", ((ObjectNotFoundException)ex).Message);
}
else if (ex is PositionOutOfCollectionException)
{
_logger.LogError("Ошибка {Message}", ((PositionOutOfCollectionException)ex).Message);
}
else
{
_logger.LogError("Ошибка {Message}", ex.Message); _logger.LogError("Ошибка {Message}", ex.Message);
} }
} }

@ -24,7 +24,7 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="Configs\nlog.config"> <None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку, что файл пустой
/// </summary>
[Serializable]
public class FileDoesNotExistException : ApplicationException
{
public FileDoesNotExistException() : base() { }
public FileDoesNotExistException(string message) : base(message) { }
public FileDoesNotExistException(string message, Exception exception) : base(message, exception) { }
protected FileDoesNotExistException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Scripts.Exceptions
{
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
public class FileEmptyException : ApplicationException
{
public FileEmptyException() : base() { }
public FileEmptyException(string message) : base(message) { }
public FileEmptyException(string message, Exception exception) : base(message, exception) { }
protected FileEmptyException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

@ -36,7 +36,8 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); //private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => 40;
/// <summary> /// <summary>
/// Конструктор /// Конструктор

@ -60,7 +60,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
if (InsertingElementCollection(i, obj)) return i; if (InsertingElementCollection(i, obj)) return i;
} }
throw new Exception("Превышение лимита Count"); throw new CollectionOverflowException("Превышение лимита Count");
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
@ -83,7 +83,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
if (InsertingElementCollection(i, obj)) return i; if (InsertingElementCollection(i, obj)) return i;
} }
throw new Exception("Нет свободного места для вставки"); throw new CollectionOverflowException("Нет свободного места для вставки");
} }
public T Remove(int position) public T Remove(int position)
@ -91,7 +91,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (!(position >= 0 && position < Count) || _collection[position] == null) throw new PositionOutOfCollectionException(position); if (!(position >= 0 && position < Count) || _collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;

@ -1,5 +1,4 @@
using ProjectMonorail.Scripts.Exceptions; using ProjectMonorail.Scripts.Monorail.Drawnings;
using ProjectMonorail.Scripts.Monorail.Drawnings;
using System.Diagnostics; using System.Diagnostics;
using System.Text; using System.Text;
@ -67,7 +66,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
collection = new MassiveGenericObjects<T>(); collection = new MassiveGenericObjects<T>();
break; break;
default: default:
throw new Exception("Collection Type is not selected: collectionType = " + collectionType); return;
} }
_storages.Add(name, collection); _storages.Add(name, collection);
@ -110,44 +109,45 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new Exception("В хранилище отсутствуют коллекции для сохранения"); throw new Exception("Storage is empty");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder sb = new(); using (StreamWriter writer = new StreamWriter(filename))
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
_storages)
{ {
sb.Append(Environment.NewLine); writer.Write(_collectionKey);
// не сохраняем пустые коллекции foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
if (value.Value.Count == 0)
{ {
continue; StringBuilder stringBuilder = new StringBuilder();
} stringBuilder.Append(Environment.NewLine);
sb.Append(value.Key);
sb.Append(_separatorForKeyValue); if (value.Value.Count == 0)
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{ {
continue; continue;
} }
sb.Append(data);
sb.Append(_separatorItems); stringBuilder.Append(value.Key);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.GetCollectionType);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.MaxCount);
stringBuilder.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
stringBuilder.Append(data);
stringBuilder.Append(_separatorItems);
}
writer.Write(stringBuilder);
} }
} }
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
} }
/// <summary> /// <summary>
@ -159,65 +159,52 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не существует"); throw new Exceptions.FileDoesNotExistException("Файл не существует " + filename);
} }
string bufferTextFromFile = ""; using (StreamReader streamRader = File.OpenText(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string inputString = streamRader.ReadLine();
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey)) if (inputString == null || inputString.Length == 0)
{ {
throw new Exception("В файле неверные данные"); throw new Exceptions.FileEmptyException("Файл пустой " + filename);
} }
_storages.Clear(); if (!inputString.StartsWith(_collectionKey))
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{ {
continue; throw new Exceptions.ObjectNotFoundException();
} }
CollectionType collectionType =
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]); _storages.Clear();
ICollectionGenericObjects<T>? collection = string strs = "";
StorageCollection<T>.CreateCollection(collectionType); while ((strs = streamRader.ReadLine()) != null)
if (collection == null)
{ {
throw new Exception("Не удалось определить тип коллекции: " + record[1]); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
} if (record.Length != 4)
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingMonorail() is T monorail)
{ {
try continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exceptions.ObjectNotFoundException();
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingMonorail() is T ship)
{ {
if (collection.Insert(monorail) == -1) if (collection.Insert(ship) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); {
} throw new Exceptions.PositionOutOfCollectionException();
catch (CollectionOverflowException ex) { }
throw new Exception("Коллекция переполнена", ex);
} }
} }
_storages.Add(record[0], collection);
} }
_storages.Add(record[0], collection);
} }
} }

@ -4,7 +4,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info"> autoReload="true" internalLogLevel="Info">
<targets> <targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" /> <target xsi:type="File" name="tofile" fileName="MonorailLog-${shortdate}.log" />
</targets> </targets>
<rules> <rules>
<logger name="*" minlevel="Debug" writeTo="tofile" /> <logger name="*" minlevel="Debug" writeTo="tofile" />