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

This commit is contained in:
H0llowVoid 2024-06-09 21:00:11 +04:00
parent f7a5fd36e9
commit e0e94bcab0
13 changed files with 385 additions and 19 deletions

View File

@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>

View File

@ -17,7 +17,7 @@ public interface ICollectionGenericObjects<T>
///<summary>
///Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
///<summary>
///Добавление объекта в коллекцию
@ -48,8 +48,14 @@ public interface ICollectionGenericObjects<T>
///<returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -19,7 +19,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
if (_maxCount < _collection.Count) return _maxCount;
return _collection.Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@ -82,4 +99,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; i++)
{
yield return _collection[i];
}
}
}

View File

@ -19,8 +19,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@ -36,6 +41,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -117,4 +125,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
return null;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,11 +1,16 @@
namespace ProjectHoistingCrane.CollectionGenericObjects;
using Microsoft.VisualBasic;
using ProjectHoistingCrane.Drawnings;
using System.Collections.ObjectModel;
using System.Text;
namespace ProjectHoistingCrane.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningCrane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -15,6 +20,13 @@ public class StorageCollection<T>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -74,4 +86,116 @@ public class StorageCollection<T>
}
}
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
writer.Close();
}
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
}
if (!line.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningCrane() is T crane)
{
if (collection.Insert(crane) < 0)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -75,13 +75,17 @@ public class DrawningCrane
EntityCrane = new EntityCrane(speed, weight, bodyColor);
}
public DrawningCrane(EntityCrane? entityCrane) : this()
{
if (entityCrane == null) return;
EntityCrane = new EntityCrane(entityCrane.Speed, entityCrane.Weight, entityCrane.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningCraneWidth">Ширина прорисовки крана</param>
/// <param name="drawningCraneHeight">Высота прорисовки крана</param>
protected DrawningCrane(int drawningCraneWidth, int drawningCraneHeight) : this()
{
_drawningCraneWidth = drawningCraneWidth;

View File

@ -20,6 +20,13 @@ public class DrawningHoistingCrane : DrawningCrane
}
public DrawningHoistingCrane(EntityHoistingCrane? entityHoistingCrane) : base(110, 56)
{
if (entityHoistingCrane == null) return;
EntityCrane = new EntityHoistingCrane(entityHoistingCrane.Speed, entityHoistingCrane.Weight, entityHoistingCrane.BodyColor,
entityHoistingCrane.AdditionalColor, entityHoistingCrane.Counterweight, entityHoistingCrane.Crane);
}
public override void DrawTransport(Graphics g)
{
if (EntityCrane == null || EntityCrane is not EntityHoistingCrane hoistingCrane || !_startPosX.HasValue || !_startPosY.HasValue)
@ -53,7 +60,7 @@ public class DrawningHoistingCrane : DrawningCrane
}
//противовес
if (hoistingCrane.Сounterweight)
if (hoistingCrane.Counterweight)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value, 10, 9);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value, 9, 8);

View File

@ -0,0 +1,44 @@
using ProjectHoistingCrane.Entities;
namespace ProjectHoistingCrane.Drawnings;
/// <summary>
/// Расширение для класса EntityCrane
/// </summary>
public static class ExtentionDrawningCrane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
private static readonly string _separator = ":";
public static DrawningCrane? CreateDrawningCrane(this string info)
{
string[] strs = info.Split(_separator);
EntityCrane? crane = EntityHoistingCrane.CreateEntityHoistingCrane(strs);
if (crane != null)
{
return new DrawningHoistingCrane((EntityHoistingCrane)crane);
}
crane = EntityCrane.CreateEntityCrane(strs);
if (crane != null)
{
return new DrawningCrane(crane);
}
return null;
}
public static string GetDataForSave(this DrawningCrane drawningCrane)
{
string[]? array = drawningCrane?.EntityCrane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separator, array);
}
}

View File

@ -45,4 +45,28 @@ public class EntityCrane
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityCrane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityCrane? CreateEntityCrane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityCrane))
{
return null;
}
return new EntityCrane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -10,7 +10,7 @@ public class EntityHoistingCrane : EntityCrane
/// <summary>
/// Признак (опция) наличия противовеса
/// </summary>
public bool Сounterweight { get; private set; }
public bool Counterweight { get; private set; }
/// <summary>
/// Признак (опция) наличия крана
/// </summary>
@ -31,10 +31,24 @@ public class EntityHoistingCrane : EntityCrane
AdditionalColor = color;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityHoistingCrane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Counterweight.ToString(), Crane.ToString()};
}
public static EntityHoistingCrane? CreateEntityHoistingCrane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityHoistingCrane))
{
return null;
}
return new EntityHoistingCrane(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
public EntityHoistingCrane(int speed, double weight, Color bodyColor, Color additionalColor, bool counterweight, bool crane):base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Сounterweight = counterweight;
Counterweight = counterweight;
Crane = crane;
}
}
}

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(771, 0);
groupBoxTools.Location = new Point(771, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(222, 690);
groupBoxTools.Size = new Size(222, 662);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -241,12 +248,54 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(771, 690);
pictureBox.Size = new Size(771, 662);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(993, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file|*.txt";
//
// FormCraneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -254,6 +303,8 @@
ClientSize = new Size(993, 690);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCraneCollection";
Text = "Коллекция кранов";
groupBoxTools.ResumeLayout(false);
@ -262,7 +313,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -285,5 +339,11 @@
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -257,4 +257,37 @@ public partial class FormCraneCollection : Form
}
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Успешно загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Ошибка загрузки", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
</root>