Лабораторная работа 06. Но пока не доделан парсинг

This commit is contained in:
Almaz 2024-04-23 01:23:03 +04:00
parent 719a219d96
commit 630fb5eacd
13 changed files with 548 additions and 66 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

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

View File

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

View File

@ -20,7 +20,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
set
{
@ -36,7 +36,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
get
{
return _collection.Length;
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
@ -101,4 +107,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[index] = obj;
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++) yield return _collection[i];
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectCruiser.Drawings;
namespace ProjectCruiser.CollectionGenericObjects;
@ -11,7 +12,7 @@ namespace ProjectCruiser.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningCruiser
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -21,6 +22,12 @@ public class StorageCollection<T>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -77,4 +84,239 @@ public class StorageCollection<T>
return _storages[name];
}
}
/// <summary>
/// Запись информации в файл
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
if (_storages.Count == 0) return false;
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></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></returns>
//public bool LoadData(string filename)
//{
// if (!File.Exists(filename))
// {
// return false;
// }
// using (StreamReader reader = File.OpenText(filename))
// {
// string str = reader.ReadLine();
// if (str == null || str.Length == 0)
// {
// return false;
// }
// if (!str.StartsWith(_collectionKey))
// {
// return false;
// }
// _storages.Clear();
// string strs = "";
// while ((strs = reader.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?.CreateDrawningCruiser() is T cruiser)
// {
// if (!collection.Insert(cruiser))
// {
// return false;
// }
// }
// }
// _storages.Add(record[0], collection);
// }
// return true;
// }
//}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></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?.CreateDrawningCruiser() is T cruiser)
{
if (!collection.Insert(cruiser))
{
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

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectCruiser.Entities;
using ProjectCruiser.Entities;
namespace ProjectCruiser.Drawings;
@ -92,6 +87,11 @@ public class DrawningCruiser
_drawingCruiserHeight = drawingCruiserHeight;
}
public DrawningCruiser(EntityCruiser cruiser)
{
EntityCruiser = cruiser;
}
public bool SetPictireSize(int width, int height)
{
_pictureWidth = width;

View File

@ -10,6 +10,11 @@ namespace ProjectCruiser.Drawings;
public class DrawningMilitaryCruiser: DrawningCruiser
{
public DrawningMilitaryCruiser(EntityCruiser cruiser) : base(cruiser)
{
}
/// <summary>
/// Конструктор
/// </summary>

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectCruiser.Entities;
namespace ProjectCruiser.Drawings;
public static class ExtentionDrawningCruiser
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningCruiser? CreateDrawningCruiser(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityCruiser? cruiser = EntityMilitaryCruiser.CreateEntityMilitaryCruiser(strs);
if (cruiser != null)
{
return new DrawningMilitaryCruiser(cruiser);
}
cruiser = EntityCruiser.CreateEntityCruiser(strs);
if (cruiser != null)
{
return new DrawningCruiser(cruiser);
}
return null;
}
///// <summary>
///// Создание обьекта в зависимости от выбранного типа
///// </summary>
///// <param name="info"></param>
///// <returns></returns>
//public static DrawningCruiser? CreateDrawningCruiser(this string info)
//{
// string[] strs = info.Split(_separatorForObject);
// EntityMilitaryCruiser? militaryCruiser = EntityMilitaryCruiser.CreateEntityMilitaryCruiser(strs);
// if (militaryCruiser != null)
// {
// return new DrawningMilitaryCruiser(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
// }
// EntityCruiser? cruiser = EntityCruiser.CreateEntityCruiser(strs);
// if (cruiser != null)
// {
// return new DrawningCruiser(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
// }
// return null;
//}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningCruiser drawningCruiser)
{
string[]? array = drawningCruiser?.EntityCruiser?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@ -1,5 +1,7 @@
namespace ProjectCruiser.Entities
{
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectCruiser.Entities;
/// <summary>
/// Класс-сущность "Военный Крейсер" Вариант 18
/// </summary>
@ -51,5 +53,15 @@
RocketMine = rocketMine;
HelicopterPad = helicopterPad;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityMilitaryCruiser), Speed.ToString(), Weigth.ToString(), BodyColor.Name, AdditionalColor.ToString(), RocketMine.ToString(), HelicopterPad.ToString() };
}
public static EntityMilitaryCruiser? CreateEntityMilitaryCruiser(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityMilitaryCruiser)) return null;
return new EntityMilitaryCruiser(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

@ -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(890, 0);
groupBoxTools.Location = new Point(890, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 728);
groupBoxTools.Size = new Size(250, 700);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -77,7 +84,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 431);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(244, 294);
panelCompanyTools.Size = new Size(244, 266);
panelCompanyTools.TabIndex = 9;
//
// buttonAddCruiser
@ -93,7 +100,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(9, 109);
maskedTextBoxPosition.Location = new Point(9, 67);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(232, 27);
@ -103,7 +110,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(9, 234);
buttonRefresh.Location = new Point(9, 192);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(226, 40);
buttonRefresh.TabIndex = 6;
@ -114,7 +121,7 @@
// buttonRemoveCruiser
//
buttonRemoveCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveCruiser.Location = new Point(9, 142);
buttonRemoveCruiser.Location = new Point(9, 100);
buttonRemoveCruiser.Name = "buttonRemoveCruiser";
buttonRemoveCruiser.Size = new Size(226, 40);
buttonRemoveCruiser.TabIndex = 4;
@ -125,7 +132,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(9, 188);
buttonGoToCheck.Location = new Point(9, 146);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(226, 40);
buttonGoToCheck.TabIndex = 5;
@ -239,12 +246,53 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(890, 728);
pictureBox.Size = new Size(890, 700);
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(1140, 28);
menuStrip.TabIndex = 2;
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";
//
// FormCruiserCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -252,6 +300,8 @@
ClientSize = new Size(1140, 728);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCruiserCollection";
Text = "Коллекция Крейсеров";
groupBoxTools.ResumeLayout(false);
@ -260,7 +310,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -283,5 +336,11 @@
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -186,4 +186,32 @@ public partial class FormCruiserCollection : 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)
{
//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);
}
}
}
}

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>