PIbd-23 Starostin I.K. Lab_8 #10

Closed
Ivan_Starostin wants to merge 5 commits from lab8 into lab7.0
5 changed files with 207 additions and 119 deletions
Showing only changes of commit a8df138423 - Show all commits

View File

@ -43,13 +43,15 @@
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripItem = new ToolStripMenuItem();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(12, 56);
pictureBoxCollection.Location = new Point(29, 48);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(706, 434);
pictureBoxCollection.TabIndex = 0;
@ -57,7 +59,7 @@
//
// ButtonAddLainer
//
ButtonAddLainer.Location = new Point(804, 374);
ButtonAddLainer.Location = new Point(818, 374);
ButtonAddLainer.Name = "ButtonAddLainer";
ButtonAddLainer.Size = new Size(154, 32);
ButtonAddLainer.TabIndex = 1;
@ -67,7 +69,7 @@
//
// ButtonRemove
//
ButtonRemove.Location = new Point(807, 453);
ButtonRemove.Location = new Point(818, 445);
ButtonRemove.Name = "ButtonRemove";
ButtonRemove.Size = new Size(139, 37);
ButtonRemove.TabIndex = 2;
@ -87,14 +89,14 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(812, 412);
maskedTextBoxNumber.Location = new Point(832, 412);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 4;
//
// ButtonAddObject
//
ButtonAddObject.Location = new Point(790, 133);
ButtonAddObject.Location = new Point(802, 81);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(170, 29);
ButtonAddObject.TabIndex = 5;
@ -104,17 +106,16 @@
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(808, 69);
textBoxStorageName.Location = new Point(817, 48);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(125, 27);
textBoxStorageName.TabIndex = 6;
//textBoxStorageName.TextChanged += textBoxStorageName_TextChanged;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(808, 168);
listBoxStorages.Location = new Point(817, 116);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(150, 104);
listBoxStorages.TabIndex = 7;
@ -122,7 +123,7 @@
//
// ButtonDelObject
//
ButtonDelObject.Location = new Point(808, 293);
ButtonDelObject.Location = new Point(818, 226);
ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(138, 29);
ButtonDelObject.TabIndex = 8;
@ -165,11 +166,33 @@
LoadToolStripItem.Text = "загрузка";
LoadToolStripItem.Click += LoadToolStripItem_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(817, 261);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(178, 29);
ButtonSortByType.TabIndex = 13;
ButtonSortByType.Text = "сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(818, 296);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(177, 29);
ButtonSortByColor.TabIndex = 14;
ButtonSortByColor.Text = "сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormLainerCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1027, 551);
Controls.Add(ButtonSortByColor);
Controls.Add(ButtonSortByType);
Controls.Add(menuStrip1);
Controls.Add(ButtonDelObject);
Controls.Add(listBoxStorages);
@ -183,6 +206,7 @@
MainMenuStrip = menuStrip1;
Name = "FormLainerCollection";
Text = "FormLainerCollection";
Load += FormLainerCollection_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
@ -207,5 +231,7 @@
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripItem;
private Button ButtonSortByType;
private Button ButtonSortByColor;
}
}

View File

