labwork06

This commit is contained in:
BoiledMilk123 2024-05-07 02:10:53 +04:00
parent 70023c1911
commit f00e0c5a8c
14 changed files with 435 additions and 28 deletions

View File

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

View File

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

View File

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

View File

@ -45,12 +45,12 @@ public class LocomotiveDepot : AbstractCompany
if (_collection?.Count != null)
{
for (int i = 0; i < (_collection.Count); i++)
for (int i = 0; i < (_collection?.Count); i++)
{
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
}
if (positionWidth < width - 1)

View File

@ -20,7 +20,28 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount { set { if (Count > 0) { Array.Resize(ref _collection, value); } else { _collection = new T?[value]; } } }
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else _collection = new T?[value];
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
@ -104,4 +125,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return removedObject;
}
public IEnumerable<T> GetItems()
{
for( int i = 0; i < _collection.Length; ++i )
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -11,7 +12,7 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningLocomotive
{
/// <summary>
/// Словарь с коллекциями
@ -23,6 +24,21 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -64,14 +80,13 @@ public class StorageCollection<T>
}
}
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[int index]
{
get
{
// логика получения объекта (если есть запись с ключом мы должны вернуть объект иначе значение словаря по ключу)
if (_storages.ContainsKey(name))
if (index >= 0 && index < _storages.Count)
{
return _storages[name];
return _storages.ElementAt(index).Value;
}
else
{
@ -79,4 +94,115 @@ public class StorageCollection<T>
}
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилице в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
if (_storages.Count == 0) return false;
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
writer.Write(_separatorItems);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (!string.IsNullOrEmpty(data))
{
writer.Write(data + _separatorItems);
}
}
writer.WriteLine();
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename)) return false;
using (StreamReader reader = new StreamReader(filename))
{
string line = reader.ReadLine();
if (line == null || !line.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
while (line != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
line = reader.ReadLine();
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?.CreateDrawningLocomotive() is T locomotive)
{
if (collection.Insert(locomotive) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
line = reader.ReadLine();
}
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -22,6 +22,11 @@ public class DrawningElectricLocomotive : DrawningLocomotive
EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement);
}
public DrawningElectricLocomotive(EntityLocomotive locomotive) : base(locomotive)
{
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -87,6 +87,11 @@ public class DrawningLocomotive
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
public DrawningLocomotive(EntityLocomotive locomotive)
{
EntityLocomotive = locomotive;
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -0,0 +1,53 @@
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Drawnings;
public static class ExtentionDrawningLocomotive
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningLocomotive? CreateDrawningLocomotive(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityLocomotive? locomotive = EntityElectricLocomotive.CreateEntityElectricLocomotive(strs);
if (locomotive != null)
{
return new DrawningElectricLocomotive(locomotive);
}
locomotive = EntityLocomotive.CreateEntityLocomotive(strs);
if (locomotive != null)
{
return new DrawningLocomotive(locomotive);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningLocomotive drawningLocomotive)
{
string[]? array = drawningLocomotive?.EntityLocomotive?.GetStringRepresentation();
if (array == null) return string.Empty;
return string.Join(_separatorForObject, array);
}
}

View File

@ -42,4 +42,27 @@ public class EntityElectricLocomotive : EntityLocomotive
{
AdditionalColor = color;
}
/// <summary>
/// Получение строк с значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityElectricLocomotive), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, ElectricHorns.ToString(), BatteryPlacement.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityElectricLocomotive? CreateEntityElectricLocomotive(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityElectricLocomotive))
{
return null;
}
return new EntityElectricLocomotive(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

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

View File

@ -47,10 +47,17 @@
labelCollectionName = new Label();
pictureBox = new PictureBox();
colorDialog1 = new ColorDialog();
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
@ -60,9 +67,9 @@
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(640, 0);
groupBoxTools.Location = new Point(640, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 593);
groupBoxTools.Size = new Size(200, 569);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -98,7 +105,7 @@
panelCompanyTools.Controls.Add(buttonRemoveLocomotive);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 364);
panelCompanyTools.Location = new Point(3, 340);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 226);
panelCompanyTools.TabIndex = 8;
@ -237,12 +244,52 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(640, 593);
pictureBox.Size = new Size(640, 569);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(840, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(173, 22);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(173, 22);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
//
// FormLocomotiveCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -250,6 +297,8 @@
ClientSize = new Size(840, 593);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormLocomotiveCollection";
Text = "FormLocomotiveCollection";
groupBoxTools.ResumeLayout(false);
@ -258,7 +307,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -282,5 +334,11 @@
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -207,9 +207,8 @@ public partial class FormLocomotiveCollection : Form
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for(int i = 0; i < _storageCollection.Keys?.Count; ++i)
foreach(string colName in _storageCollection.Keys)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -230,7 +229,7 @@ public partial class FormLocomotiveCollection : Form
return;
}
ICollectionGenericObjects<DrawningLocomotive>? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningLocomotive>? collection = _storageCollection[listBoxCollection.SelectedIndex];
if (collection == null)
{
MessageBox.Show("Коллекция не проиннициализирована");
@ -245,4 +244,45 @@ public partial class FormLocomotiveCollection : Form
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -120,4 +120,13 @@
<metadata name="colorDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>138, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>247, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>382, 17</value>
</metadata>
</root>