LabWork07 #7

Closed
Mongol wants to merge 18 commits from LabWork07 into main
13 changed files with 429 additions and 29 deletions
Showing only changes of commit f63e0fa080 - Show all commits

View File

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

View File

@ -11,8 +11,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
@ -52,4 +66,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -9,7 +9,28 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> where T : c
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _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>
/// Конструктор
/// </summary>
@ -83,4 +104,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> where T : c
_collection[position] = null;
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,9 +1,10 @@
using ProjectLiner.Drawnings;
using System.Text;
namespace ProjectLiner.CollectionGenericObjects;
public class StorageCollection<T>
where T : class
where T : DrawningLiner
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -14,6 +15,18 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
@ -69,4 +82,134 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
_storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
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);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.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?.CreateDrawningLiner() is T car)
{
if (!collection.Insert(car))
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
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

@ -19,6 +19,11 @@ public class DrawningBetterLiner : DrawningLiner
EntityLiner = new EntityBetterLiner(speed, weight, bodyColor, additionalColor, hasMark, hasDecoration);
}
public DrawningBetterLiner(EntityBetterLiner liner) : base(150, 80)
{
EntityLiner = new EntityBetterLiner(liner.Speed, liner.Weight, liner.BodyColor, liner.AdditionalColor, liner.HasMark, liner.HasDecoratins);
}
public override void DrawTransport(Graphics g)
{
if (EntityLiner == null || EntityLiner is not EntityBetterLiner betterLiner || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -72,14 +72,18 @@ public class DrawningLiner
_startPosX = null;
_startPosY = null;
}
public DrawningLiner(EntityLiner liner) : this()
{
EntityLiner = new EntityLiner(liner.Speed, liner.Weight, liner.BodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningLiner(int speed, double weight, Color bodyColor) : this()
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningLiner(int speed, double weight, Color bodyColor) : this()
{
EntityLiner = new EntityLiner(speed, weight, bodyColor);
}

View File

@ -0,0 +1,46 @@
using ProjectLiner.Entities;
namespace ProjectLiner.Drawnings;
/// <summary>
/// Расширение для класса EntityLiner
/// </summary>
public static class ExtentionDrawningLiner
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningLiner? CreateDrawningLiner(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityLiner? liner = EntityLiner.CreateEntityLiner(strs);
if (liner != null)
{
return new DrawningBetterLiner(liner as EntityBetterLiner);
}
liner = EntityLiner.CreateEntityLiner(strs);
if (liner != null)
{
return new DrawningLiner(liner);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLiner">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningLiner drawningLiner)
{
string[]? array = drawningLiner?.EntityLiner?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -35,4 +35,27 @@ public class EntityBetterLiner : EntityLiner
HasMark = hasMark;
HasDecoratins = hasDecoratins;
}
/// <summary>
/// Получение строк со значениями свойств продвинутого объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityLiner), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
HasMark.ToString(), HasDecoratins.ToString()};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBetterLiner? CreateEntityWarmlyShip(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityBetterLiner))
{
return null;
}
return new EntityBetterLiner(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

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

View File

@ -1,8 +1,4 @@
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectLiner
namespace ProjectLiner
{
partial class FormLinerCollection
{
@ -50,10 +46,17 @@ namespace ProjectLiner
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
FileToolStripMenuItem = 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
@ -62,9 +65,9 @@ namespace ProjectLiner
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(887, 0);
groupBoxTools.Location = new Point(887, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(146, 596);
groupBoxTools.Size = new Size(146, 597);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -82,14 +85,14 @@ namespace ProjectLiner
panelCompanyTools.Size = new Size(200, 280);
panelCompanyTools.TabIndex = 2;
//
// buttonAddLiner
// buttonAddShip
//
buttonAddLiner.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddLiner.Location = new Point(3, 3);
buttonAddLiner.Name = "buttonAddLiner";
buttonAddLiner.Name = "buttonAddShip";
buttonAddLiner.Size = new Size(128, 38);
buttonAddLiner.TabIndex = 1;
buttonAddLiner.Text = "Добавление Лайнера";
buttonAddLiner.Text = "Добавление судна";
buttonAddLiner.UseVisualStyleBackColor = true;
buttonAddLiner.Click += buttonAddShip_Click;
//
@ -124,11 +127,11 @@ namespace ProjectLiner
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveLiner
// buttonRemoveShip
//
buttonRemoveLiner.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveLiner.Location = new Point(3, 122);
buttonRemoveLiner.Name = "buttonRemoveLiner";
buttonRemoveLiner.Name = "buttonRemoveShip";
buttonRemoveLiner.Size = new Size(128, 40);
buttonRemoveLiner.TabIndex = 4;
buttonRemoveLiner.Text = "Удаление";
@ -243,28 +246,73 @@ namespace ProjectLiner
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(887, 596);
pictureBox.Size = new Size(887, 597);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// FormLinerCollection
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1033, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1033, 596);
ClientSize = new Size(1033, 621);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormLinerCollection";
Text = "Коллекция лайнеров";
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Коллекция судов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -287,5 +335,11 @@ namespace ProjectLiner
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -169,5 +169,51 @@ public partial class FormLinerCollection : Form
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <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);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -127,4 +127,5 @@ public partial class FormLinerConfig : Form
Close();
}
}
}