From e9d5335db915aef3d295b13e7c49ae2f7c258e8f Mon Sep 17 00:00:00 2001 From: chtzsch ~ Date: Tue, 28 Nov 2023 20:44:01 +0300 Subject: [PATCH 1/4] lab_6 --- .../speed_Boat/BoatsGenericCollection.cs | 8 +- speed_Boat/speed_Boat/BoatsGenericStorage.cs | 109 +++++++++++++++++- speed_Boat/speed_Boat/ExtentionBoat.cs | 65 +++++++++++ .../speed_Boat/FormBoatCollection.Designer.cs | 64 +++++++++- speed_Boat/speed_Boat/FormBoatCollection.cs | 43 +++++++ speed_Boat/speed_Boat/FormBoatCollection.resx | 9 ++ 6 files changed, 292 insertions(+), 6 deletions(-) create mode 100644 speed_Boat/speed_Boat/ExtentionBoat.cs 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..1bc84f0 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,99 @@ 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 FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return true; + } + /// + /// Загрузка информации по катерам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + 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); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].StartsWith("BoatStorage")) + { + //если нет такой записи, то это не те данные + return false; + } + _boatStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + 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); + } + 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..3feaea5 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -191,5 +191,48 @@ namespace SpeedBoatLab } pictureBoxCollection.Image = obj.ShowBoats(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + 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 -- 2.25.1 From 51f2664d20579c0931c276d1a0fe9971bb396cc5 Mon Sep 17 00:00:00 2001 From: chtzsch ~ Date: Tue, 28 Nov 2023 22:34:30 +0300 Subject: [PATCH 2/4] lab_6(storage) --- speed_Boat/speed_Boat/BoatsGenericStorage.cs | 73 ++++++++++---------- 1 file changed, 35 insertions(+), 38 deletions(-) diff --git a/speed_Boat/speed_Boat/BoatsGenericStorage.cs b/speed_Boat/speed_Boat/BoatsGenericStorage.cs index 1bc84f0..281c2e6 100644 --- a/speed_Boat/speed_Boat/BoatsGenericStorage.cs +++ b/speed_Boat/speed_Boat/BoatsGenericStorage.cs @@ -80,10 +80,11 @@ namespace speed_Boat.Generics { return false; } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new - UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}"); - fs.Write(info, 0, info.Length); + + using (StreamWriter sw = new (filename)) + { + sw.WriteLine($"BoatStorage{Environment.NewLine}{data}"); + } return true; } /// @@ -98,50 +99,46 @@ namespace speed_Boat.Generics return false; } string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader sr = new(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str = sr.ReadLine(); + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) { - bufferTextFromFile += temp.GetString(b); + return false; } - } - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].StartsWith("BoatStorage")) - { - //если нет такой записи, то это не те данные - return false; - } - _boatStorages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + if (!strs[0].StartsWith("BoatStorage")) { - continue; + //если нет такой записи, то это не те данные + return false; } - BoatsGenericCollection - collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + _boatStorages.Clear(); + do { - DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); - if (boat != null) + string[] record = str.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - if (!(collection + boat)) + 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) { - return false; + if (!(collection + boat)) + { + return false; + } } } - } - _boatStorages.Add(record[0], collection); + _boatStorages.Add(record[0], collection); + str = sr.ReadLine(); + } while (str != null); } return true; } -- 2.25.1 From 1f7f3bdc1df55c870eb90213df86390955b2ae68 Mon Sep 17 00:00:00 2001 From: chtzsch ~ Date: Tue, 28 Nov 2023 22:39:23 +0300 Subject: [PATCH 3/4] lab_6 --- speed_Boat/speed_Boat/BoatsGenericStorage.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/speed_Boat/speed_Boat/BoatsGenericStorage.cs b/speed_Boat/speed_Boat/BoatsGenericStorage.cs index 281c2e6..f0d7b88 100644 --- a/speed_Boat/speed_Boat/BoatsGenericStorage.cs +++ b/speed_Boat/speed_Boat/BoatsGenericStorage.cs @@ -102,7 +102,7 @@ namespace speed_Boat.Generics using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { return false; -- 2.25.1 From bc39a6b65d05f291e5799bc3d92fdd5ab4083098 Mon Sep 17 00:00:00 2001 From: chtzsch ~ Date: Wed, 29 Nov 2023 12:44:55 +0300 Subject: [PATCH 4/4] lab_6 --- speed_Boat/speed_Boat/FormBoatCollection.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/speed_Boat/speed_Boat/FormBoatCollection.cs b/speed_Boat/speed_Boat/FormBoatCollection.cs index 3feaea5..f1d64f8 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -183,8 +183,7 @@ namespace SpeedBoatLab { return; } - var obj = _storage[storagesListBox.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -199,6 +198,10 @@ namespace SpeedBoatLab /// private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { + if (storagesListBox.SelectedIndex == -1) + { + return; + } if (saveFileDialog.ShowDialog() == DialogResult.OK) { if (_storage.SaveData(saveFileDialog.FileName)) @@ -222,12 +225,12 @@ namespace SpeedBoatLab if (_storage.LoadData(saveFileDialog.FileName)) { ReloadObjects(); - MessageBox.Show("Сохранение прошло успешно", + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } -- 2.25.1