Лаба 6 готова.

This commit is contained in:
Андрей Байгулов 2023-11-26 23:57:23 +04:00
parent 127a678e28
commit 18d078a97e
4 changed files with 253 additions and 8 deletions

View File

@ -28,6 +28,7 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLocomotiveCollection));
panelLocomotiveCollection = new Panel(); panelLocomotiveCollection = new Panel();
groupBoxSets = new GroupBox(); groupBoxSets = new GroupBox();
textBoxSetName = new TextBox(); textBoxSetName = new TextBox();
@ -40,9 +41,16 @@
ButtonRemoveLocomotive = new Button(); ButtonRemoveLocomotive = new Button();
ButtonAddLocomotive = new Button(); ButtonAddLocomotive = new Button();
pictureBoxCollection = new PictureBox(); pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
panelLocomotiveCollection.SuspendLayout(); panelLocomotiveCollection.SuspendLayout();
groupBoxSets.SuspendLayout(); groupBoxSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// panelLocomotiveCollection // panelLocomotiveCollection
@ -56,9 +64,9 @@
panelLocomotiveCollection.Controls.Add(ButtonRemoveLocomotive); panelLocomotiveCollection.Controls.Add(ButtonRemoveLocomotive);
panelLocomotiveCollection.Controls.Add(ButtonAddLocomotive); panelLocomotiveCollection.Controls.Add(ButtonAddLocomotive);
panelLocomotiveCollection.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); panelLocomotiveCollection.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point);
panelLocomotiveCollection.Location = new Point(660, 2); panelLocomotiveCollection.Location = new Point(660, 27);
panelLocomotiveCollection.Name = "panelLocomotiveCollection"; panelLocomotiveCollection.Name = "panelLocomotiveCollection";
panelLocomotiveCollection.Size = new Size(248, 584); panelLocomotiveCollection.Size = new Size(248, 559);
panelLocomotiveCollection.TabIndex = 0; panelLocomotiveCollection.TabIndex = 0;
panelLocomotiveCollection.Tag = "Инструменты"; panelLocomotiveCollection.Tag = "Инструменты";
// //
@ -68,9 +76,9 @@
groupBoxSets.Controls.Add(buttonDeleteSet); groupBoxSets.Controls.Add(buttonDeleteSet);
groupBoxSets.Controls.Add(listBoxStorages); groupBoxSets.Controls.Add(listBoxStorages);
groupBoxSets.Controls.Add(buttonAddSet); groupBoxSets.Controls.Add(buttonAddSet);
groupBoxSets.Location = new Point(3, 15); groupBoxSets.Location = new Point(3, 25);
groupBoxSets.Name = "groupBoxSets"; groupBoxSets.Name = "groupBoxSets";
groupBoxSets.Size = new Size(242, 324); groupBoxSets.Size = new Size(242, 314);
groupBoxSets.TabIndex = 5; groupBoxSets.TabIndex = 5;
groupBoxSets.TabStop = false; groupBoxSets.TabStop = false;
groupBoxSets.Text = "Наборы"; groupBoxSets.Text = "Наборы";
@ -130,7 +138,7 @@
// //
// ButtonRefreshCollection // ButtonRefreshCollection
// //
ButtonRefreshCollection.Location = new Point(3, 530); ButtonRefreshCollection.Location = new Point(3, 505);
ButtonRefreshCollection.Name = "ButtonRefreshCollection"; ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(242, 43); ButtonRefreshCollection.Size = new Size(242, 43);
ButtonRefreshCollection.TabIndex = 2; ButtonRefreshCollection.TabIndex = 2;
@ -160,19 +168,65 @@
// //
// pictureBoxCollection // pictureBoxCollection
// //
pictureBoxCollection.Location = new Point(2, 2); pictureBoxCollection.Location = new Point(2, 27);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(655, 584); pictureBoxCollection.Size = new Size(655, 560);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
// //
// menuStrip
//
menuStrip.GripStyle = ToolStripGripStyle.Visible;
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(909, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, SaveToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "&Файл";
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Image = (Image)resources.GetObject("LoadToolStripMenuItem.Image");
LoadToolStripMenuItem.ImageTransparentColor = Color.Magenta;
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Image = (Image)resources.GetObject("SaveToolStripMenuItem.Image");
SaveToolStripMenuItem.ImageTransparentColor = Color.Magenta;
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
//
// FormLocomotiveCollection // FormLocomotiveCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(909, 587); ClientSize = new Size(909, 587);
Controls.Add(pictureBoxCollection); Controls.Add(menuStrip);
Controls.Add(panelLocomotiveCollection); Controls.Add(panelLocomotiveCollection);
Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip;
Name = "FormLocomotiveCollection"; Name = "FormLocomotiveCollection";
Text = "Набор локомотивов"; Text = "Набор локомотивов";
panelLocomotiveCollection.ResumeLayout(false); panelLocomotiveCollection.ResumeLayout(false);
@ -180,7 +234,10 @@
groupBoxSets.ResumeLayout(false); groupBoxSets.ResumeLayout(false);
groupBoxSets.PerformLayout(); groupBoxSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -196,5 +253,11 @@
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Button buttonAddSet; private Button buttonAddSet;
private TextBox textBoxSetName; private TextBox textBoxSetName;
private MenuStrip menuStrip;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
} }
} }