@ -1,15 +1,4 @@
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 Microsoft.Extensions.Logging;
using ProjectLainer.DrawningObjects;
using ProjectLainer.Exceptions;
using ProjectLainer.Generics;
@ -27,23 +16,25 @@ namespace ProjectLainer
_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)
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(key);
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
@ -57,6 +48,7 @@ namespace ProjectLainer
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -72,6 +64,7 @@ namespace ProjectLainer
_logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddLainer_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -87,6 +80,7 @@ namespace ProjectLainer
formLinerConfig.AddEvent(AddLainer);
formLinerConfig.Show();
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -106,15 +100,11 @@ namespace ProjectLainer
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowLainers();
_logger.LogInformation($"удален лайнер из набора :{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"удален лайнер в набор :{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
}
catch (LainerNotFoundException ex)
@ -123,6 +113,7 @@ namespace ProjectLainer
_logger.LogWarning("ошибка лайнер не найден");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -141,7 +132,7 @@ namespace ProjectLainer
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLainers();
}
private void AddLainer(DrawingLainer lainer)
private void AddLainer(DrawingEntity lainer)
{
if (listBoxStorages.SelectedIndex == -1)
{
@ -160,17 +151,20 @@ namespace ProjectLainer
pictureBoxCollection.Image = obj.ShowLainers();
_logger.LogInformation($"добавлен лайнер в набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (OverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning("ошибка переполнения");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning("ошибка, лайнер не был добавлен, возможно такой объект уже есть");
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
@ -186,6 +180,7 @@ namespace ProjectLainer
}
}
}
private void LoadToolStripItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
@ -205,5 +200,25 @@ namespace ProjectLainer
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareLainers(new LainerCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareLainers(new LainerCompareByColor());
private void CompareLainers(IComparer<DrawingEntity?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowLainers();
}
}
}

View File

@ -1,10 +1,11 @@
using ProjectLainer.MovementStrategy;
using ProjectLainer.DrawningObjects;
using ProjectLainer.Entities;
namespace ProjectLainer.Generics
{
internal class LainersGenericCollection<T, U>
where T : DrawingLainer
where T : DrawingEntity
where U : IMoveableObject
{
private readonly int _pictureWidth;
@ -25,16 +26,14 @@ namespace ProjectLainer.Generics
{
if (obj != null && collect != null)
{
collect._collection.Insert(obj);
return true;
}
DrawiningLainerEqutables equal = new Generics.DrawiningLainerEqutables();
return collect._collection.Insert(obj, equal);
}
return false;
}
public static T? operator -(LainersGenericCollection<T, U> collect, int pos)
public static bool operator -(LainersGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
return collect._collection.Remove(pos);
}
public U? GetU(int pos)
{
@ -71,7 +70,7 @@ namespace ProjectLainer.Generics
{
if (lainer != null)
{
int inRow = _pictureWidth / _placeSizeWidth;
int inRow = _pictureWidth / _placeSizeWidth; //(inRow + 1 + (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight
lainer.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight);
lainer.DrawTransport(g);
@ -79,5 +78,6 @@ namespace ProjectLainer.Generics
i++;
}
}
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
}
}

View File

