Лаба 6. Осталось доработать форму

This commit is contained in:
bulatova_karina 2023-11-21 16:48:30 +03:00
parent 6fe7112791
commit 4f3c6390c4
6 changed files with 275 additions and 9 deletions

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawingObjects
{
public static class ExtentionDrawingShip
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingWarmlyShip? CreateDrawingShip(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingWarmlyShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawingWarmlyShipWithPipes(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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingWarmlyShip drawingShip,
char separatorForObject)
{
var ship = drawingShip.EntityWarmlyShip;
if (ship == null)
{
return string.Empty;
}
var str =
$"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityWarmlyShipWithPipes warmlyShip)
{
return str;
}
return
$"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.Pipes}{separatorForObject}{warmlyShip.Section}";
}
}
}

View File

@ -40,16 +40,21 @@
this.buttonRefreshCollection = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonAddShip = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelCollection.SuspendLayout();
this.groupBoxSets.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(864, 536);
this.pictureBoxCollection.Size = new System.Drawing.Size(864, 625);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
@ -61,9 +66,10 @@
this.panelCollection.Controls.Add(this.buttonRefreshCollection);
this.panelCollection.Controls.Add(this.buttonRemoveShip);
this.panelCollection.Controls.Add(this.buttonAddShip);
this.panelCollection.Controls.Add(this.menuStrip1);
this.panelCollection.Location = new System.Drawing.Point(870, 0);
this.panelCollection.Name = "panelCollection";
this.panelCollection.Size = new System.Drawing.Size(218, 536);
this.panelCollection.Size = new System.Drawing.Size(218, 625);
this.panelCollection.TabIndex = 1;
//
// groupBoxSets
@ -72,7 +78,7 @@
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.buttonnAddObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Location = new System.Drawing.Point(12, 42);
this.groupBoxSets.Location = new System.Drawing.Point(12, 131);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(199, 242);
this.groupBoxSets.TabIndex = 7;
@ -118,7 +124,7 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 375);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 455);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(171, 27);
this.maskedTextBoxNumber.TabIndex = 6;
@ -126,7 +132,7 @@
// labelCollection
//
this.labelCollection.AutoSize = true;
this.labelCollection.Location = new System.Drawing.Point(3, 9);
this.labelCollection.Location = new System.Drawing.Point(3, 97);
this.labelCollection.Name = "labelCollection";
this.labelCollection.Size = new System.Drawing.Size(103, 20);
this.labelCollection.TabIndex = 2;
@ -134,7 +140,7 @@
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(16, 482);
this.buttonRefreshCollection.Location = new System.Drawing.Point(16, 575);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(171, 40);
this.buttonRefreshCollection.TabIndex = 5;
@ -144,7 +150,7 @@
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 424);
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 515);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(171, 40);
this.buttonRemoveShip.TabIndex = 4;
@ -154,7 +160,7 @@
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(16, 309);
this.buttonAddShip.Location = new System.Drawing.Point(16, 388);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(171, 40);
this.buttonAddShip.TabIndex = 2;
@ -162,13 +168,46 @@
this.buttonAddShip.UseVisualStyleBackColor = true;
this.buttonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(218, 28);
this.menuStrip1.TabIndex = 8;
this.menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.сохранениеToolStripMenuItem,
this.загрузкаToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.файлToolStripMenuItem.Text = "Файл";
//
// сохранениеToolStripMenuItem
//
this.сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.сохранениеToolStripMenuItem.Text = "Сохранение";
//
// загрузкаToolStripMenuItem
//
this.загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.загрузкаToolStripMenuItem.Text = "Загрузка";
//
// FormShipCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1093, 534);
this.ClientSize = new System.Drawing.Size(1093, 627);
this.Controls.Add(this.panelCollection);
this.Controls.Add(this.pictureBoxCollection);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormShipCollection";
this.Text = "Набор теплоходов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
@ -176,6 +215,8 @@
this.panelCollection.PerformLayout();
this.groupBoxSets.ResumeLayout(false);
this.groupBoxSets.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
}
@ -194,5 +235,9 @@
private Button buttonnAddObject;
private ListBox listBoxStorages;
private TextBox textBoxStorageName;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
}
}

View File

@ -207,6 +207,50 @@ namespace WarmlyShip
}
pictureBoxCollection.Image = obj.ShowShips();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
}
}
}

View File

@ -57,4 +57,7 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -14,6 +14,10 @@ namespace WarmlyShip.Generics
where T : DrawingWarmlyShip
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetShips => _collection.GetShips();
/// <summary>
/// Ширина окна прорисовки
/// </summary>

View File

@ -81,5 +81,110 @@ namespace WarmlyShip.Generics
return null;
}
}
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawingWarmlyShip? elem in record.Value.GetShips)
{
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($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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("CarStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_shipStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarmlyShip? ship = elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
if (!(collection + ship))
{
return false;
}
}
}
_shipStorages.Add(record[0], collection);
}
return true;
}
}
}