Lab7_DONE

This commit is contained in:
Itos 2024-10-03 00:45:35 +03:00
parent 7ed90109f5
commit f4861308df
15 changed files with 283 additions and 145 deletions

View File

@ -11,7 +11,6 @@ namespace ProjectGasolineTanker.Drawings
public class DrawingGasolineTanker : DrawingTruck public class DrawingGasolineTanker : DrawingTruck
{ {
public DrawingGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool wheel, int width, int height) : base(speed, weight, bodyColor, width, height, 130, 70) public DrawingGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool wheel, int width, int height) : base(speed, weight, bodyColor, width, height, 130, 70)
{ {
if (EntityTruck != null) if (EntityTruck != null)

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException (string message) : base(message) { }
public StorageOverflowException (string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectGasolineTanker.Exceptions
{
[Serializable]
internal class TruckNotFoundException : ApplicationException
{
public TruckNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public TruckNotFoundException() : base() { }
public TruckNotFoundException(string message) : base(message) { }
public TruckNotFoundException(string message, Exception exception) : base(message, exception) { }
protected TruckNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,4 +1,5 @@
using System; using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -10,7 +11,10 @@ using System.Windows.Forms;
using ProjectGasolineTanker.Generic; using ProjectGasolineTanker.Generic;
using ProjectGasolineTanker.Drawings; using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.MovementStratg; using ProjectGasolineTanker.MovementStratg;
using ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker; using ProjectGasolineTanker;
using System.Xml.Linq;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
@ -18,11 +22,14 @@ namespace ProjectGasolineTanker
{ {
// Набор объектов // Набор объектов
private readonly TruckGenericStorage _storage; private readonly TruckGenericStorage _storage;
// Логер
private readonly ILogger _logger;
public FormTruckCollection() public FormTruckCollection(ILogger<FormTruckCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
// заполнение лист бокс // заполнение лист бокс
@ -55,6 +62,7 @@ namespace ProjectGasolineTanker
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
// выбрать набор // выбрать набор
@ -70,10 +78,12 @@ namespace ProjectGasolineTanker
{ {
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удалён набор: {name}");
} }
} }
@ -82,8 +92,6 @@ namespace ProjectGasolineTanker
{ {
var formTruckConfig = new FormTruckConfig(); var formTruckConfig = new FormTruckConfig();
// TODO Call method AddEvent from formCarConfig
formTruckConfig.AddEvent(AddTruck); formTruckConfig.AddEvent(AddTruck);
formTruckConfig.Show(); formTruckConfig.Show();
} }
@ -100,17 +108,26 @@ namespace ProjectGasolineTanker
{ {
return; return;
} }
selectedTruck.ChangePictureSize(pictureBoxCollection.Width, pictureBoxCollection.Height); selectedTruck.ChangePictureSize(Width, Height);
try
{
if (obj + selectedTruck != -1) if (obj + selectedTruck != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTruck(); pictureBoxCollection.Image = obj.ShowTruck();
_logger.LogInformation($"Добавлен объект: {selectedTruck.EntityTruck.BodyColor}");
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
private void buttonDeleteTruck_Click(object sender, EventArgs e) private void buttonDeleteTruck_Click(object sender, EventArgs e)
@ -128,26 +145,31 @@ namespace ProjectGasolineTanker
{ {
return; return;
} }
int pos = 0;
try try
{ {
pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (obj - pos) if (obj - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTruck(); pictureBoxCollection.Image = obj.ShowTruck();
_logger.LogInformation($"Удалён объект по позиции : {pos}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (FormatException ex)
{
MessageBox.Show("Неверный формат ввода");
_logger.LogWarning("Неверный формат ввода");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
// обновить рисунок по набору // обновить рисунок по набору
private void buttonUpdate_Click(object sender, EventArgs e) private void buttonUpdate_Click(object sender, EventArgs e)
@ -169,13 +191,16 @@ namespace ProjectGasolineTanker
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}");
} }
else catch (InvalidOperationException ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
} }
} }
} }
@ -185,18 +210,19 @@ namespace ProjectGasolineTanker
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
ReloadObjects(); _storage.LoadData(openFileDialog.FileName);
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
pictureBoxCollection.Image = obj.ShowTruck();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл загружен по пути: {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
} }
} }
ReloadObjects();
} }
} }

