ПИбд-23 Тихоненков А.Е. Лабораторная №6 #14

Closed
YourDax wants to merge 2 commits from Lab6 into Lab5
6 changed files with 273 additions and 4 deletions

View File

@ -0,0 +1,46 @@
using AntiAircraftGun.Enitites;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.DrawingObjects
{
public static class ExtentionDrawningAntiAirCraftGun
{
public static BaseDrawingAntiAirCraftGun? CreateDrawningAntiAirCraftGun(this string info, char separatorForObject,int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 4)
{
return new BaseDrawingAntiAirCraftGun(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), Color.FromName(strs[3]),
width, height);
}
if (strs.Length == 7)
{
return new AdvancedDrawingAntiAirCraftGun(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), width, height);
}
return null;
}
public static string GetDataForSave(this BaseDrawingAntiAirCraftGun drawningAntiAirCraftGun, char separatorForObject)
{
var zenit = drawningAntiAirCraftGun.AntiAirСraftGun;
if (zenit == null)
{
return string.Empty;
}
var str = $"{zenit.Speed}{separatorForObject}{zenit.Weight}{separatorForObject}{zenit.BodyColor.Name}{separatorForObject}{zenit.AdditionalColor.Name}";
if (zenit is not EntityAdvancedAntiAirCraftGun antiAirCraftGun)
{
return str;
}
return
$"{str}{separatorForObject}{antiAirCraftGun.DopColor.Name}{separatorForObject}{antiAirCraftGun.Radar}{separatorForObject}{antiAirCraftGun.Rocket}";
}
}
}

View File

@ -39,14 +39,21 @@
this.buttonUpdateColletion = new System.Windows.Forms.Button();
this.buttonDeleteZenit = new System.Windows.Forms.Button();
this.buttonAddZenit = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelTools.SuspendLayout();
this.panel1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(12, 12);
this.pictureBoxCollection.Location = new System.Drawing.Point(12, 50);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(711, 571);
this.pictureBoxCollection.TabIndex = 0;
@ -59,7 +66,7 @@
this.panelTools.Controls.Add(this.buttonUpdateColletion);
this.panelTools.Controls.Add(this.buttonDeleteZenit);
this.panelTools.Controls.Add(this.buttonAddZenit);
this.panelTools.Location = new System.Drawing.Point(729, 14);
this.panelTools.Location = new System.Drawing.Point(729, 50);
this.panelTools.Name = "panelTools";
this.panelTools.Size = new System.Drawing.Size(234, 568);
this.panelTools.TabIndex = 1;
@ -151,13 +158,57 @@
this.buttonAddZenit.UseVisualStyleBackColor = true;
this.buttonAddZenit.Click += new System.EventHandler(this.ButtonAddZenit_Click);
//
// menuStrip1
//
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(971, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "File";
//
// toolStripMenuItem
//
this.toolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.toolStripMenuItem.Name = "toolStripMenuItem";
this.toolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.LoadToolStripMenuItem.Text = "Загрузить";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormAntiAirCraftGunCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(971, 595);
this.ClientSize = new System.Drawing.Size(971, 633);
this.Controls.Add(this.panelTools);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormAntiAirCraftGunCollection";
this.Text = "FormAntiAirCraftGunCollection";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
@ -165,7 +216,10 @@
this.panelTools.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@ -182,5 +236,11 @@
private ListBox listBoxStorages;
private Button buttonAddCollection;
private Button buttonDelCollection;
private MenuStrip menuStrip1;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -165,5 +165,52 @@ namespace AntiAircraftGun
pictureBoxCollection.Image = obj.ShowZenits();
}
/// <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);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -57,4 +57,13 @@
<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>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>272, 17</value>
</metadata>
</root>

View File

@ -12,6 +12,10 @@ namespace AntiAircraftGun.Generics
where T : BaseDrawingAntiAirCraftGun
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCars => _collection.GetZenits();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
@ -126,7 +130,7 @@ namespace AntiAircraftGun.Generics
foreach (var zenit in _collection.GetZenits())
{
// TODO: Получение объекта
T? obj = zenit;
if (obj != null)

View File

@ -13,6 +13,18 @@ namespace AntiAircraftGun.Generics
/// </summary>
internal class AntiAirCraftGunGenericStorage
{
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
@ -91,5 +103,96 @@ namespace AntiAircraftGun.Generics
}
}
}
/// <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,
AntiAirCraftGunGenericCollection<BaseDrawingAntiAirCraftGun, DrawingObjectAntiAirCraftGun>> record in _zenitStorages)
{
StringBuilder records = new();
foreach (BaseDrawingAntiAirCraftGun? elem in record.Value.GetCars)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
string toWrite = $"CarStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
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("CarStorage"))
{
return false;
}
_zenitStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
AntiAirCraftGunGenericCollection<BaseDrawingAntiAirCraftGun, DrawingObjectAntiAirCraftGun> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
BaseDrawingAntiAirCraftGun? zenit =
elem?.CreateDrawningAntiAirCraftGun(_separatorForObject, _pictureWidth, _pictureHeight);
if (zenit != null)
{
if (!(collection + zenit))
{
return false;
}
}
}
_zenitStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
}
}