PIbd-14 ChertovA.A. LabWork6 Simple #6

Closed
pibd14chertovandrey wants to merge 3 commits from lab06 into lab05
13 changed files with 396 additions and 39 deletions
Showing only changes of commit bc62abb2b5 - Show all commits

View File

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

View File

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

View File

@ -19,7 +19,22 @@ 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 Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@ -46,7 +61,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return 1;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public int Insert(T obj, int position)
{
if (_collection.Count + 1 < _maxCount) { return 0; }

View File

@ -14,8 +14,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)
@ -30,8 +35,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
@ -107,15 +113,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
if (position >= Count || position < 0) return null;
T? myObject = _collection[position];
_collection[position] = null;
return temp;
return myObject;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using ProjectRoadTrain.CollectionGenericObjects;
using ProjectRoadTrain.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
@ -6,7 +7,7 @@ using System.Text;
using System.Threading.Tasks;
public class StorageCollection<T>
where T : class
where T : DrawningTrain
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
@ -21,19 +22,12 @@ public class StorageCollection<T>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { });
return;
}
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
public void DelCollection(string name)
@ -46,8 +40,133 @@ public class StorageCollection<T>
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
if (_storages.ContainsKey(name))
return _storages[name];
return null;
}
}
private readonly string _collectionKey = "CollectionsStorage";
Review

Поля объявляются в начале класса

Поля объявляются в начале класса
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
Review

Записывать в файл можно сразу, без использования StringBuilder

Записывать в файл можно сразу, без использования StringBuilder
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
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 fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.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?.CreateTrain() is T machine)
{
if (collection.Insert(machine) == -1)
{
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

@ -9,12 +9,19 @@ namespace ProjectRoadTrain.Drawnings;
public class DrawningRoadTrain : DrawningTrain
{
public DrawningRoadTrain(int speed, double weight, Color bodycolor, Color bodytankcolor, bool watertank, bool cleanbrush) : base(230, 115)
{
EntityTrain = new EntityRoadTrain(speed, weight, bodycolor, bodytankcolor, watertank, cleanbrush);
}
public DrawningRoadTrain(EntityRoadTrain entityRoadTrain) : base(180, 140)
{
EntityTrain = new EntityRoadTrain(entityRoadTrain.Speed, entityRoadTrain.Weight, entityRoadTrain.BodyColor, entityRoadTrain.BodyTankColor, entityRoadTrain.WaterTank, entityRoadTrain.CleanBrush);
}
//public DrawningRoadTrain(EntityRoadTrain roadTrain) : base(180, 140)
Review

Закомментированного кода быть не должно

Закомментированного кода быть не должно
//{
// EntityTrain = new EntityRoadTrain(roadTrain.Speed, roadTrain.Weight, roadTrain.BodyColor, roadTrain.BodyTankColor, roadTrain.WaterTank, roadTrain.CleanBrush);
//}

View File

@ -45,6 +45,10 @@ public class DrawningTrain
_startPosX = null;
_startPosY = null;
}
public DrawningTrain(EntityTrain train) : this()
{
EntityTrain = new EntityTrain(train.Speed, train.Weight, train.BodyColor);
}
public DrawningTrain(int speed, double weight, Color bodycolor) : this()
{
EntityTrain = new EntityTrain(speed, weight, bodycolor);

View File

@ -0,0 +1,58 @@
using ProjectRoadTrain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningMachine
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrain? CreateTrain(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrain? machine = EntityRoadTrain.CreateEntityRoadTrain(strs);
if (machine != null)
{
return new DrawningRoadTrain((EntityRoadTrain)machine);
}
machine = EntityTrain.CreateEntityTrain(strs);
if (machine != null)
{
return new DrawningTrain(machine);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrackedMachine">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrain drawningTrackedMachine)
{
string[]? array = drawningTrackedMachine?.EntityTrain?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,6 +1,6 @@
namespace ProjectRoadTrain.Entities;
internal class EntityRoadTrain : EntityTrain
public class EntityRoadTrain : EntityTrain
{
public Color BodyTankColor { get; private set; }
public bool WaterTank { get; private set; }
@ -10,6 +10,26 @@ internal class EntityRoadTrain : EntityTrain
{
BodyTankColor = color;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityRoadTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name, BodyTankColor.Name,
WaterTank.ToString(), CleanBrush.ToString()};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityRoadTrain? CreateEntityRoadTrain(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityRoadTrain))
{
return null;
}
return new EntityRoadTrain(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 EntityRoadTrain(int speed, double weight, Color bodycolor, Color bodytankcolor,
bool watertank, bool cleanbrush) : base(speed, weight, bodycolor)

View File

@ -12,6 +12,25 @@ public class EntityTrain
{
BodyColor = color;
}
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrain? CreateEntityTrain(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrain))
{
return null;
}
return new EntityTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }

View File

@ -1,4 +1,6 @@
namespace ProjectRoadTrain
using System.Windows.Forms;
namespace ProjectRoadTrain
{
partial class FormTrainCollection
{
@ -65,6 +67,57 @@
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
// menuStrip
//
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
PerformLayout();
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(980, 28);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// файл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.Filter = "txt file | *.txt";
//
// panelCompanyTools
//
@ -284,5 +337,11 @@
private Button buttonCollectionDel;
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

@ -256,7 +256,45 @@ namespace ProjectRoadTrain
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
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)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)

View File

@ -6,6 +6,7 @@ using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
@ -114,10 +115,8 @@ public partial class FormTrainConfig : Form
}
private void labelBodyTankColor_DragDrop(object sender, DragEventArgs e)
{
if (_train.EntityTrain is EntityRoadTrain _waterTank)
{
_waterTank.setBodyTankColor((Color)e.Data.GetData(typeof(Color)));
}
if (_train != null && _train.EntityTrain is EntityRoadTrain _bulldozer)
_bulldozer.setBodyTankColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}