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

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

View File

@ -4,7 +4,7 @@ using ProjectLainer.DrawningObjects;
namespace ProjectLainer.Generics namespace ProjectLainer.Generics
{ {
internal class LainersGenericCollection<T, U> internal class LainersGenericCollection<T, U>
where T : DrawingEntity where T : DrawingLainer
where U : IMoveableObject where U : IMoveableObject
{ {
private readonly int _pictureWidth; private readonly int _pictureWidth;
@ -12,6 +12,7 @@ namespace ProjectLainer.Generics
private readonly int _placeSizeWidth = 210; private readonly int _placeSizeWidth = 210;
private readonly int _placeSizeHeight = 90; private readonly int _placeSizeHeight = 90;
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetLainers => _collection.GetLainers();
public LainersGenericCollection(int picWidth, int picHeight) public LainersGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@ -23,16 +24,16 @@ namespace ProjectLainer.Generics
public static bool operator +(LainersGenericCollection<T, U> collect, T? obj) public static bool operator +(LainersGenericCollection<T, U> collect, T? obj)
{ {
if (obj != null && collect != null) if (obj != null && collect != null)
return collect._collection.Insert(obj); {
collect._collection.Insert(obj);
return true;
}
return false; return false;
} }
public static T? operator -(LainersGenericCollection<T, U> collect, int pos) public static T? operator -(LainersGenericCollection<T, U> collect, int pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null) collect._collection.Remove(pos);
{
collect._collection.Remove(pos);
}
return obj; return obj;
} }
public U? GetU(int pos) public U? GetU(int pos)
@ -74,8 +75,6 @@ namespace ProjectLainer.Generics
lainer.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight); lainer.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight);
lainer.DrawTransport(g); lainer.DrawTransport(g);
} }
i++; 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,16 +1,18 @@
using ProjectLainer.DrawningObjects; using ProjectLainer.DrawningObjects;
using ProjectLainer.MovementStrategy; using ProjectLainer.MovementStrategy;
using System.Text;
namespace ProjectLainer.Generics namespace ProjectLainer.Generics
{ {
internal class LainersGenericStorage internal class LainersGenericStorage
{ {
readonly Dictionary<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> _lainerStorages; readonly Dictionary<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> _lainerStorages;
public List<string> Keys => _lainerStorages.Keys.ToList(); public List<string> Keys => _lainerStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
public LainersGenericStorage(int pictureWidth, int pictureHeight) public LainersGenericStorage(int pictureWidth, int pictureHeight)
{ {
@ -18,22 +20,21 @@ namespace ProjectLainer.Generics
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
public void AddSet(string name) public void AddSet(string name)
{ {
_lainerStorages.Add(name, new LainersGenericCollection<DrawingEntity, DrawningObjectLainer>(_pictureWidth, _pictureHeight)); _lainerStorages.Add(name, new LainersGenericCollection<DrawingEntity, DrawningObjectLainer>(_pictureWidth, _pictureHeight));
} }
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_lainerStorages.ContainsKey(name)) if (!_lainerStorages.ContainsKey(name))
{ {
return; return;
} }
_lainerStorages.Remove(name); _lainerStorages.Remove(name);
} }
public LainersGenericCollection<DrawingEntity, DrawningObjectLainer>? this[string ind] public LainersGenericCollection<DrawingEntity, DrawningObjectLainer>? this[string ind]
{ {
get get
@ -48,18 +49,17 @@ namespace ProjectLainer.Generics
private static readonly char _separatorForKeyValue = '|'; private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';'; private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':'; private static readonly char _separatorForObject = ':';
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, LainersGenericCollection<DrawingLainer, DrawningObjectLainer>> record in _lainerStorages) foreach (KeyValuePair<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> record in _lainerStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingLainer? elem in record.Value.GetLainers) foreach (DrawingEntity? elem in record.Value.GetLainers)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
@ -67,19 +67,18 @@ namespace ProjectLainer.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new ArgumentException("Невалиданя операция, нет данных для сохранения");
} }
using (StreamWriter sw = new(filename)) using (StreamWriter sw = new(filename))
{ {
sw.WriteLine($"LainerStorage{Environment.NewLine}{data}"); sw.WriteLine($"LainerStorage{Environment.NewLine}{data}");
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new NullReferenceException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -87,31 +86,32 @@ namespace ProjectLainer.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new NullReferenceException("нет данных для загрузки");
} }
if (!strs[0].StartsWith("LainerStorage")) if (!strs[0].StartsWith("LainerStorage"))
{ {
return false; throw new ArgumentException("неверный фориат данных");
} }
_lainerStorages.Clear(); _lainerStorages.Clear();
do do
{ {
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 1) if (record.Length != 2)
{ {
str = sr.ReadLine(); str = sr.ReadLine();
continue; continue;
} }
LainersGenericCollection<DrawingLainer, DrawningObjectLainer> collection = new(_pictureWidth, _pictureHeight); LainersGenericCollection<DrawingEntity, DrawningObjectLainer> 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)
{ {
DrawingLainer? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight); DrawingEntity? lainer = elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight);
if (lainer != null) if (lainer != null)
{ {
if (!(collection + lainer)) if (!(collection + lainer))
{ {
return false; throw new IOException("Ошибка добавления в коллекцию");
} }
} }
} }
@ -119,7 +119,6 @@ namespace ProjectLainer.Generics
str = sr.ReadLine(); str = sr.ReadLine();
} while (str != null); } 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) { }
}
}