From 21741e196c1a6d4aa2d752e673f16d62558f4640 Mon Sep 17 00:00:00 2001 From: mar-va Date: Tue, 16 Apr 2024 19:57:11 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 9 +- .../ICollectionGenericObjects.cs | 20 ++- .../ListGenericObjects.cs | 34 +++-- .../MassiveGenericObjects.cs | 30 +++- .../StorageCollection.cs | 140 +++++++++++++++++- .../Drawnings/DrawningAccordionBus.cs | 8 + .../Drawnings/DrawningBus.cs | 10 +- .../Drawnings/ExtentionDrawningBus.cs | 53 +++++++ .../Entities/EntityAccordionBus.cs | 18 +++ .../ProjectAccordionBus/Entities/EntityBus.cs | 21 +++ .../FormBusCollection.Designer.cs | 71 ++++++++- .../ProjectAccordionBus/FormBusCollection.cs | 31 ++++ .../FormBusCollection.resx | 9 ++ 13 files changed, 421 insertions(+), 33 deletions(-) create mode 100644 ProjectAccordionBus/ProjectAccordionBus/Drawnings/ExtentionDrawningBus.cs diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs index 3ae1230..2aca4f1 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs @@ -3,6 +3,7 @@ using ProjectAccordionBus.MovementStrategy; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; @@ -27,12 +28,16 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeigth; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } public static int operator +(AbstractCompany company, DrawningBus bus) { - return company._collection.Insert(bus); + if (company._collection.Insert(bus)) + { + return 1; + } + return 0; } public static DrawningBus operator -(AbstractCompany company, int position) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs index 961e5ac..387ab6d 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; + +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -21,21 +22,21 @@ public interface ICollectionGenericObjects /// /// Установка максимального кол-ва объектов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллецию /// /// /// - int Insert(T obj); + bool Insert(T obj); /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + bool Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции @@ -50,5 +51,16 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs index b16bb18..34b7dc6 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -12,11 +12,21 @@ public class ListGenericObjects : ICollectionGenericObjects private readonly List _collection; private int _maxCount; - public int MaxCount => _maxCount; + public int MaxCount { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public CollectionType GetCollectionType => CollectionType.List; public ListGenericObjects() { @@ -30,26 +40,26 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public bool Insert(T obj) { if (Count == _maxCount) { - return -1; + return false; } _collection.Add(obj); - return _collection.Count; + return true; } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { if (Count == _maxCount || position < 0 || position > Count) { - return -1; + return false; } _collection.Insert(position, obj); - return position; + return true; } public T? Remove(int position) @@ -61,5 +71,11 @@ public class ListGenericObjects : ICollectionGenericObjects return obj; } - + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index 2694786..ed6d261 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -20,8 +20,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -38,6 +42,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор @@ -56,7 +62,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public bool Insert(T obj) { int index = 0; while (index < _collection.Length) @@ -64,18 +70,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[index] == null) { _collection[index] = obj; - return index; + return true; } index++; } - return -1; + return false; } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { if (position >= _collection.Length || position < 0) - return -1; + return false; if (_collection[position] != null) @@ -93,7 +99,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // Если пустого элемента нет, то выходим if (nullIndex < 0) { - return -1; + return false; } // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента int j = nullIndex - 1; @@ -104,7 +110,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } _collection[position] = obj; - return position; + return true; } public T? Remove(int position) @@ -117,5 +123,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[position] = null; return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs index 8a54479..6580b17 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,6 @@ -using System; +using ProjectAccordionBus.Drawnings; +using ProjectAccordionBus.CollectionGenericObjects; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -7,7 +9,7 @@ using System.Threading.Tasks; namespace ProjectAccordionBus.CollectionGenericObjects; public class StorageCollection - where T : class + where T : DrawningBus { /// /// Словарь (хранилище) с коллекциями @@ -18,7 +20,21 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); - + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// /// Конструктор /// @@ -75,4 +91,122 @@ public class StorageCollection } } + 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> 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; + } + + 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? collection = StorageCollection.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?.CreateDrawningBus() is T bus) + { + if (!collection.Insert(bus)) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs index cc0df31..b08d394 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs @@ -15,6 +15,14 @@ public class DrawningAccordionBus : DrawningBus EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, compartment, entrance, windows); } + public DrawningAccordionBus(EntityBus? entityBus) + { + if (entityBus != null) + { + EntityBus = entityBus; + } + } + public override void DrawTransport(Graphics g) { if (EntityBus == null || EntityBus is not EntityAccordionBus accordionBus || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBus.cs index 7e3eddb..344cf1f 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningBus.cs @@ -64,7 +64,7 @@ public class DrawningBus public int GetHight => _drawningBusHeight; // Пустой конструктор - private DrawningBus() + public DrawningBus() { _pictureWidth = null; _pictureHeight = null; @@ -85,6 +85,14 @@ public class DrawningBus _drawningBusHeight = drawningBusHeight; } + public DrawningBus(EntityBus? entityBus) + { + if (entityBus != null) + { + EntityBus = entityBus; + } + } + public bool SetPictureSize(int width, int height) { if (_drawningBusWidth <= width && _drawningBusHeight <= height) diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/ExtentionDrawningBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/ExtentionDrawningBus.cs new file mode 100644 index 0000000..6bb82a7 --- /dev/null +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/ExtentionDrawningBus.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectAccordionBus.Entities; + +namespace ProjectAccordionBus.Drawnings; + +public static class ExtentionDrawningBus +{ + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBus? CreateDrawningBus(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBus? bus = EntityAccordionBus.CreateEntityAccordionBus(strs); + if (bus != null) + { + return new DrawningAccordionBus(bus); + } + + bus = EntityBus.CreateEntityBus(strs); + if (bus != null) + { + return new DrawningBus(bus); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBus drawningBus) + { + string[]? array = drawningBus?.EntityBus?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs index c07ddbf..2b3efb6 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityAccordionBus.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Sockets; using System.Text; using System.Threading.Tasks; +using static System.Reflection.Metadata.BlobBuilder; namespace ProjectAccordionBus.Entities; @@ -34,4 +36,20 @@ public class EntityAccordionBus : EntityBus Windows = windows; } + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityAccordionBus), Speed.ToString(), Weight.ToString(), BodyColor.Name, + AdditionalColor.Name, Compartment.ToString(), Entrance.ToString(), Windows.ToString() }; + } + + public static EntityAccordionBus? CreateEntityAccordionBus(string[] strs) + { + if (strs.Length != 8 || 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]), Convert.ToBoolean(strs[7])); + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs index ce1ec78..d96c987 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Entities/EntityBus.cs @@ -31,4 +31,25 @@ public class EntityBus Weight = weight; BodyColor = bodyColor; } + + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name}; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + 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])); + } + } diff --git a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs index c2920bc..1690db7 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.Designer.cs @@ -46,10 +46,17 @@ comboBoxSelectorCompany = new ComboBox(); labelCollectionName = new Label(); 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 @@ -57,9 +64,9 @@ groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(625, 0); + groupBoxTools.Location = new Point(625, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(175, 510); + groupBoxTools.Size = new Size(175, 511); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -73,7 +80,7 @@ panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 316); + panelCompanyTools.Location = new Point(3, 317); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(169, 191); panelCompanyTools.TabIndex = 10; @@ -244,19 +251,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(625, 510); + pictureBox.Size = new Size(625, 511); pictureBox.TabIndex = 4; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(800, 24); + menuStrip.TabIndex = 5; + 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(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.FileName = "openFileDialog"; + openFileDialog.Filter = "txt file | *.txt"; + // // FormBusCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 510); + ClientSize = new Size(800, 535); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBusCollection"; Text = "Коллекция автобусов"; groupBoxTools.ResumeLayout(false); @@ -265,7 +315,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -288,5 +341,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; } } \ No newline at end of file diff --git a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs index abb8394..752b192 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.cs @@ -269,4 +269,35 @@ public partial class FormBusCollection : Form panelCompanyTools.Enabled = true; RefreshListBoxItems(); } + + 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); + } + } + } } diff --git a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.resx b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.resx index af32865..8b1dfa1 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.resx +++ b/ProjectAccordionBus/ProjectAccordionBus/FormBusCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 126, 17 + + + 261, 17 + \ No newline at end of file -- 2.25.1 From 2365620cf699975c3fcf2347c35976462999ddec Mon Sep 17 00:00:00 2001 From: mar-va Date: Thu, 18 Apr 2024 15:18:31 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=966?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 6 +- .../ICollectionGenericObjects.cs | 4 +- .../ListGenericObjects.cs | 12 +-- .../MassiveGenericObjects.cs | 14 +-- .../StorageCollection.cs | 93 +++++++++---------- .../Drawnings/DrawningAccordionBus.cs | 53 ++++++----- 6 files changed, 87 insertions(+), 95 deletions(-) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs index 2aca4f1..f236836 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/AbstractCompany.cs @@ -33,11 +33,7 @@ public abstract class AbstractCompany public static int operator +(AbstractCompany company, DrawningBus bus) { - if (company._collection.Insert(bus)) - { - return 1; - } - return 0; + return company._collection.Insert(bus); } public static DrawningBus operator -(AbstractCompany company, int position) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs index 387ab6d..927d76b 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -29,14 +29,14 @@ public interface ICollectionGenericObjects /// /// /// - bool Insert(T obj); + int Insert(T obj); /// /// Добавление объекта в коллекцию /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj, int position); + int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs index 34b7dc6..087e88b 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -40,26 +40,26 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public bool Insert(T obj) + public int Insert(T obj) { if (Count == _maxCount) { - return false; + return -1; } _collection.Add(obj); - return true; + return Count; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { if (Count == _maxCount || position < 0 || position > Count) { - return false; + return -1; } _collection.Insert(position, obj); - return true; + return 1; } public T? Remove(int position) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index ed6d261..c94d1cb 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -62,7 +62,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return _collection[position]; } - public bool Insert(T obj) + public int Insert(T obj) { int index = 0; while (index < _collection.Length) @@ -70,18 +70,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[index] == null) { _collection[index] = obj; - return true; + return 1; } index++; } - return false; + return -1; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { if (position >= _collection.Length || position < 0) - return false; + return -1; if (_collection[position] != null) @@ -99,7 +99,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // Если пустого элемента нет, то выходим if (nullIndex < 0) { - return false; + return -1; } // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента int j = nullIndex - 1; @@ -110,7 +110,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } _collection[position] = obj; - return true; + return 1; } public T? Remove(int position) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs index 6580b17..f8a3f22 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -101,23 +101,23 @@ public class StorageCollection { File.Delete(filename); } - StringBuilder sb = new(); - sb.Append(_collectionKey); - foreach (KeyValuePair> value in - _storages) + using FileStream fs = new(filename, FileMode.Create); + using StreamWriter sw = new StreamWriter(fs); + sw.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - sb.Append(Environment.NewLine); + sw.Write(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); + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -125,81 +125,74 @@ public class StorageCollection { continue; } - sb.Append(data); - sb.Append(_separatorItems); + sw.Write(data); + sw.Write(_separatorItems); } } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); return true; } public bool LoadData(string filename) + { + if (!File.Exists(filename)) { - if (!File.Exists(filename)) + return false; + } + + using (FileStream fs = new(filename, FileMode.Open)) + { + using StreamReader sr = new StreamReader(fs); + + string str = sr.ReadLine(); + if (str == null || str.Length == 0) { return false; } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + + if (!str.Equals(_collectionKey)) { - 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) + + while (!sr.EndOfStream) { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); + string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { continue; } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { return false; } + collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningBus() is T bus) { - if (!collection.Insert(bus)) - { + if (collection.Insert(bus) == -1) return false; - } } } _storages.Add(record[0], collection); } - return true; } - /// - /// Создание коллекции по типу - /// - /// - /// - private static ICollectionGenericObjects? + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch diff --git a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs index b08d394..078d863 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/Drawnings/DrawningAccordionBus.cs @@ -36,35 +36,38 @@ public class DrawningAccordionBus : DrawningBus Brush brushBlue = new SolidBrush(Color.Blue); // отсек - g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value, 50, 30); - g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20); - - g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value, 50, 30); - g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20); - - // колеса - g.FillEllipse(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10); - g.FillEllipse(additionalBrush, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10); - - g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10); - - if (accordionBus.Entrance) + if (accordionBus.Compartment) { - g.FillRectangle(additionalBrush, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value, 50, 30); + g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20); - g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20); - } + g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value, 50, 30); + g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 5, 10, 20); - if (accordionBus.Windows) - { - g.FillEllipse(brushBlue, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10); - g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10); - g.FillEllipse(brushBlue, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10); + // колеса + g.FillEllipse(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10); + g.FillEllipse(additionalBrush, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10); - g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10); - g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10); - g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10); + g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 25, 10, 10); + g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 25, 10, 10); + + if (accordionBus.Entrance) + { + g.FillRectangle(additionalBrush, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20); + + g.DrawRectangle(pen, _startPosX.Value + 78, _startPosY.Value + 10, 10, 20); + } + + if (accordionBus.Windows) + { + g.FillEllipse(brushBlue, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10); + g.FillEllipse(brushBlue, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10); + g.FillEllipse(brushBlue, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10); + + g.DrawEllipse(pen, _startPosX.Value + 65, _startPosY.Value + 5, 5, 10); + g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 5, 5, 10); + g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 5, 5, 10); + } } } } \ No newline at end of file -- 2.25.1 From 86aefff19974d44c20a5b3f6fe9557b2af19dff3 Mon Sep 17 00:00:00 2001 From: mar-va Date: Sat, 20 Apr 2024 10:14:45 +0400 Subject: [PATCH 3/3] Lab6 --- .../StorageCollection.cs | 78 +++++++++---------- 1 file changed, 36 insertions(+), 42 deletions(-) diff --git a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs index f8a3f22..a34d8f3 100644 --- a/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAccordionBus/ProjectAccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -50,8 +50,6 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления if (_storages.ContainsKey(name) || name == "") return; if (collectionType == CollectionType.Massive) @@ -69,7 +67,6 @@ public class StorageCollection /// Название коллекции public void DelCollection(string name) { - // TODO Прописать логику для удаления коллекции _storages.Remove(name); } @@ -82,7 +79,6 @@ public class StorageCollection { get { - // TODO Продумать логику получения объекта if (name == "") { return null; @@ -101,32 +97,34 @@ public class StorageCollection { File.Delete(filename); } - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter sw = new StreamWriter(fs); - sw.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + using (StreamWriter writer = new(filename)) { - sw.Write(Environment.NewLine); - // не сохраняем пустые коллекции - if (value.Value.Count == 0) + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - continue; - } - sw.Write(value.Key); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.MaxCount); - sw.Write(_separatorForKeyValue); - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } - sw.Write(data); - sw.Write(_separatorItems); + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } } } return true; @@ -138,47 +136,43 @@ public class StorageCollection { return false; } - - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader reader = new(filename)) { - using StreamReader sr = new StreamReader(fs); - - string str = sr.ReadLine(); - if (str == null || str.Length == 0) + string line = reader.ReadLine(); + if (line == null || line.Length == 0) { return false; } - - if (!str.Equals(_collectionKey)) + if (!line.Equals(_collectionKey)) { return false; } _storages.Clear(); - - while (!sr.EndOfStream) + while ((line = reader.ReadLine()) != null) { - string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + string[] record = line.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { return false; } - collection.MaxCount = Convert.ToInt32(record[2]); - - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + string[] set = record[3].Split(_separatorItems, + StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T bus) + if (elem?.CreateDrawningBus() is T truck) { - if (collection.Insert(bus) == -1) + if (collection.Insert(truck) == -1) + { return false; + } } } _storages.Add(record[0], collection); -- 2.25.1