зафиксировать

This commit is contained in:
Kristina 2023-12-10 21:24:28 +04:00
parent a17a520267
commit 95892d4f59
6 changed files with 307 additions and 108 deletions

View File

@ -9,7 +9,7 @@ namespace ProjectBoat_bae
{
internal class BoatDelegate
{
// Делегат для передачи объекта-автомобиля
// Делегат для передачи объекта
public delegate void boatDelegate(Drawningboat boat);
}
}

View File

@ -10,7 +10,7 @@ using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae
{
internal static class ExtentionCar
internal static class ExtentionBoat
{
// Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':';

View File

@ -1,4 +1,6 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -7,12 +9,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Generics;
using ProjectBoat_bae.Exceptions;
using ProjectBoat_bae.MovementStrategy;
using NLog;
namespace ProjectBoat_bae
{
@ -22,9 +24,9 @@ namespace ProjectBoat_bae
private readonly BoatsGenericStorage _storage;
// Логер
private readonly ILogger _logger;
private readonly Microsoft.Extensions.Logging.ILogger? _logger;
public FormBoatCollection()
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
@ -72,7 +74,7 @@ namespace ProjectBoat_bae
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
}
// Удаление набора
@ -95,71 +97,143 @@ namespace ProjectBoat_bae
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
_logger.LogInformation($"Deleted set: {name}");
}
}
// Добавление объекта в набор
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1) return;
//if (listBoxStorages.SelectedIndex == -1) return;
//var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
//if (obj == null) return;
//FormBoatConfig form = new FormBoatConfig();
//form.AddEvent(AddBoat);
//form.Show();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
FormBoatConfig form = new FormBoatConfig();
form.AddEvent(AddBoat);
form.Show();
if (obj == null)
{
return;
}
FormBoatConfig formPlaneConfig = new FormBoatConfig();
formPlaneConfig.AddEvent(AddBoat);
formPlaneConfig.Show();
}
private void AddBoat(Drawningboat boat)
{
boat._pictureWidth = pictureBoxCollection.Width;
boat._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
//boat._pictureWidth = pictureBoxCollection.Width;
//boat._pictureHeight = pictureBoxCollection.Height;
//if (listBoxStorages.SelectedIndex == -1) return;
//var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
//if (obj == null) return;
if (obj + boat)
//if (obj + boat)
//{
// MessageBox.Show("Объект добавлен");
// pictureBoxCollection.Image = obj.ShowBoats();
//}
//else
//{
// MessageBox.Show("Не удалось добавить объект");
//}
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + boat;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"boat added {listBoxStorages.SelectedItem.ToString()}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"boat not added {listBoxStorages.SelectedItem.ToString()}");
}
}
//удаление объекта
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
//if (listBoxStorages.SelectedIndex == -1)
//{
// return;
//}
//var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
//string.Empty];
//if (obj == null)
//{
// return;
//}
//if (MessageBox.Show("Удалить объект?", "Удаление",
//MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
//{
// return;
//}
//int pos = 0;
//if (textBoxBoat != null)
// pos = Convert.ToInt32(textBoxBoat.Text);
//if (obj - pos != null)
//{
// MessageBox.Show("Объект удален");
// pictureBoxCollection.Image = obj.ShowBoats();
//}
//else
//{
// MessageBox.Show("Не удалось удалить объект");
//}
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = 0;
if (textBoxBoat != null)
pos = Convert.ToInt32(textBoxBoat.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBoats();
int pos = Convert.ToInt32(textBoxBoat.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Объект не удален");
_logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (BoatNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Объект не добавлен");
_logger.LogWarning("Not input");
}
}
@ -189,18 +263,47 @@ namespace ProjectBoat_bae
//сохранение
private void SaveToolStripMenu_Click(object sender, EventArgs e)
{
//if (saveFileDialog.ShowDialog() == DialogResult.OK)
//{
// try
// {
// _storage.SaveData(saveFileDialog.FileName);
// MessageBox.Show("Сохранение прошло успешно",
// "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// catch (Exception ex)
// {
// MessageBox.Show($"Не сохранилось: {ex.Message}",
// "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
//}
//if (saveFileDialog.ShowDialog() == DialogResult.OK)
//{
// try
// {
// _storage.SaveData(saveFileDialog.FileName);
// MessageBox.Show("Сохранение завершено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// _logger.LogInformation($"save in file {saveFileDialog.FileName}");
// }
// catch (Exception ex)
// {
// MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
// _logger.LogWarning($"Save to file {saveFileDialog.FileName} not complete");
// }
//}
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -208,52 +311,56 @@ namespace ProjectBoat_bae
//загрузка
private void LoadToolStripMenu_Click(object sender, EventArgs args)
{
//if (openFileDialog.ShowDialog() == DialogResult.OK)
//{
// if (_storage.LoadData(openFileDialog.FileName))
// {
// MessageBox.Show("Load Complete", "Result",
// MessageBoxButtons.OK, MessageBoxIcon.Information);
// ReloadObjects();
// MessageBox.Show("Загрузка прошла успешно",
// "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// else
// {
// MessageBox.Show("Load Not Complete", "Result",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// MessageBox.Show("Не загрузилось", "Результат",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
//}
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
//ReloadObjects();
//if (openFileDialog.ShowDialog() == DialogResult.OK)
//{
// try
// {
// _storage.LoadData(openFileDialog.FileName);
// MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// _logger.LogInformation("Загрузка прошла успешно");
// MessageBox.Show("Загрузка завершена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// ReloadObjects();
// _logger.LogInformation($"load from file {openFileDialog.FileName}");
// }
// catch (Exception ex)
// {
// MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
// _logger.LogWarning($"Не загрузилось: {ex.Message}");
// MessageBox.Show($"Не загружено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
// _logger.LogWarning($"load from file {openFileDialog.FileName} not complete");
// }
//}
//ReloadObjects();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -10,6 +10,10 @@ using System.Windows.Forms;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ProjectBoat_bae
{
public partial class FormBoatConfig : Form
@ -83,18 +87,28 @@ namespace ProjectBoat_bae
// Действия при приеме перетаскиваемой информации
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
//switch (e.Data?.GetData(DataFormats.Text).ToString())
//{
// case "labelSimpleObject":
// _boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
// break;
// case "labelModifiedObject":
// _boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black,
// checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
// break;
//}
//LabelColor.BackColor = Color.Empty;
//LabelAdditionalColor.BackColor = Color.Empty;
ILogger<FormBoatCollection> logger = new NullLogger<FormBoatCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelModifiedObject":
_boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
_boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
LabelColor.BackColor = Color.Empty;
LabelAdditionalColor.BackColor = Color.Empty;
DrawBoat();
}

View File

@ -102,7 +102,8 @@ namespace ProjectBoat_bae.Generics
T? t = _collection[i];
if (t != null)
{
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth,
(i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t is Drawningboat) (t as Drawningboat).DrawTransport(g);
else t.DrawTransport(g);
}

View File

@ -52,6 +52,30 @@ namespace ProjectBoat_bae.Generics
public void SaveData(string filename)
{
//if (File.Exists(filename))
//{
// File.Delete(filename);
//}
//StringBuilder data = new();
//foreach (KeyValuePair<string,
//BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
//{
// StringBuilder records = new();
// foreach (Drawningboat? elem in record.Value.GetBoats)
// {
// records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
// }
// data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
//}
//if (data.Length == 0)
//{
// throw new Exception("Невалиданя операция, нет данных для сохранения");
//}
//using FileStream fs = new(filename, FileMode.Create);
//byte[] info = new
//UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
//fs.Write(info, 0, info.Length);
//return;
if (File.Exists(filename))
{
File.Delete(filename);
@ -69,65 +93,118 @@ namespace ProjectBoat_bae.Generics
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public bool LoadData(string filename)
//public bool LoadData(string filename)
public void LoadData(string filename)
{
//if (!File.Exists(filename))
//{
// return false;
//}
//using (StreamReader fs = File.OpenText(filename))
//{
// string str = fs.ReadLine();
// if (str == null || str.Length == 0)
// {
// return false;
// }
// if (!str.StartsWith("ShipStorage"))
// {
// return false;
// }
// _boatStorages.Clear();
// string strs = "";
// while ((strs = fs.ReadLine()) != null)
// {
// if (strs == null)
// {
// return false;
// }
// string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
// if (record.Length != 2)
// {
// continue;
// }
// BoatsGenericCollection<Drawningboat, DrawningObjectBoat> collection = new(_pictureWidth, _pictureHeight);
// string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
// foreach (string elem in set)
// {
// Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight);
// if (boat != null)
// {
// if (!(collection + boat))
// {
// return false;
// }
// }
// }
// _boatStorages.Add(record[0], collection);
// }
// return true;
//}
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
return false;
bufferTextFromFile += temp.GetString(b);
}
if (!str.StartsWith("ShipStorage"))
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("BusStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_boatStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
return false;
continue;
}
_boatStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
BoatsGenericCollection<Drawningboat, DrawningObjectBoat>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (strs == null)
Drawningboat? boat =
elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<Drawningboat, DrawningObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
if (!(collection + boat))
{
if (!(collection + boat))
{
return false;
}
throw new Exception("Ошибка добавления в коллекцию");
}
}
_boatStorages.Add(record[0], collection);
}
return true;
_boatStorages.Add(record[0], collection);
}
}
}