@ -1,47 +1,65 @@
using ProjectLainer.DrawningObjects;
using ProjectLainer.Entities;
using ProjectLainer.MovementStrategy;
using System.Text;
namespace ProjectLainer.Generics
{
internal class LainersGenericStorage
internal class LainersGenericStorage
{
readonly Dictionary<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> _lainerStorages;
readonly Dictionary<LainersCollectionInfo, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>> _lainerStorages;
public List<string> Keys => _lainerStorages.Keys.ToList();
public List<LainersCollectionInfo> Keys => _lainerStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public LainersGenericStorage(int pictureWidth, int pictureHeight)
{
_lainerStorages = new Dictionary<string, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>>();
_lainerStorages = new Dictionary<LainersCollectionInfo, LainersGenericCollection<DrawingEntity, DrawningObjectLainer>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_lainerStorages.Add(name, new LainersGenericCollection<DrawingEntity, DrawningObjectLainer>(_pictureWidth, _pictureHeight));
//проверка
var addItem = new LainersCollectionInfo(name, null);
foreach(LainersCollectionInfo elem in Keys)
{
if (addItem.Equals(elem))
{
return;
}
}
_lainerStorages.Add(new LainersCollectionInfo(name, null), new LainersGenericCollection<DrawingEntity, DrawningObjectLainer>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_lainerStorages.ContainsKey(name))
var deleteItem = new LainersCollectionInfo(name, null);
foreach (LainersCollectionInfo elem in Keys)
{
return;
if (deleteItem.Equals(elem))
{
_lainerStorages.Remove(elem);
}
}
_lainerStorages.Remove(name);
return;
}
public LainersGenericCollection<DrawingEntity, DrawningObjectLainer>? this[string ind]
{
get
{
if (_lainerStorages.ContainsKey(ind))
var getItem = new LainersCollectionInfo(ind, null);
foreach(LainersCollectionInfo elem in Keys)
{
return _lainerStorages[ind];
if (getItem.Equals(elem))
{
return _lainerStorages[elem];
}
}
return null;
}
@ -56,68 +74,80 @@ namespace ProjectLainer.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, LainersGenericCollection<DrawingLainer, DrawningObjectLainer>> record in _lainerStorages)
foreach (KeyValuePair<LainersCollectionInfo, 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}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new ArgumentException("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter sw = new(filename))
{
sw.WriteLine($"LainerStorage{Environment.NewLine}{data}");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"LainerStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new NullReferenceException("Файл не найден");
throw new Exception("Файл не найден");
}
using (StreamReader sr = new(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
throw new NullReferenceException("нет данных для загрузки");
bufferTextFromFile += temp.GetString(b);
}
if (!strs[0].StartsWith("LainerStorage"))
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CarStorage"))
{
//если нет такой записи, то это не те данные
throw new ArgumentException("Неверный формат данных");
}
_lainerStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
throw new ArgumentException("неверный фориат данных");
continue;
}
_lainerStorages.Clear();
do
LainersGenericCollection<DrawingEntity, DrawningObjectLainer>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
DrawingEntity? lainer =
elem?.CreateDrawningLainer(_separatorForObject, _pictureWidth, _pictureHeight);
if (lainer != null)
{
str = sr.ReadLine();
continue;
}
LainersGenericCollection<DrawingLainer, 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);
if (lainer != null)
if (!(collection + lainer))
{
if (!(collection + lainer))
{
throw new IOException("Ошибка добавления в коллекцию");
}
throw new OverflowException("Ошибка добавления в коллекцию");
}
}
_lainerStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
_lainerStorages.Add(new LainersCollectionInfo(record[0],
string.Empty), collection);
}
}
}

View File

@ -1,4 +1,5 @@
using ProjectLainer.Exceptions;
using ProjectLainer.DrawningObjects;
using ProjectLainer.Exceptions;
using System.Numerics;
namespace ProjectLainer.Generics
@ -14,38 +15,53 @@ namespace ProjectLainer.Generics
_maxCount = count;
_places = new List<T?>(count);
}
public void Insert(T lainer)
public bool Insert(T lainer, IEqualityComparer<T?>? equal = null)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
Insert(lainer, 0);
}
public void Insert(T lainer, int position)
{
if (position >= 0 && position <= Count)
{
_places.Insert(position, lainer);
}
else
{
throw new Exception("Неверная позиция для вставки");
throw new OverflowException();
}
Insert(lainer, 0, equal);
return true;
}
public void Remove(int position)
public bool Insert(T lainer, int position, IEqualityComparer<T?>? equal = null)
{
if (position < Count && position >= 0)
// объект есть уже в коллекции - выбросить исключение
if (!(position >= 0 && position <= Count))
{
_places.RemoveAt(position);
return false;
}
else
if (equal != null)
{
throw new LainerNotFoundException(position);
foreach (T elem in _places)
{
if (equal.Equals(lainer, elem))
{
throw new Exception("такой объект уже есть");
}
}
}
_places.Insert(position, lainer);
return true;
}
public bool Remove(int position)
{
if(position < _maxCount && position >= 0)
{
if(position < Count)
{
_places.RemoveAt(position);
return true;
}
else
{
throw new LainerNotFoundException();
}
}
return false;
}
public T? this[int position]
{
@ -77,6 +93,7 @@ namespace ProjectLainer.Generics
}
}
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
}
}