View File

@ -32,14 +32,14 @@
this.labelAdvancedObject = new System.Windows.Forms.Label(); this.labelAdvancedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label(); this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox(); this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelLightBlue = new System.Windows.Forms.Panel(); this.panelIndigo = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel(); this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel(); this.panelPurple = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel(); this.panelGray = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel(); this.panelGreen = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel(); this.panelYellow = new System.Windows.Forms.Panel();
this.panelOrange = new System.Windows.Forms.Panel(); this.panelOrange = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel(); this.panelLawnGreen = new System.Windows.Forms.Panel();
this.checkBoxWheel = new System.Windows.Forms.CheckBox(); this.checkBoxWheel = new System.Windows.Forms.CheckBox();
this.checkBoxTanker = new System.Windows.Forms.CheckBox(); this.checkBoxTanker = new System.Windows.Forms.CheckBox();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown(); this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
@ -102,14 +102,14 @@
// //
// groupBoxColor // groupBoxColor
// //
this.groupBoxColor.Controls.Add(this.panelLightBlue); this.groupBoxColor.Controls.Add(this.panelIndigo);
this.groupBoxColor.Controls.Add(this.panelBlue); this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPurple); this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelGray); this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelGreen); this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Controls.Add(this.panelYellow); this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelOrange); this.groupBoxColor.Controls.Add(this.panelOrange);
this.groupBoxColor.Controls.Add(this.panelRed); this.groupBoxColor.Controls.Add(this.panelLawnGreen);
this.groupBoxColor.Location = new System.Drawing.Point(283, 32); this.groupBoxColor.Location = new System.Drawing.Point(283, 32);
this.groupBoxColor.Name = "groupBoxColor"; this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(277, 145); this.groupBoxColor.Size = new System.Drawing.Size(277, 145);
@ -117,25 +117,25 @@
this.groupBoxColor.TabStop = false; this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета"; this.groupBoxColor.Text = "Цвета";
// //
// panelLightBlue // panelIndigo
// //
this.panelLightBlue.BackColor = System.Drawing.Color.Indigo; this.panelIndigo.BackColor = System.Drawing.Color.Indigo;
this.panelLightBlue.Location = new System.Drawing.Point(5, 85); this.panelIndigo.Location = new System.Drawing.Point(5, 85);
this.panelLightBlue.Name = "panelLightBlue"; this.panelIndigo.Name = "panelIndigo";
this.panelLightBlue.Size = new System.Drawing.Size(50, 40); this.panelIndigo.Size = new System.Drawing.Size(50, 40);
this.panelLightBlue.TabIndex = 0; this.panelIndigo.TabIndex = 0;
// //
// panelBlue // panelBlack
// //
this.panelBlue.BackColor = System.Drawing.Color.Black; this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlue.Location = new System.Drawing.Point(75, 85); this.panelBlack.Location = new System.Drawing.Point(75, 85);
this.panelBlue.Name = "panelBlue"; this.panelBlack.Name = "panelBlack";
this.panelBlue.Size = new System.Drawing.Size(50, 40); this.panelBlack.Size = new System.Drawing.Size(50, 40);
this.panelBlue.TabIndex = 0; this.panelBlack.TabIndex = 0;
// //
// panelPurple // panelPurple
// //
this.panelPurple.BackColor = System.Drawing.Color.Fuchsia; this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(145, 85); this.panelPurple.Location = new System.Drawing.Point(145, 85);
this.panelPurple.Name = "panelPurple"; this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 40); this.panelPurple.Size = new System.Drawing.Size(50, 40);
@ -151,7 +151,7 @@
// //
// panelGreen // panelGreen
// //
this.panelGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(215, 25); this.panelGreen.Location = new System.Drawing.Point(215, 25);
this.panelGreen.Name = "panelGreen"; this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 40); this.panelGreen.Size = new System.Drawing.Size(50, 40);
@ -173,13 +173,13 @@
this.panelOrange.Size = new System.Drawing.Size(50, 40); this.panelOrange.Size = new System.Drawing.Size(50, 40);
this.panelOrange.TabIndex = 0; this.panelOrange.TabIndex = 0;
// //
// panelRed // panelLawnGreen
// //
this.panelRed.BackColor = System.Drawing.Color.LawnGreen; this.panelLawnGreen.BackColor = System.Drawing.Color.LawnGreen;
this.panelRed.Location = new System.Drawing.Point(5, 25); this.panelLawnGreen.Location = new System.Drawing.Point(5, 25);
this.panelRed.Name = "panelRed"; this.panelLawnGreen.Name = "panelLawnGreen";
this.panelRed.Size = new System.Drawing.Size(50, 40); this.panelLawnGreen.Size = new System.Drawing.Size(50, 40);
this.panelRed.TabIndex = 0; this.panelLawnGreen.TabIndex = 0;
// //
// checkBoxWheel // checkBoxWheel
// //
@ -362,14 +362,14 @@
private CheckBox checkBoxWheel; private CheckBox checkBoxWheel;
private CheckBox checkBoxTanker; private CheckBox checkBoxTanker;
private GroupBox groupBoxColor; private GroupBox groupBoxColor;
private Panel panelLightBlue; private Panel panelIndigo;
private Panel panelBlue; private Panel panelBlack;
private Panel panelPurple; private Panel panelPurple;
private Panel panelGray; private Panel panelGray;
private Panel panelGreen; private Panel panelGreen;
private Panel panelYellow; private Panel panelYellow;
private Panel panelOrange; private Panel panelOrange;
private Panel panelRed; private Panel panelLawnGreen;
private Label labelAdvancedObject; private Label labelAdvancedObject;
private Label labelSimpleObject; private Label labelSimpleObject;
private PictureBox pictureBoxObject; private PictureBox pictureBoxObject;