View File

@ -132,5 +132,48 @@ namespace ProjectElectricLocomotive
ReloadObjects(); ReloadObjects();
} }
} }
/// <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("Load is done!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
}
else
{
MessageBox.Show("Load is fail!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -117,4 +117,37 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>19, 13</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="LoadToolStripMenuItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAFUSURBVDhPlZK9SgNBFIXnCcQnkLyA4CPkHayFdBY22mqj
paVlxCKCoBaClUQLESNRC4OE4EKQrAbcYBKy62Z/ynHOzUwcMzuyDhzYGc795tw7y2ZXFEVLSZI8p2la
kkf5lywO1vZr/MH54LkhwlgQKsZxvC4AfHHjjM+tHOaDiKIKiqDqk0s6rbUJoCDCsy3t5kJh+bJFZrZ8
YGhh9ZjgSIeUUgVZPgHot2HfGwbTNu4aTf75UuW+50wVhSMAKwRwugO6aevokYohfQbDzj1/vdj8pffb
PfJREpUAEPSOvXoFBdSFBIDgmxIgTr3lEkRPYZMOwDwYDtzrXToATPVp06B9QwB8o4YAipjVr02dqx0T
gOHMGm3qNc8nL6EAX33XMP2l8cj7mQEOvMaJYbKpWy/zMAzf6BVE9ADF6CnLnCXMCn8mAUSMEiCYwX/k
+/48Y4x9AwxhsnXBwZZBAAAAAElFTkSuQmCC
</value>
</data>
<data name="SaveToolStripMenuItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABzSURBVDhPY/j69WvDt2/f/pODQXoZQIyYCfv+MwTPIQmD
9ID0gg3ApoAYjGHAh/cficLD2QBS8SA1AJufkTGyWtoagM5HFwdhmAEfkPMCukJkzcjiIAw24MuXLwbI
hqArRNaMLA7CYANAAGYISIA0/O0/AID67ECmnhNDAAAAAElFTkSuQmCC
</value>
</data>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>134, 11</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>269, 13</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>62</value>
</metadata>
</root> </root>

View File

@ -20,6 +20,18 @@ namespace ProjectElectricLocomotive
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _locomotivesStorage.Keys.ToList(); public List<string> Keys => _locomotivesStorage.Keys.ToList();
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
private readonly int _pictureWidth; private readonly int _pictureWidth;
@ -79,5 +91,99 @@ namespace ProjectElectricLocomotive
return null; return null;
} }
} }
/// <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,
LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>> record in _locomotivesStorage)
{
StringBuilder records = new();
foreach (DrawingLocomotive? elem in record.Value.GetLocomotives)
{
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;
}
_locomotivesStorage.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
LocomotivesGenericCollection<DrawingLocomotive, DrawingObjectLocomotive>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingLocomotive? loco = elem?.CreateDrawningCar(_separatorForObject, _pictureWidth, _pictureHeight);
if (loco != null)
{
if (collection + loco == -1)
{
return false;
}
}
}
_locomotivesStorage.Add(record[0], collection);
}
return true;
}
} }
} }