файлы лабораторной

This commit is contained in:
Ivan_Starostin 2023-12-21 21:20:07 +04:00
parent bd67bd89f4
commit 296d9b1d2a
5 changed files with 136 additions and 61 deletions

View File

@ -1,4 +1,17 @@
using ProjectLainer.DrawningObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using ProjectLainer.DrawningObjects;
using ProjectLainer.Exceptions;
using ProjectLainer.Generics;
using ProjectLainer.MovementStrategy;
@ -7,17 +20,17 @@ namespace ProjectLainer
public partial class FormLainerCollection : Form
{
private readonly LainersGenericStorage _storage;
public FormLainerCollection()
private readonly ILogger _logger;
public FormLainerCollection(ILogger<FormLainerCollection> logger)
{
InitializeComponent();
_storage = new LainersGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_storage = new LainersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
foreach (string key in _storage.Keys)
{
listBoxStorages.Items.Add(key);
@ -41,6 +54,8 @@ namespace ProjectLainer
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
@ -48,11 +63,13 @@ namespace ProjectLainer
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddLainer_Click(object sender, EventArgs e)
@ -76,8 +93,7 @@ namespace ProjectLainer
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
@ -88,14 +104,23 @@ namespace ProjectLainer
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowLainers();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowLainers();
_logger.LogInformation($"удален лайнер из набора :{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (LainerNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning("ошибка лайнер не найден");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -116,7 +141,7 @@ namespace ProjectLainer
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLainers();
}
private void AddLainer(DrawingEntity lainer)
private void AddLainer(DrawingLainer lainer)
{
if (listBoxStorages.SelectedIndex == -1)
{
@ -127,29 +152,37 @@ namespace ProjectLainer
{
return;
}
if (obj + lainer)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowLainers();
if (obj + lainer)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowLainers();
_logger.LogInformation($"добавлен лайнер в набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (OverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning("ошибка переполнения");
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -157,15 +190,16 @@ namespace ProjectLainer
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
}
else
catch (Exception)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

View File

@ -4,7 +4,7 @@ using ProjectLainer.DrawningObjects;
namespace ProjectLainer.Generics
{
internal class LainersGenericCollection<T, U>
where T : DrawingEntity
where T : DrawingLainer
where U : IMoveableObject
{
private readonly int _pictureWidth;
@ -12,6 +12,7 @@ namespace ProjectLainer.Generics
private readonly int _placeSizeWidth = 210;
private readonly int _placeSizeHeight = 90;
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetLainers => _collection.GetLainers();
public LainersGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@ -23,16 +24,16 @@ namespace ProjectLainer.Generics
public static bool operator +(LainersGenericCollection<T, U> collect, T? obj)
{
if (obj != null && collect != null)
return collect._collection.Insert(obj);
{
collect._collection.Insert(obj);
return true;
}
return false;
}
public static T? operator -(LainersGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
@ -74,8 +75,6 @@ namespace ProjectLainer.Generics
lainer.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight);
lainer.DrawTransport(g);
}
i++;
}

View File

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

View File

@ -1,5 +1,7 @@
using ProjectLainer.DrawningObjects;
using ProjectLainer.MovementStrategy;
using System.Text;
namespace ProjectLainer.Generics
{
internal class LainersGenericStorage
@ -30,7 +32,6 @@ namespace ProjectLainer.Generics
{
return;
}
_lainerStorages.Remove(name);
}
@ -48,18 +49,17 @@ namespace ProjectLainer.Generics
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, LainersGenericCollection<DrawingLainer, DrawningObjectLainer>> record in _lainerStorages)
foreach (KeyValuePair<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> record in _lainerStorages)
{
StringBuilder records = new();
foreach (DrawingLainer? elem in record.Value.GetLainers)
foreach (DrawingEntity? elem in record.Value.GetLainers)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
@ -67,19 +67,18 @@ namespace ProjectLainer.Generics
}
if (data.Length == 0)
{
return false;
throw new ArgumentException("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter sw = new(filename))
{
sw.WriteLine($"LainerStorage{Environment.NewLine}{data}");
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new NullReferenceException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@ -87,31 +86,32 @@ namespace ProjectLainer.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new NullReferenceException("нет данных для загрузки");
}
if (!strs[0].StartsWith("LainerStorage"))
{
return false;
throw new ArgumentException("неверный фориат данных");
}
_lainerStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 1)
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
LainersGenericCollection<DrawingLainer, DrawningObjectLainer> collection = new(_pictureWidth, _pictureHeight);
LainersGenericCollection<DrawingEntity, DrawningObjectLainer> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingLainer? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight);
DrawingEntity? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight);
if (lainer != null)
{
if (!(collection + lainer))
{
return false;
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
@ -119,7 +119,6 @@ namespace ProjectLainer.Generics
str = sr.ReadLine();
} while (str != null);
}
return true;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLainer.Exceptions
{
[Serializable]
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) { }
}
}