From 2a1cb4dec399e20120c4782baf04247b6749e891 Mon Sep 17 00:00:00 2001 From: bekodeg Date: Tue, 28 Nov 2023 14:16:01 +0400 Subject: [PATCH 1/3] =?UTF-8?q?6=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20?= =?UTF-8?q?=D0=B1=D0=B0=D0=B7=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExtentionDrawningLocomotive.cs | 72 +++++++++++ .../FormLocomotiveCollection.Designer.cs | 52 +++++++- .../FormLocomotiveCollection.cs | 10 ++ .../FormLocomotiveCollection.resx | 3 + .../Generics/LocomotivesGenericCollection.cs | 4 + .../Generics/LocomotivesGenericStorage.cs | 113 ++++++++++++++++++ .../LogicFormLocomotiveCollection.cs | 51 +++++++- .../LogicFormLocomotiveConfig.cs | 2 + 8 files changed, 301 insertions(+), 6 deletions(-) create mode 100644 ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs diff --git a/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs new file mode 100644 index 0000000..112673f --- /dev/null +++ b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs @@ -0,0 +1,72 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.DrawningObjects +{ + /// + /// Расширение для класса EntityCar + /// + public static class ExtentionDrawningLocomotive + { + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Разделитель даннных + /// Ширина + /// Высота + /// Объект + public static DrawningLocomotive? CreateDrawningLocomotive(this string info, char separatorForObject, int width, int height) + { + string[] strs = info.Split(separatorForObject); + if (strs.Length == 3 ) { + return new DrawningLocomotive( + Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), + Color.FromName(strs[2]), + width, height); + } + if (strs.Length == 6) { + return new DrawningElectricLocomotive( + 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 DrawningLocomotive drawningLocomotive, char separatorForObject) + { + var locomotive = drawningLocomotive.EntityLocomotive; + if (locomotive == null) + { + return string.Empty; + } + var str = + $"{locomotive.Speed}{separatorForObject}" + + $"{locomotive.Weight}{separatorForObject}" + + $"{locomotive.BodyColor.Name}"; + if (locomotive is not EntityElectricLocomotive electricLocomotive) + { + return str; + } + return $"{str}{separatorForObject}" + + $"{electricLocomotive.AdditionalColor}{separatorForObject}" + + $"{electricLocomotive.Horns}{separatorForObject}" + + $"{electricLocomotive.Battery}"; + } + } +} diff --git a/ElectricLocomotive/FormLocomotiveCollection.Designer.cs b/ElectricLocomotive/FormLocomotiveCollection.Designer.cs index a8bdfd8..bd9649b 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.Designer.cs +++ b/ElectricLocomotive/FormLocomotiveCollection.Designer.cs @@ -40,10 +40,15 @@ buttonRefreshCollection = new Button(); buttonRemoveLocomotive = new Button(); buttonAddLocomotive = new Button(); + menuStrip1 = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); groupBox1.SuspendLayout(); groupBox2.SuspendLayout(); + menuStrip1.SuspendLayout(); SuspendLayout(); // // tableLayoutPanel1 @@ -55,11 +60,11 @@ tableLayoutPanel1.Controls.Add(pictureBoxCollection, 0, 0); tableLayoutPanel1.Controls.Add(groupBox1, 1, 0); tableLayoutPanel1.Dock = DockStyle.Fill; - tableLayoutPanel1.Location = new Point(0, 0); + tableLayoutPanel1.Location = new Point(0, 28); tableLayoutPanel1.Name = "tableLayoutPanel1"; tableLayoutPanel1.RowCount = 1; tableLayoutPanel1.RowStyles.Add(new RowStyle()); - tableLayoutPanel1.Size = new Size(885, 449); + tableLayoutPanel1.Size = new Size(885, 453); tableLayoutPanel1.TabIndex = 0; // // pictureBoxCollection @@ -68,7 +73,7 @@ pictureBoxCollection.Location = new Point(3, 3); pictureBoxCollection.MinimumSize = new Size(100, 100); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(673, 444); + pictureBoxCollection.Size = new Size(673, 447); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // @@ -178,12 +183,45 @@ buttonAddLocomotive.UseVisualStyleBackColor = true; buttonAddLocomotive.Click += buttonAddLocomotive_Click; // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(885, 28); + menuStrip1.TabIndex = 1; + menuStrip1.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(59, 24); + fileToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.Size = new Size(224, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.Size = new Size(224, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // // FormLocomotiveCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(885, 449); + ClientSize = new Size(885, 481); Controls.Add(tableLayoutPanel1); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; MinimumSize = new Size(700, 400); Name = "FormLocomotiveCollection"; Text = "FormLocomotiveCollection"; @@ -193,6 +231,8 @@ groupBox1.PerformLayout(); groupBox2.ResumeLayout(false); groupBox2.PerformLayout(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ResumeLayout(false); PerformLayout(); } @@ -211,5 +251,9 @@ private Button buttonAddObject; private ListBox listBoxStorages; private Button buttonDelObject; + private MenuStrip menuStrip1; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; } } \ No newline at end of file diff --git a/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/FormLocomotiveCollection.cs index 5b3fab0..1b8a281 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/FormLocomotiveCollection.cs @@ -40,5 +40,15 @@ namespace ProjectElectricLocomotive { ListBoxObjects_SelectedIndexChanged(sender, e); } + + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + SaveToolStripMenuItem_Click(sender, e); + } + + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + LoadToolStripMenuItem_Click(sender, e); + } } } diff --git a/ElectricLocomotive/FormLocomotiveCollection.resx b/ElectricLocomotive/FormLocomotiveCollection.resx index af32865..a0623c8 100644 --- a/ElectricLocomotive/FormLocomotiveCollection.resx +++ b/ElectricLocomotive/FormLocomotiveCollection.resx @@ -117,4 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + \ No newline at end of file diff --git a/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs index a77769e..43335fa 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs @@ -146,5 +146,9 @@ namespace ProjectElectricLocomotive.Generics } } } + /// + /// Получение объектов коллекции + /// + public IEnumerable GetCars => _collection.GetLocomotives(); } } \ No newline at end of file diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs index e7b044b..5317ad7 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs @@ -35,6 +35,19 @@ namespace ProjectElectricLocomotive.Generics /// private readonly int _pictureHeight; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private static readonly char _separatorForKeyValue = '|'; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly char _separatorRecords = ';'; + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly char _separatorForObject = ':'; + /// /// Конструктор /// @@ -92,5 +105,105 @@ namespace ProjectElectricLocomotive.Generics return null; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// + public bool SaveData(string filename) { + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder data = new(); + foreach ( + KeyValuePair> + record in _locomotiveStorage) + { + StringBuilder records = new(); + foreach (DrawningLocomotive? elem in record.Value.GetCars) + { + records.Append( + $"{elem?.GetDataForSave(_separatorForObject)}" + + $"{_separatorRecords}"); + } + data.Append($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + return false; + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes( + $"LocomotiveStorage{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("LocomotiveStorage")) + { + //если нет такой записи, то это не те данные + return false; + } + strs = strs[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + _locomotiveStorage.Clear(); + foreach (string data in strs) + { + string[] record = data.Split( + _separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + LocomotivesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningLocomotive? locomotive = + elem?.CreateDrawningLocomotive( + _separatorForObject, + _pictureWidth, _pictureHeight); + if (locomotive != null) + { + if ((collection + locomotive) == 0) + { + return false; + } + } + } + _locomotiveStorage.Add(record[0], collection); + } + return true; + } } } diff --git a/ElectricLocomotive/LogicFormLocomotiveCollection.cs b/ElectricLocomotive/LogicFormLocomotiveCollection.cs index 524dabb..1acefcd 100644 --- a/ElectricLocomotive/LogicFormLocomotiveCollection.cs +++ b/ElectricLocomotive/LogicFormLocomotiveCollection.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Windows.Forms; using ProjectElectricLocomotive.DrawningObjects; using ProjectElectricLocomotive.Generics; using ProjectElectricLocomotive.MovementStrategy; @@ -124,7 +125,7 @@ namespace ProjectElectricLocomotive if (obj + SelectedLocomotive > 0) { MessageBox.Show("Объект добавлен"); - + pictureBoxCollection.Image = obj.ShowLocomotives(); } else @@ -159,7 +160,8 @@ namespace ProjectElectricLocomotive try { pos = Convert.ToInt32(maskedTextBoxNumber.Text); - } catch(System.FormatException ex) + } + catch (System.FormatException ex) { pos = 0; } @@ -191,5 +193,50 @@ namespace ProjectElectricLocomotive } pictureBoxCollection.Image = obj.ShowLocomotives(); } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + SaveFileDialog saveFileDialog = new SaveFileDialog(); + saveFileDialog.Filter = "txt file | *.txt"; + saveFileDialog.Title = "Сохранение"; + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadToolStripMenuItem_Click(object sendee, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Filter = "txt file | *.txt"; + openFileDialog.Title = "Загрузка"; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storage.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + ReloadObjects(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/ElectricLocomotive/LogicFormLocomotiveConfig.cs b/ElectricLocomotive/LogicFormLocomotiveConfig.cs index a62e59e..38942c2 100644 --- a/ElectricLocomotive/LogicFormLocomotiveConfig.cs +++ b/ElectricLocomotive/LogicFormLocomotiveConfig.cs @@ -16,6 +16,8 @@ namespace ProjectElectricLocomotive /// DrawningLocomotive? _locomotive = null; + public delegate Object Func(); + /// /// Событие /// -- 2.25.1 From b86d3af35ec862770cbfcb3b0fd8815931c88d26 Mon Sep 17 00:00:00 2001 From: bekodeg Date: Tue, 28 Nov 2023 17:09:44 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=20=D0=B1=D0=B0?= =?UTF-8?q?=D0=B3=D0=BE=D0=B2=20=D1=81=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ElectricLocomotive/Generics/LocomotivesGenericStorage.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs index 5317ad7..ddc84fb 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs @@ -129,7 +129,7 @@ namespace ProjectElectricLocomotive.Generics $"{elem?.GetDataForSave(_separatorForObject)}" + $"{_separatorRecords}"); } - data.Append($"{record.Key}{_separatorForKeyValue}{records}"); + data.Append($"{record.Key}{_separatorForKeyValue}{records}{Environment.NewLine}"); } if (data.Length == 0) { @@ -174,7 +174,6 @@ namespace ProjectElectricLocomotive.Generics //если нет такой записи, то это не те данные return false; } - strs = strs[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); _locomotiveStorage.Clear(); foreach (string data in strs) { @@ -187,6 +186,7 @@ namespace ProjectElectricLocomotive.Generics LocomotivesGenericCollection collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + Array.Reverse(set); foreach (string elem in set) { DrawningLocomotive? locomotive = -- 2.25.1 From 6da4c51da629af2961954e02de96f096a516cce9 Mon Sep 17 00:00:00 2001 From: bekodeg Date: Wed, 6 Dec 2023 10:04:33 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=206=20?= =?UTF-8?q?=D0=B1=D0=B5=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Generics/LocomotivesGenericStorage.cs | 111 ++++++++---------- 1 file changed, 50 insertions(+), 61 deletions(-) diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs index ddc84fb..b10a6c2 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs @@ -110,37 +110,38 @@ namespace ProjectElectricLocomotive.Generics /// /// Путь и имя файла /// - public bool SaveData(string filename) { + public bool SaveData(string filename) + { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); - foreach ( - KeyValuePair> - record in _locomotiveStorage) + using (StreamWriter sw = new StreamWriter(filename)) { - StringBuilder records = new(); - foreach (DrawningLocomotive? elem in record.Value.GetCars) + sw.WriteLine("LocomotiveStorage"); + if (_locomotiveStorage.Count == 0) { - records.Append( - $"{elem?.GetDataForSave(_separatorForObject)}" + - $"{_separatorRecords}"); + return false; } - data.Append($"{record.Key}{_separatorForKeyValue}{records}{Environment.NewLine}"); + foreach ( + KeyValuePair> + record in _locomotiveStorage) + { + sw.Write(record.Key); + sw.Write(_separatorForKeyValue); + foreach (DrawningLocomotive? elem in record.Value.GetCars) + { + sw.Write( + $"{elem?.GetDataForSave(_separatorForObject)}" + + $"{_separatorRecords}"); + } + sw.WriteLine(); + } + return true; } - if (data.Length == 0) - { - return false; - } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new - UTF8Encoding(true).GetBytes( - $"LocomotiveStorage{Environment.NewLine}{data}"); - fs.Write(info, 0, info.Length); - return true; } /// /// Загрузка информации по Локомативам в хранилище из файла @@ -154,56 +155,44 @@ namespace ProjectElectricLocomotive.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 line; + if (!((line = sr.ReadLine() != null) && line.StartsWith("LocomotiveStorage"))) { - 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("LocomotiveStorage")) - { - //если нет такой записи, то это не те данные - return false; - } - _locomotiveStorage.Clear(); - foreach (string data in strs) - { - string[] record = data.Split( - _separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + _locomotiveStorage.Clear(); + while ((line = sr.ReadLine()) != null) { - continue; - } - LocomotivesGenericCollection - collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - Array.Reverse(set); - foreach (string elem in set) - { - DrawningLocomotive? locomotive = - elem?.CreateDrawningLocomotive( - _separatorForObject, - _pictureWidth, _pictureHeight); - if (locomotive != null) + string[] record = line.Split( + _separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - if ((collection + locomotive) == 0) + continue; + } + LocomotivesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningLocomotive? locomotive = + elem?.CreateDrawningLocomotive( + _separatorForObject, + _pictureWidth, _pictureHeight); + if (locomotive != null) { - return false; + if ((collection + locomotive) == 0) + { + return false; + } } } + _locomotiveStorage.Add(record[0], collection); } - _locomotiveStorage.Add(record[0], collection); + return true; } - return true; } } } -- 2.25.1