From f4861308df4e4c15b90d0cc1e25ce4e5cb38ccee Mon Sep 17 00:00:00 2001 From: Itos Date: Thu, 3 Oct 2024 00:45:35 +0300 Subject: [PATCH] Lab7_DONE --- .../Drawings/DrawingGasolineTanker.cs | 1 - .../Entities/EntityTruck.cs | 4 +- .../Exceptions/StorageOverflowException.cs | 19 +++ .../Exceptions/TruckNotFoundException.cs | 19 +++ .../FormTruckCollection.cs | 90 +++++++++----- .../FormTruckConfig.Designer.cs | 58 ++++----- .../ProjectGasolineTanker/FormTruckConfig.cs | 8 +- .../Generic/SetGeneric.cs | 26 ++-- .../Generic/TruckGenericCollection.cs | 12 +- .../Generic/TruckGenericStorage.cs | 113 ++++++++++-------- .../MovementStratg/AbstractStrategy.cs | 7 +- .../MovementStratg/IMoveableObject.cs | 2 +- .../ProjectGasolineTanker/Program.cs | 35 +++++- .../ProjectGasolineTanker.csproj | 13 ++ .../ProjectGasolineTanker/serilog.json | 21 ++++ 15 files changed, 283 insertions(+), 145 deletions(-) create mode 100644 GasolineTanker/ProjectGasolineTanker/Exceptions/StorageOverflowException.cs create mode 100644 GasolineTanker/ProjectGasolineTanker/Exceptions/TruckNotFoundException.cs create mode 100644 GasolineTanker/ProjectGasolineTanker/serilog.json diff --git a/GasolineTanker/ProjectGasolineTanker/Drawings/DrawingGasolineTanker.cs b/GasolineTanker/ProjectGasolineTanker/Drawings/DrawingGasolineTanker.cs index 25df613..b079ee8 100644 --- a/GasolineTanker/ProjectGasolineTanker/Drawings/DrawingGasolineTanker.cs +++ b/GasolineTanker/ProjectGasolineTanker/Drawings/DrawingGasolineTanker.cs @@ -11,7 +11,6 @@ namespace ProjectGasolineTanker.Drawings 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) { if (EntityTruck != null) diff --git a/GasolineTanker/ProjectGasolineTanker/Entities/EntityTruck.cs b/GasolineTanker/ProjectGasolineTanker/Entities/EntityTruck.cs index c6d24cd..6792740 100644 --- a/GasolineTanker/ProjectGasolineTanker/Entities/EntityTruck.cs +++ b/GasolineTanker/ProjectGasolineTanker/Entities/EntityTruck.cs @@ -9,9 +9,9 @@ namespace ProjectGasolineTanker.Entities public class EntityTruck { - + public int Speed { get; private set; } - + public double Weight { get; private set; } public Color BodyColor { get; private set; } diff --git a/GasolineTanker/ProjectGasolineTanker/Exceptions/StorageOverflowException.cs b/GasolineTanker/ProjectGasolineTanker/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..f236a86 --- /dev/null +++ b/GasolineTanker/ProjectGasolineTanker/Exceptions/StorageOverflowException.cs @@ -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) { } + } +} diff --git a/GasolineTanker/ProjectGasolineTanker/Exceptions/TruckNotFoundException.cs b/GasolineTanker/ProjectGasolineTanker/Exceptions/TruckNotFoundException.cs new file mode 100644 index 0000000..b74966d --- /dev/null +++ b/GasolineTanker/ProjectGasolineTanker/Exceptions/TruckNotFoundException.cs @@ -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) { } + } +} diff --git a/GasolineTanker/ProjectGasolineTanker/FormTruckCollection.cs b/GasolineTanker/ProjectGasolineTanker/FormTruckCollection.cs index cc51d22..85f7a36 100644 --- a/GasolineTanker/ProjectGasolineTanker/FormTruckCollection.cs +++ b/GasolineTanker/ProjectGasolineTanker/FormTruckCollection.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -10,7 +11,10 @@ using System.Windows.Forms; using ProjectGasolineTanker.Generic; using ProjectGasolineTanker.Drawings; using ProjectGasolineTanker.MovementStratg; + +using ProjectGasolineTanker.Exceptions; using ProjectGasolineTanker; +using System.Xml.Linq; namespace ProjectGasolineTanker { @@ -18,11 +22,14 @@ namespace ProjectGasolineTanker { // Набор объектов private readonly TruckGenericStorage _storage; + // Логер + private readonly ILogger _logger; - public FormTruckCollection() + public FormTruckCollection(ILogger logger) { InitializeComponent(); _storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } // заполнение лист бокс @@ -55,6 +62,7 @@ namespace ProjectGasolineTanker } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } // выбрать набор @@ -70,10 +78,12 @@ namespace ProjectGasolineTanker { return; } + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удалён набор: {name}"); } } @@ -81,9 +91,7 @@ namespace ProjectGasolineTanker private void buttonAddTruck_Click(object sender, EventArgs e) { - var formTruckConfig = new FormTruckConfig(); - - // TODO Call method AddEvent from formCarConfig + var formTruckConfig = new FormTruckConfig(); formTruckConfig.AddEvent(AddTruck); formTruckConfig.Show(); } @@ -100,15 +108,24 @@ namespace ProjectGasolineTanker { return; } - selectedTruck.ChangePictureSize(pictureBoxCollection.Width, pictureBoxCollection.Height); - if (obj + selectedTruck != -1) + selectedTruck.ChangePictureSize(Width, Height); + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowTruck(); + if (obj + selectedTruck != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowTruck(); + _logger.LogInformation($"Добавлен объект: {selectedTruck.EntityTruck.BodyColor}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } @@ -128,24 +145,29 @@ namespace ProjectGasolineTanker { return; } - int pos = 0; try { - pos = Convert.ToInt32(maskedTextBoxNumber.Text); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowTruck(); + _logger.LogInformation($"Удалён объект по позиции : {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - catch + catch (FormatException ex) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + MessageBox.Show("Неверный формат ввода"); + _logger.LogWarning("Неверный формат ввода"); } - if (obj - pos) + catch (Exception ex) { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowTruck(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } @@ -169,13 +191,16 @@ namespace ProjectGasolineTanker { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); 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 (_storage.LoadData(openFileDialog.FileName)) + try { - ReloadObjects(); - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - pictureBoxCollection.Image = obj.ShowTruck(); + _storage.LoadData(openFileDialog.FileName); 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(); } } diff --git a/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.Designer.cs b/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.Designer.cs index beec2ad..fc0dc16 100644 --- a/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.Designer.cs +++ b/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.Designer.cs @@ -32,14 +32,14 @@ this.labelAdvancedObject = new System.Windows.Forms.Label(); this.labelSimpleObject = new System.Windows.Forms.Label(); this.groupBoxColor = new System.Windows.Forms.GroupBox(); - this.panelLightBlue = new System.Windows.Forms.Panel(); - this.panelBlue = new System.Windows.Forms.Panel(); + this.panelIndigo = new System.Windows.Forms.Panel(); + this.panelBlack = new System.Windows.Forms.Panel(); this.panelPurple = new System.Windows.Forms.Panel(); this.panelGray = new System.Windows.Forms.Panel(); this.panelGreen = new System.Windows.Forms.Panel(); this.panelYellow = 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.checkBoxTanker = new System.Windows.Forms.CheckBox(); this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown(); @@ -102,14 +102,14 @@ // // groupBoxColor // - this.groupBoxColor.Controls.Add(this.panelLightBlue); - this.groupBoxColor.Controls.Add(this.panelBlue); + this.groupBoxColor.Controls.Add(this.panelIndigo); + this.groupBoxColor.Controls.Add(this.panelBlack); this.groupBoxColor.Controls.Add(this.panelPurple); this.groupBoxColor.Controls.Add(this.panelGray); this.groupBoxColor.Controls.Add(this.panelGreen); this.groupBoxColor.Controls.Add(this.panelYellow); 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.Name = "groupBoxColor"; this.groupBoxColor.Size = new System.Drawing.Size(277, 145); @@ -117,25 +117,25 @@ this.groupBoxColor.TabStop = false; this.groupBoxColor.Text = "Цвета"; // - // panelLightBlue + // panelIndigo // - this.panelLightBlue.BackColor = System.Drawing.Color.Indigo; - this.panelLightBlue.Location = new System.Drawing.Point(5, 85); - this.panelLightBlue.Name = "panelLightBlue"; - this.panelLightBlue.Size = new System.Drawing.Size(50, 40); - this.panelLightBlue.TabIndex = 0; + this.panelIndigo.BackColor = System.Drawing.Color.Indigo; + this.panelIndigo.Location = new System.Drawing.Point(5, 85); + this.panelIndigo.Name = "panelIndigo"; + this.panelIndigo.Size = new System.Drawing.Size(50, 40); + this.panelIndigo.TabIndex = 0; // - // panelBlue + // panelBlack // - this.panelBlue.BackColor = System.Drawing.Color.Black; - this.panelBlue.Location = new System.Drawing.Point(75, 85); - this.panelBlue.Name = "panelBlue"; - this.panelBlue.Size = new System.Drawing.Size(50, 40); - this.panelBlue.TabIndex = 0; + this.panelBlack.BackColor = System.Drawing.Color.Black; + this.panelBlack.Location = new System.Drawing.Point(75, 85); + this.panelBlack.Name = "panelBlack"; + this.panelBlack.Size = new System.Drawing.Size(50, 40); + this.panelBlack.TabIndex = 0; // // 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.Name = "panelPurple"; this.panelPurple.Size = new System.Drawing.Size(50, 40); @@ -151,7 +151,7 @@ // // 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.Name = "panelGreen"; this.panelGreen.Size = new System.Drawing.Size(50, 40); @@ -173,13 +173,13 @@ this.panelOrange.Size = new System.Drawing.Size(50, 40); this.panelOrange.TabIndex = 0; // - // panelRed + // panelLawnGreen // - this.panelRed.BackColor = System.Drawing.Color.LawnGreen; - this.panelRed.Location = new System.Drawing.Point(5, 25); - this.panelRed.Name = "panelRed"; - this.panelRed.Size = new System.Drawing.Size(50, 40); - this.panelRed.TabIndex = 0; + this.panelLawnGreen.BackColor = System.Drawing.Color.LawnGreen; + this.panelLawnGreen.Location = new System.Drawing.Point(5, 25); + this.panelLawnGreen.Name = "panelLawnGreen"; + this.panelLawnGreen.Size = new System.Drawing.Size(50, 40); + this.panelLawnGreen.TabIndex = 0; // // checkBoxWheel // @@ -362,14 +362,14 @@ private CheckBox checkBoxWheel; private CheckBox checkBoxTanker; private GroupBox groupBoxColor; - private Panel panelLightBlue; - private Panel panelBlue; + private Panel panelIndigo; + private Panel panelBlack; private Panel panelPurple; private Panel panelGray; private Panel panelGreen; private Panel panelYellow; private Panel panelOrange; - private Panel panelRed; + private Panel panelLawnGreen; private Label labelAdvancedObject; private Label labelSimpleObject; private PictureBox pictureBoxObject; diff --git a/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.cs b/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.cs index cc55e27..be8a005 100644 --- a/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.cs +++ b/GasolineTanker/ProjectGasolineTanker/FormTruckConfig.cs @@ -27,12 +27,12 @@ namespace ProjectGasolineTanker public FormTruckConfig() { InitializeComponent(); - panelRed.MouseDown += PanelColor_MouseDown; + panelLawnGreen.MouseDown += PanelColor_MouseDown; panelOrange.MouseDown += PanelColor_MouseDown; panelYellow.MouseDown += PanelColor_MouseDown; panelGreen.MouseDown += PanelColor_MouseDown; - panelLightBlue.MouseDown += PanelColor_MouseDown; - panelBlue.MouseDown += PanelColor_MouseDown; + panelIndigo.MouseDown += PanelColor_MouseDown; + panelBlack.MouseDown += PanelColor_MouseDown; panelPurple.MouseDown += PanelColor_MouseDown; panelGray.MouseDown += PanelColor_MouseDown; buttonCancel.Click += (s, e) => Close(); @@ -170,6 +170,8 @@ namespace ProjectGasolineTanker private void ButtonAdd_Click(object sender, EventArgs e) { + if (_truck == null) + return; EventAddTruck?.Invoke(_truck); Close(); } diff --git a/GasolineTanker/ProjectGasolineTanker/Generic/SetGeneric.cs b/GasolineTanker/ProjectGasolineTanker/Generic/SetGeneric.cs index 6aacf51..89df6f7 100644 --- a/GasolineTanker/ProjectGasolineTanker/Generic/SetGeneric.cs +++ b/GasolineTanker/ProjectGasolineTanker/Generic/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectGasolineTanker.Exceptions; namespace ProjectGasolineTanker.Generic { @@ -23,36 +24,33 @@ namespace ProjectGasolineTanker.Generic // Добавление объекта в начало public int Insert(T truck) - { - _places.Insert(0, truck); - return 0; + { + return Insert(truck, 0); } // Добавление объекта в набор на конкретную позицию - public bool Insert(T truck, int position) + public int Insert(T truck, int position) { - // TODO проверка позиции - if (position < 0 || position >= Count || Count >= _maxCount) + if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new IndexOutOfRangeException("Индекс вне границ коллекции"); } - - // TODO вставка по позиции _places.Insert(position, truck); - return true; + return 0; } // Удаление объекта из набора с конкретной позиции public bool Remove(int position) { - // TODO проверка позиции if (position < 0 || position >= Count) { - return false; + throw new TruckNotFoundException(position); } - // TODO удаление объекта из списка _places.RemoveAt(position); - return true; } diff --git a/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericCollection.cs b/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericCollection.cs index 8264a58..4be4734 100644 --- a/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericCollection.cs +++ b/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericCollection.cs @@ -46,16 +46,14 @@ namespace ProjectGasolineTanker.Generic return collect?._collection.Remove(pos) ?? false; } - // получение объектов коллекции public IEnumerable GetTruck => _collection.GetTruck(); - // получение объекта IMoveableObjecr + public U? GetU(int pos) { return (U?)_collection[pos]?.GetMoveableObject; } - // вывод всего набора public Bitmap ShowTruck() { Bitmap bmp = new(_pictureWidth, _pictureHeight); @@ -65,7 +63,6 @@ namespace ProjectGasolineTanker.Generic return bmp; } - // прорисовка фона private void DrawBackground(Graphics gr) { Pen pen = new(Color.Black, 3); @@ -80,6 +77,7 @@ namespace ProjectGasolineTanker.Generic } } + private void DrawObjects(Graphics g) { // координаты @@ -90,15 +88,15 @@ namespace ProjectGasolineTanker.Generic { if (truck != null) { - // TODO получение объекта + if (x > _pictureWidth / _placeSizeWidth - 1) { x = 0; --y; } - // TODO установка позиции + truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y); - // TODO прорисовка объекта + truck.DrawTransport(g); ++x; } diff --git a/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericStorage.cs b/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericStorage.cs index b3e360a..51d85d0 100644 --- a/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericStorage.cs +++ b/GasolineTanker/ProjectGasolineTanker/Generic/TruckGenericStorage.cs @@ -33,11 +33,9 @@ namespace ProjectGasolineTanker.Generic _pictureHeight = pictureHeight; } - // Добавление набора public void AddSet(string name) { - // TODO Прописать логику для добавления - // проверка, что нет набора с таким именем + foreach (string nameStorage in Keys) { if (nameStorage == name) @@ -74,79 +72,92 @@ namespace ProjectGasolineTanker.Generic } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } - - using (StreamWriter sw = File.CreateText(filename)) + StringBuilder data = new(); + foreach (KeyValuePair> record in _TruckStorages) { - sw.WriteLine($"TruckStorage"); - foreach (var record in _TruckStorages) + StringBuilder records = new(); + foreach (DrawingTruck? elem in record.Value.GetTruck) { - StringBuilder records = new(); - foreach (DrawingTruck? elem in record.Value.GetTruck) - { - records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); - } - sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}"); + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } - - return true; + 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; } - // Загрузка информации по автомобилям в хранилище из файла - public bool LoadData(string filename) + + + + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } - - using (StreamReader sr = File.OpenText(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - // 1-ая строка - string? curLine = sr.ReadLine(); - // пустая или не те данные - if (curLine == null || !curLine.Contains("TruckStorage")) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - return false; + bufferTextFromFile += temp.GetString(b); } - // очищаем - _TruckStorages.Clear(); - - // загружаем данные построчно - curLine = sr.ReadLine(); - while (curLine != null) + } + 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(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - // загружаем запись - string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - - // загружаем набор - TruckGenericCollection collection = new(_pictureWidth, _pictureHeight); - // record[0] - название набора, record[1] - куча объектов - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - - foreach (string elem in set) + continue; + } + TruckGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawingTruck? truck = + elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight); + if (truck != null) { - DrawingTruck? Truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight); - // проверяем, не переполнится ли коллекция - if (Truck != null) + if ((collection + truck) == -1) { - if (collection + Truck == -1) - { - return false; - } + throw new Exception("Ошибка добавления в коллекцию"); } } - _TruckStorages.Add(record[0], collection); - curLine = sr.ReadLine(); } + _TruckStorages.Add(record[0], collection); } - return true; } + } } diff --git a/GasolineTanker/ProjectGasolineTanker/MovementStratg/AbstractStrategy.cs b/GasolineTanker/ProjectGasolineTanker/MovementStratg/AbstractStrategy.cs index 0700a08..8ca941e 100644 --- a/GasolineTanker/ProjectGasolineTanker/MovementStratg/AbstractStrategy.cs +++ b/GasolineTanker/ProjectGasolineTanker/MovementStratg/AbstractStrategy.cs @@ -9,15 +9,16 @@ using ProjectGasolineTanker.Entities; namespace ProjectGasolineTanker.MovementStratg { + public abstract class AbstractStrategy { private IMoveableObject? _moveableObject; private Status _state = Status.NotInit; - + protected int FieldWidth { get; private set; } - + protected int FieldHeight { get; private set; } public Status GetStatus() { return _state; } @@ -54,7 +55,7 @@ namespace ProjectGasolineTanker.MovementStratg protected bool MoveRight() => MoveTo(DirectionType.Right); protected bool MoveUp() => MoveTo(DirectionType.Up); - + protected bool MoveDown() => MoveTo(DirectionType.Down); protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; diff --git a/GasolineTanker/ProjectGasolineTanker/MovementStratg/IMoveableObject.cs b/GasolineTanker/ProjectGasolineTanker/MovementStratg/IMoveableObject.cs index 220e961..e7dc0f1 100644 --- a/GasolineTanker/ProjectGasolineTanker/MovementStratg/IMoveableObject.cs +++ b/GasolineTanker/ProjectGasolineTanker/MovementStratg/IMoveableObject.cs @@ -14,7 +14,7 @@ namespace ProjectGasolineTanker.MovementStratg { ObjectParameters? GetObjectPosition { get; } - + int GetStep { get; } bool CheckCanMove(DirectionType direction); diff --git a/GasolineTanker/ProjectGasolineTanker/Program.cs b/GasolineTanker/ProjectGasolineTanker/Program.cs index 8a40783..5ba6d03 100644 --- a/GasolineTanker/ProjectGasolineTanker/Program.cs +++ b/GasolineTanker/ProjectGasolineTanker/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + + namespace ProjectGasolineTanker { internal static class Program @@ -7,11 +13,36 @@ namespace ProjectGasolineTanker /// [STAThread] static void Main() - { + { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTruckCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().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); + }); + } + + } } \ No newline at end of file diff --git a/GasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj b/GasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj index 13ee123..6e2246a 100644 --- a/GasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj +++ b/GasolineTanker/ProjectGasolineTanker/ProjectGasolineTanker.csproj @@ -8,6 +8,19 @@ enable + + + + + + + + + + + + + True diff --git a/GasolineTanker/ProjectGasolineTanker/serilog.json b/GasolineTanker/ProjectGasolineTanker/serilog.json new file mode 100644 index 0000000..e46b436 --- /dev/null +++ b/GasolineTanker/ProjectGasolineTanker/serilog.json @@ -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" + } + } +} \ No newline at end of file