diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs index 72defe7..128367e 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs @@ -24,7 +24,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } public static int operator +(AbstractCompany company, DrawningBoat boat) { diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs index eaf98c0..155355d 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -11,10 +11,12 @@ public interface ICollectionGenericObjects where T : class { int Count { get; } - int SetMaxCount { set; } + int MaxCount { get; set; } int Insert(T obj); int Insert(T obj, int position); T Remove(int position); T? Get(int position); + CollectionType GetCollectionType { get; } + IEnumerable GetItems(); } diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs index 9310c0f..370d8c8 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs @@ -15,6 +15,8 @@ where T : class /// private readonly List _collection; + public CollectionType GetCollectionType => CollectionType.List; + /// /// Максимально допустимое число объектов в списке /// @@ -22,7 +24,20 @@ where T : class public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } /// /// Конструктор @@ -68,4 +83,12 @@ where T : class _collection.RemoveAt(position); return pos; } + + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs index 332d606..6047760 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,17 +1,25 @@ -namespace ProjectMotorboat.CollectionGenericObjects; + + +namespace ProjectMotorboat.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class { - + private T?[] _collection; + public int Count => _collection.Length; - public int SetMaxCount + + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) { - if (_collection.Length > 0) + if (Count > 0) { Array.Resize(ref _collection, value); } @@ -22,7 +30,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } } - + + public CollectionType GetCollectionType => CollectionType.Massive; + public MassiveGenericObjects() { _collection = Array.Empty(); @@ -93,5 +103,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } + + diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs index 4f3a336..ea06e9c 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectMotorboat.Drownings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -7,10 +8,10 @@ using System.Threading.Tasks; namespace ProjectMotorboat.CollectionGenericObjects; public class StorageCollection - where T : class + where T : DrawningBoat { - - readonly Dictionary> _storages; + + private Dictionary> _storages; public List Keys => _storages.Keys.ToList(); @@ -57,4 +58,137 @@ public class StorageCollection return _storages[name]; } } + + private readonly string _collectionKey = "CollectionsStorage"; + + private readonly string _separatorForKeyValue = "|"; + + private readonly string _separatorItems = ";"; + + public bool SaveData(string filname) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filname)) + { + File.Delete(filname); + } + + if (File.Exists(filname)) + { + File.Delete(filname); + } + + 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(filname, 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?.CreateDrawningBoat() is T warship) + { + if (collection.Insert(warship) == -1) + { + 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, + }; + } } \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs index 50db8a7..9c9321a 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs @@ -51,6 +51,11 @@ public class DrawningBoat _drawningBoatHeight = drawningBoatHeight; } + + public DrawningBoat(EntityBoat ship) : this() + { + EntityBoat = new EntityBoat(ship.Speed, ship.Weight, ship.BodyColor); + } public bool SetPictureSize(int width, int height) { if (_drawningBoatWidth < width && _drawningBoatHeight < height) diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs index 53a489e..fcda9e0 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs @@ -9,6 +9,12 @@ public class DrawningMotorboat : DrawningBoat EntityBoat = new EntityMotorboat(speed, weight, bodyColor, additionalColor, motor, glass); } + + public DrawningMotorboat(EntityMotorboat boat) : base(129, 80) + { + EntityBoat = new EntityMotorboat(boat.Speed, boat.Weight, boat.BodyColor, boat.AdditionalColor, boat.Motor, boat.Glass); + } + public override void DrawTransport(Graphics g) { if (EntityBoat == null || EntityBoat is not EntityMotorboat motorboat|| !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs new file mode 100644 index 0000000..93a04ba --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs @@ -0,0 +1,54 @@ +using ProjectMotorboat.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMotorboat.Drownings; +public static class ExtentionDrawningBoat +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// + /// + public static DrawningBoat? CreateDrawningBoat(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityBoat? boat = EntityMotorboat.CreateEntityMotorboat(strs); + if (boat != null) + { + return new DrawningMotorboat((EntityMotorboat)boat); + } + + boat = EntityBoat.CreateEntityBoat(strs); + if (boat != null) + { + return new DrawningBoat(boat); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// + /// + public static string GetDataForSave(this DrawningBoat drawningBoat) + { + string[]? array = drawningBoat?.EntityBoat?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectMotorboat/ProjectMotorboat/Entities/EntityBoat.cs b/ProjectMotorboat/ProjectMotorboat/Entities/EntityBoat.cs index 73e61fe..d386dc6 100644 --- a/ProjectMotorboat/ProjectMotorboat/Entities/EntityBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Entities/EntityBoat.cs @@ -26,4 +26,23 @@ public class EntityBoat Weight = weight; BodyColor = bodyColor; } + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из строки + /// + /// + /// + public static EntityBoat? CreateEntityBoat(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityBoat)) + { + return null; + } + + return new EntityBoat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } } diff --git a/ProjectMotorboat/ProjectMotorboat/Entities/EntityMotorboat.cs b/ProjectMotorboat/ProjectMotorboat/Entities/EntityMotorboat.cs index 3632655..ef508b3 100644 --- a/ProjectMotorboat/ProjectMotorboat/Entities/EntityMotorboat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Entities/EntityMotorboat.cs @@ -20,4 +20,12 @@ public class EntityMotorboat : EntityBoat Motor = motor; Glass = glass; } + public static EntityMotorboat? CreateEntityMotorboat(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityMotorboat)) + { + return null; + } + return new EntityMotorboat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.Designer.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.Designer.cs index f0eb980..df9c8a7 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.Designer.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.Designer.cs @@ -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(1027, 0); + groupBoxTools.Location = new Point(1027, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(231, 746); + groupBoxTools.Size = new Size(231, 718); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -75,7 +82,7 @@ panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 418); + panelCompanyTools.Location = new Point(3, 390); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(225, 325); panelCompanyTools.TabIndex = 7; @@ -239,12 +246,49 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1027, 746); + pictureBox.Size = new Size(1027, 718); 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(1258, 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"; + // // FormBoatCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -252,6 +296,8 @@ ClientSize = new Size(1258, 746); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormBoatCollection"; Text = "Коллекция лодок"; groupBoxTools.ResumeLayout(false); @@ -260,7 +306,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +332,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/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs index e894fa7..d127340 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs @@ -1,5 +1,6 @@ using ProjectMotorboat.CollectionGenericObjects; using ProjectMotorboat.Drownings; +using System.Windows.Forms; namespace ProjectMotorboat; @@ -7,7 +8,7 @@ namespace ProjectMotorboat; /// Форма работы с компанией и ее коллекцией /// public partial class FormBoatCollection : Form -{ +{ private readonly StorageCollection _storageCollection; /// @@ -228,4 +229,35 @@ public partial class FormBoatCollection : Form panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } + + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + 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); + } + } + } } \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx index af32865..ee1748a 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 310, 17 + \ No newline at end of file