ISEbd-12_Skvortsov-A.K._AccordionBus_Simple_Lab6 #7

Closed
Aleksey-Skvortsov wants to merge 1 commits from lab6 into lab5
13 changed files with 431 additions and 61 deletions

View File

@ -26,15 +26,15 @@ namespace AccordionBus.CollectionGenericObjects
_pictureWidth = picWidth;
_pictureHeight = picHeigth;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
public static int operator +(AbstractCompany company, DrawningBus bus)
public static bool operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection.Insert(bus);
}
public static DrawningBus? operator -(AbstractCompany company, int position)
public static bool operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
@ -55,6 +55,7 @@ namespace AccordionBus.CollectionGenericObjects
for (int i = 0; i < (_collection?.MaxCount ?? 0); i++)
{
DrawningBus? obj = _collection?.Get(i);
if (obj != null) obj.SetPictureSize(_pictureWidth, _pictureHeight);
SetObjectPosition(i, _collection?.MaxCount ?? 0, obj);
obj?.DrawTransport(graphics);
}

View File

@ -12,35 +12,46 @@ namespace AccordionBus.CollectionGenericObjects
/// <summary>
/// кол-во элем
/// </summary>
int MaxCount { get; }
int Count { get; }
/// <summary>
/// установить макс элем
/// макс кол-во элем
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// вставить
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <returns></returns>
int Insert(T obj);
bool Insert(T obj);
/// <summary>
/// вставить по позиции
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <param name="position">индекс</param>
/// <returns></returns>
int Insert(T obj, int position);
bool Insert(T obj, int position);
/// <summary>
/// удаление
/// </summary>
/// <param name="position">индекс</param>
/// <returns></returns>
T? Remove(int position);
bool Remove(int position);
/// <summary>
/// получение объекта по позиции
/// </summary>
/// <param name="position">индекс</param>
/// <returns></returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T> GetItems();
}
}

View File

@ -13,9 +13,21 @@ namespace AccordionBus.CollectionGenericObjects
private readonly List<T?> _collection;
private int _maxCount;
public int MaxCount => _maxCount;
public int Count { get { return _collection.Count; } }
public int SetMaxCount { set { if (value > 0) _maxCount = value; } }
public int MaxCount
{
get
{
return _maxCount;
}
set
{
if (value > 0) _maxCount = value;
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenericObjects()
{
@ -29,29 +41,37 @@ namespace AccordionBus.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public bool Insert(T obj)
{
if (_collection == null || _collection.Count == _maxCount) return -1;
if (_collection == null || _collection.Count == _maxCount) return false;
_collection.Add(obj);
return _collection.Count - 1;
return true;
}
public int Insert(T obj, int position)
public bool Insert(T obj, int position)
{
if (_collection == null || position < 0 || position > _maxCount) return -1;
if (_collection == null || position < 0 || position > _maxCount) return false;
_collection.Insert(position, obj);
return position;
return true;
}
public T? Remove(int position)
public bool Remove(int position)
{
if (_collection == null || position < 0 || position >= _collection.Count) return null;
if (_collection == null || position < 0 || position >= _collection.Count) return false;
T? obj = _collection[position];
_collection[position] = null;
return obj;
return true;
}
public IEnumerable<T> GetItems()
{
for (int i = 0; i < _collection.Count; i++)
{
yield return _collection[i];
}
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
@ -11,9 +12,25 @@ namespace AccordionBus.CollectionGenericObjects
{
private T?[] _collection;
public int MaxCount => _collection.Length;
public int Count { get { return _collection.Length; } }
public int SetMaxCount { set { if (value > 0 && MaxCount == 0) { _collection = new T?[value]; } } }
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0 && _collection.Length == 0)
{
_collection = new T?[value];
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
public MassiveGenericObjects()
{
@ -26,27 +43,27 @@ namespace AccordionBus.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public bool Insert(T obj)
{
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
return true;
}
}
return -1;
return false;
}
public int Insert(T obj, int position)
public bool Insert(T obj, int position)
{
if (position < 0 || position >= _collection.Length) { return -1; }
if (position < 0 || position >= _collection.Length) { return false; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
return true;
}
else
{
@ -55,7 +72,7 @@ namespace AccordionBus.CollectionGenericObjects
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
return true;
}
}
@ -64,20 +81,28 @@ namespace AccordionBus.CollectionGenericObjects
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
return true;
}
}
}
return -1;
return false;
}
public T? Remove(int position)
public bool Remove(int position)
{
if (position < 0 || position >= _collection.Length) { return null;}
if (position < 0 || position >= _collection.Length) { return false;}
T? obj = _collection[position];
_collection[position] = null;
return obj;
return true;
}
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 AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
@ -8,12 +9,18 @@ using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class StorageCollection<T>
where T: class
where T: DrawningBus
{
private Dictionary<string, ICollectionGenericObjects<T>> _storage;
readonly Dictionary<string, ICollectionGenericObjects<T>> _storage;
public List<string> Keys => _storage.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItem = ";";
public StorageCollection()
{
_storage = new Dictionary<string, ICollectionGenericObjects<T>>();
@ -23,14 +30,7 @@ namespace AccordionBus.CollectionGenericObjects
{
if (_storage.ContainsKey(name) || name == "") return;
if (collectionType == CollectionType.Massive)
{
_storage[name] = new MassiveGenericObjects<T>();
}
else
{
_storage[name] = new ListGenericObjects<T>();
}
_storage[name] = CreateCollection(collectionType);
}
public void DelCollection(string name)
@ -46,5 +46,109 @@ namespace AccordionBus.CollectionGenericObjects
return _storage[name];
}
}
public bool SaveData(string filename)
{
if (_storage.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 _storage)
{
StringBuilder sb = new();
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(_separatorItem);
}
writer.Write(sb);
}
return true;
}
}
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;
}
_storage.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(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T bus)
{
if (!collection.Insert(bus))
{
return false;
}
}
}
_storage.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