View File

@ -27,12 +27,12 @@ namespace ProjectGasolineTanker
public FormTruckConfig() public FormTruckConfig()
{ {
InitializeComponent(); InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown; panelLawnGreen.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown; panelOrange.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown; panelYellow.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown; panelGreen.MouseDown += PanelColor_MouseDown;
panelLightBlue.MouseDown += PanelColor_MouseDown; panelIndigo.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown; panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown; panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown; panelGray.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close(); buttonCancel.Click += (s, e) => Close();
@ -170,6 +170,8 @@ namespace ProjectGasolineTanker
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
if (_truck == null)
return;
EventAddTruck?.Invoke(_truck); EventAddTruck?.Invoke(_truck);
Close(); Close();
} }

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.Generic namespace ProjectGasolineTanker.Generic
{ {
@ -24,35 +25,32 @@ namespace ProjectGasolineTanker.Generic
// Добавление объекта в начало // Добавление объекта в начало
public int Insert(T truck) public int Insert(T truck)
{ {
_places.Insert(0, truck); return Insert(truck, 0);
return 0;
} }
// Добавление объекта в набор на конкретную позицию // Добавление объекта в набор на конкретную позицию
public bool Insert(T truck, int position) public int Insert(T truck, int position)
{ {
// TODO проверка позиции if (Count >= _maxCount)
if (position < 0 || position >= Count || Count >= _maxCount)
{ {
return false; throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
} }
// TODO вставка по позиции
_places.Insert(position, truck); _places.Insert(position, truck);
return true; return 0;
} }
// Удаление объекта из набора с конкретной позиции // Удаление объекта из набора с конкретной позиции
public bool Remove(int position) public bool Remove(int position)
{ {
// TODO проверка позиции
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return false; throw new TruckNotFoundException(position);
} }
// TODO удаление объекта из списка
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }

View File

@ -46,16 +46,14 @@ namespace ProjectGasolineTanker.Generic
return collect?._collection.Remove(pos) ?? false; return collect?._collection.Remove(pos) ?? false;
} }
// получение объектов коллекции
public IEnumerable<T?> GetTruck => _collection.GetTruck(); public IEnumerable<T?> GetTruck => _collection.GetTruck();
// получение объекта IMoveableObjecr
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection[pos]?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
// вывод всего набора
public Bitmap ShowTruck() public Bitmap ShowTruck()
{ {
Bitmap bmp = new(_pictureWidth, _pictureHeight); Bitmap bmp = new(_pictureWidth, _pictureHeight);
@ -65,7 +63,6 @@ namespace ProjectGasolineTanker.Generic
return bmp; return bmp;
} }
// прорисовка фона
private void DrawBackground(Graphics gr) private void DrawBackground(Graphics gr)
{ {
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
@ -80,6 +77,7 @@ namespace ProjectGasolineTanker.Generic
} }
} }
private void DrawObjects(Graphics g) private void DrawObjects(Graphics g)
{ {
// координаты // координаты
@ -90,15 +88,15 @@ namespace ProjectGasolineTanker.Generic
{ {
if (truck != null) if (truck != null)
{ {
// TODO получение объекта
if (x > _pictureWidth / _placeSizeWidth - 1) if (x > _pictureWidth / _placeSizeWidth - 1)
{ {
x = 0; x = 0;
--y; --y;
} }
// TODO установка позиции
truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y); truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
// TODO прорисовка объекта
truck.DrawTransport(g); truck.DrawTransport(g);
++x; ++x;
} }

View File

@ -33,11 +33,9 @@ namespace ProjectGasolineTanker.Generic
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
// Добавление набора
public void AddSet(string name) public void AddSet(string name)
{ {
// TODO Прописать логику для добавления
// проверка, что нет набора с таким именем
foreach (string nameStorage in Keys) foreach (string nameStorage in Keys)
{ {
if (nameStorage == name) if (nameStorage == name)
@ -74,79 +72,92 @@ namespace ProjectGasolineTanker.Generic
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new();
using (StreamWriter sw = File.CreateText(filename)) foreach (KeyValuePair<string,
{ TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> record in _TruckStorages)
sw.WriteLine($"TruckStorage");
foreach (var record in _TruckStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTruck) foreach (DrawingTruck? elem in record.Value.GetTruck)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}"); 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($"TruckStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
} }
return true;
}
// Загрузка информации по автомобилям в хранилище из файла
public bool LoadData(string filename)
public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
string bufferTextFromFile = "";
using (StreamReader sr = File.OpenText(filename)) using (FileStream fs = new(filename, FileMode.Open))
{ {
// 1-ая строка byte[] b = new byte[fs.Length];
string? curLine = sr.ReadLine(); UTF8Encoding temp = new(true);
// пустая или не те данные while (fs.Read(b, 0, b.Length) > 0)
if (curLine == null || !curLine.Contains("TruckStorage"))
{ {
return false; bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("TruckStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
} }
// очищаем
_TruckStorages.Clear(); _TruckStorages.Clear();
foreach (string data in strs)
// загружаем данные построчно
curLine = sr.ReadLine();
while (curLine != null)
{ {
// загружаем запись string[] record = data.Split(_separatorForKeyValue,
string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
// загружаем набор {
TruckGenericCollection<DrawingTruck, DrawingObjectTruck> collection = new(_pictureWidth, _pictureHeight); continue;
// record[0] - название набора, record[1] - куча объектов }
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); TruckGenericCollection<DrawingTruck, DrawingObjectTruck>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
DrawingTruck? Truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight); DrawingTruck? truck =
// проверяем, не переполнится ли коллекция elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (Truck != null) if (truck != null)
{ {
if (collection + Truck == -1) if ((collection + truck) == -1)
{ {
return false; throw new Exception("Ошибка добавления в коллекцию");
} }
} }
} }
_TruckStorages.Add(record[0], collection); _TruckStorages.Add(record[0], collection);
curLine = sr.ReadLine();
} }
} }
return true;
}
} }
} }

View File

@ -9,6 +9,7 @@ using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.MovementStratg namespace ProjectGasolineTanker.MovementStratg
{ {
public abstract class AbstractStrategy public abstract class AbstractStrategy
{ {

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
internal static class Program internal static class Program
@ -11,7 +17,32 @@ namespace ProjectGasolineTanker
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTruckCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
} }
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTruckCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}serilog.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
} }

View File

@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -0,0 +1,21 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/trucklog.log",
"rollingInterval": "Day",
"outputTemplate": null,
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ProjectGasolineTanker"
}
}
}