diff --git a/speed_Boat/speed_Boat/BoatsGenericCollection.cs b/speed_Boat/speed_Boat/BoatsGenericCollection.cs index 0da3495..6ad0924 100644 --- a/speed_Boat/speed_Boat/BoatsGenericCollection.cs +++ b/speed_Boat/speed_Boat/BoatsGenericCollection.cs @@ -14,6 +14,10 @@ namespace speed_Boat.Generics where T : DrawingBoat where U : IMovementObject { + /// + /// Получение объектов коллекции + /// + public IEnumerable GetBoats => _collection.GetBoats(); /// /// Ширина окна прорисовки /// @@ -119,10 +123,10 @@ namespace speed_Boat.Generics int width_Col = _pictureWidth / _placeSizeWidth;//количество колонок в окне прорисовки foreach (var boat in _collection.GetBoats()) { - boat.screenWidth = _pictureWidth; - boat.screenHeight = _pictureHeight; if(boat != null) { + boat.screenWidth = _pictureWidth; + boat.screenHeight = _pictureHeight; boat.SetPosition(col * _placeSizeWidth, (i / width_Col) * _placeSizeHeight); col++; if (col > 2) diff --git a/speed_Boat/speed_Boat/BoatsGenericStorage.cs b/speed_Boat/speed_Boat/BoatsGenericStorage.cs index c8ce9ad..f0d7b88 100644 --- a/speed_Boat/speed_Boat/BoatsGenericStorage.cs +++ b/speed_Boat/speed_Boat/BoatsGenericStorage.cs @@ -2,6 +2,7 @@ using SpeedBoatLab.Drawings; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -30,6 +31,20 @@ namespace speed_Boat.Generics /// Высота окна отрисовки /// private readonly int _pictureHeight; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// @@ -39,7 +54,96 @@ namespace speed_Boat.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } + + /// + /// Сохранение информации по катерам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _boatStorages) + { + StringBuilder records = new(); + foreach (DrawingBoat? elem in record.Value.GetBoats) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using (StreamWriter sw = new (filename)) + { + sw.WriteLine($"BoatStorage{Environment.NewLine}{data}"); + } + return true; + } + /// + /// Загрузка информации по катерам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + string bufferTextFromFile = ""; + using (StreamReader sr = new(filename)) + { + string str = sr.ReadLine(); + var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("BoatStorage")) + { + //если нет такой записи, то это не те данные + return false; + } + _boatStorages.Clear(); + do + { + string[] record = str.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + str = sr.ReadLine(); + continue; + } + BoatsGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); + if (boat != null) + { + if (!(collection + boat)) + { + return false; + } + } + } + _boatStorages.Add(record[0], collection); + str = sr.ReadLine(); + } while (str != null); + } + return true; + } + + /// /// Добавление набора /// diff --git a/speed_Boat/speed_Boat/ExtentionBoat.cs b/speed_Boat/speed_Boat/ExtentionBoat.cs new file mode 100644 index 0000000..7d87297 --- /dev/null +++ b/speed_Boat/speed_Boat/ExtentionBoat.cs @@ -0,0 +1,65 @@ +using SpeedBoatLab.Entity; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SpeedBoatLab.Drawings +{ + public static class ExtentionBoat + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель данных + /// Ширина + /// Высота + /// Объект + public static DrawingBoat? CreateDrawingBoat(this string info, char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3) + { + return new DrawingBoat(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height); + } + if (strs.Length == 6) + { + return new DrawingSpeedBoat(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + Color.FromName(strs[3]), + Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5]), width, height); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Разделитель данных + /// Строка с данными по объекту + public static string GetDataForSave(this DrawingBoat drawingBoat, char separatorForObject) + { + var boat = drawingBoat._entityBoat; + if (boat == null) + { + return string.Empty; + } + var str = + $"{boat.Speed}{separatorForObject}{boat.Weight}{separatorForObject}{boat.MainColor.Name}"; + if (boat is not EntitySpeedboat speedBoat) + { + return str; + } + return + $"{str}{separatorForObject}{speedBoat.SecondColor.Name}{separatorForObject}" + + $"{speedBoat.isMotor}{separatorForObject}{speedBoat.isProtectedGlass}"; + } + + } +} diff --git a/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs b/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs index 7368c60..38de93d 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.Designer.cs @@ -40,9 +40,16 @@ namespace SpeedBoatLab UpdateCollectionButton = new System.Windows.Forms.Button(); DeleteBoatButton = new System.Windows.Forms.Button(); AddBoatButton = new System.Windows.Forms.Button(); + menuStrip1 = new System.Windows.Forms.MenuStrip(); + файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); pictureBoxCollection = new System.Windows.Forms.PictureBox(); + openFileDialog = new System.Windows.Forms.OpenFileDialog(); + saveFileDialog = new System.Windows.Forms.SaveFileDialog(); groupBox1.SuspendLayout(); groupBox2.SuspendLayout(); + menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); SuspendLayout(); // @@ -54,9 +61,10 @@ namespace SpeedBoatLab groupBox1.Controls.Add(UpdateCollectionButton); groupBox1.Controls.Add(DeleteBoatButton); groupBox1.Controls.Add(AddBoatButton); + groupBox1.Controls.Add(menuStrip1); groupBox1.Location = new System.Drawing.Point(581, 2); groupBox1.Name = "groupBox1"; - groupBox1.Size = new System.Drawing.Size(205, 436); + groupBox1.Size = new System.Drawing.Size(205, 471); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Настройки"; @@ -157,27 +165,71 @@ namespace SpeedBoatLab AddBoatButton.UseVisualStyleBackColor = true; AddBoatButton.Click += ButtonAddBoat_Click; // + // menuStrip1 + // + menuStrip1.Dock = System.Windows.Forms.DockStyle.Bottom; + menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); + menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { файлToolStripMenuItem }); + menuStrip1.Location = new System.Drawing.Point(3, 440); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new System.Drawing.Size(199, 28); + menuStrip1.TabIndex = 6; + menuStrip1.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { загрузкаToolStripMenuItem, сохранениеToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24); + файлToolStripMenuItem.Text = "Файл"; + // + // загрузкаToolStripMenuItem + // + загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem"; + загрузкаToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + загрузкаToolStripMenuItem.Text = "Загрузка"; + загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // сохранениеToolStripMenuItem + // + сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; + сохранениеToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + сохранениеToolStripMenuItem.Text = "Сохранение"; + сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // // pictureBoxCollection // pictureBoxCollection.Location = new System.Drawing.Point(12, 12); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new System.Drawing.Size(554, 425); + pictureBoxCollection.Size = new System.Drawing.Size(554, 527); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormBoatCollection // AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - ClientSize = new System.Drawing.Size(800, 450); + ClientSize = new System.Drawing.Size(800, 551); Controls.Add(pictureBoxCollection); Controls.Add(groupBox1); + MainMenuStrip = menuStrip1; Name = "FormBoatCollection"; Text = "Коллекция катеров"; groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ResumeLayout(false); } @@ -196,5 +248,11 @@ namespace SpeedBoatLab private System.Windows.Forms.Button addStorageButton; private System.Windows.Forms.TextBox nameStorageTextBox; private System.Windows.Forms.Button deleteStorageButton; + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem загрузкаToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem сохранениеToolStripMenuItem; + private System.Windows.Forms.OpenFileDialog openFileDialog; + private System.Windows.Forms.SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/speed_Boat/speed_Boat/FormBoatCollection.cs b/speed_Boat/speed_Boat/FormBoatCollection.cs index 3bbd817..f1d64f8 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -183,13 +183,59 @@ namespace SpeedBoatLab { return; } - var obj = _storage[storagesListBox.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } pictureBoxCollection.Image = obj.ShowBoats(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (storagesListBox.SelectedIndex == -1) + { + return; + } + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.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 (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.LoadData(saveFileDialog.FileName)) + { + ReloadObjects(); + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + } + } } diff --git a/speed_Boat/speed_Boat/FormBoatCollection.resx b/speed_Boat/speed_Boat/FormBoatCollection.resx index af32865..b9db4d6 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.resx +++ b/speed_Boat/speed_Boat/FormBoatCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 153, 17 + + + 323, 17 + \ No newline at end of file