@ -27,6 +27,11 @@ namespace AccordionBus.Drawnings
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, hatch, fiveDoors);
}
public DrawningAccordionBus(EntityAccordionBus bus) : base(130, 20)
{
EntityBus = bus;
}
/// <summary>
/// Отрисовка транспорта
/// </summary>

View File

@ -61,7 +61,7 @@ namespace AccordionBus.Drawnings
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningBus()
public DrawningBus()
{
_pictureWeight = null;
_pictureHeigth = null;
@ -90,6 +90,11 @@ namespace AccordionBus.Drawnings
EntityBus = new EntityBus(speed, weight, bodyColor);
}
public DrawningBus(EntityBus bus)
{
EntityBus = bus;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@ -0,0 +1,51 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public static class ExtentionDrawningBus
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строк характеристик
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningBus? CreateDrawningBus(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBus? bus = EntityAccordionBus.CreateEntityAccordionBus(strs);
if (bus != null && bus is EntityAccordionBus busA)
{
return new DrawningAccordionBus(busA);
}
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Подготовка данных для сохранения в файл
/// </summary>
/// <param name="drawningBus"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null) { return string.Empty; }
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -45,5 +45,28 @@ namespace AccordionBus.Entities
/// </summary>
/// <param name="color"></param>
public void SetAdditionalColor(Color color) { AdditionalColor = color; }
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAccordionBus), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Hatch.ToString(), FiveDoors.ToString() };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAccordionBus? CreateEntityAccordionBus(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAccordionBus)) { return null; }
return new EntityAccordionBus(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

@ -45,5 +45,26 @@ namespace AccordionBus.Entities
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color) { BodyColor = color; }
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBus? CreateEntityBus(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBus)) { return null; }
return new EntityBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}
}

View File

@ -46,10 +46,17 @@
buttonGoToCheck = new Button();
buttonRemoveBus = new Button();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(panelTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(948, 0);
groupBoxTools.Location = new Point(948, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(234, 753);
groupBoxTools.Size = new Size(234, 725);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -180,7 +187,7 @@
panelTools.Enabled = false;
panelTools.Location = new Point(3, 396);
panelTools.Name = "panelTools";
panelTools.Size = new Size(228, 354);
panelTools.Size = new Size(228, 326);
panelTools.TabIndex = 7;
//
// buttonAddBus
@ -195,7 +202,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(9, 286);
buttonRefresh.Location = new Point(9, 265);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(207, 54);
buttonRefresh.TabIndex = 6;
@ -205,7 +212,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(9, 133);
maskedTextBox.Location = new Point(9, 112);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(207, 27);
@ -214,7 +221,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(9, 226);
buttonGoToCheck.Location = new Point(9, 205);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(207, 54);
buttonGoToCheck.TabIndex = 5;
@ -224,7 +231,7 @@
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(9, 166);
buttonRemoveBus.Location = new Point(9, 145);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(207, 54);
buttonRemoveBus.TabIndex = 4;
@ -235,12 +242,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(948, 753);
pictureBox.Size = new Size(948, 725);
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(1182, 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.Filter = "txt file | *.txt";
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -248,6 +296,8 @@
ClientSize = new Size(1182, 753);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusCollection";
StartPosition = FormStartPosition.CenterScreen;
Text = "Коллекция автобусов";
@ -257,7 +307,10 @@
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -280,5 +333,11 @@
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -43,7 +43,7 @@ namespace AccordionBus
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
if (_company + bus != -1)
if (_company + bus)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
@ -62,7 +62,7 @@ namespace AccordionBus
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos is DrawningBus)
if (_company - pos)
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _company.Show();
@ -123,7 +123,7 @@ namespace AccordionBus
{
if (listBoxCollection.SelectedItem == null) return;
if (MessageBox.Show("Вы действительно хотите удалить выбранный элемент?",
if (MessageBox.Show("Вы действительно хотите удалить выбранный элемент?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
@ -134,7 +134,7 @@ namespace AccordionBus
{
MessageBox.Show("Не удалось удалить компанию");
}
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
@ -145,7 +145,8 @@ namespace AccordionBus
return;
}
ICollectionGenericObjects<DrawningBus?> collection = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningBus?> collection =
_storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Компания не инициализирована");
@ -166,7 +167,7 @@ namespace AccordionBus
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i =0; i < _storageCollection.Keys?.Count; i++)
for (int i = 0; i < _storageCollection.Keys?.Count; i++)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
@ -175,5 +176,40 @@ namespace AccordionBus
}
}
}
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);
RefreshListBoxItems();
}
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>