diff --git a/Excavator/Drawing/DrawingExcavator.cs b/Excavator/Drawing/DrawingExcavator.cs index 9c7b390..977f813 100644 --- a/Excavator/Drawing/DrawingExcavator.cs +++ b/Excavator/Drawing/DrawingExcavator.cs @@ -10,11 +10,11 @@ namespace Excavator.Drawing { public class DrawingExcavator : DrawingMash { - public DrawingExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool bucket, bool supports, int width, int height) : base(speed, weight, bodyColor, width, height, 180, 110) + public DrawingExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool buket, bool supports, int width, int height) : base(speed, weight, bodyColor, width, height, 180, 110) { if (EntityMash != null) { - EntityMash = new EntityExcavator(speed, weight, bodyColor, additionalColor, bucket, supports); + EntityMash = new EntityExcavator(speed, weight, bodyColor, additionalColor, buket, supports); } } @@ -25,7 +25,7 @@ namespace Excavator.Drawing return; } Pen pen = new(Color.Black); - Pen additionalPen = new(Excavator.Body); + Pen additionalPen = new(Excavator.AddColor); Brush additionalBrush = new SolidBrush(Excavator.AddColor); base.DrawTransport(g); diff --git a/Excavator/Drawing/DrawingMash.cs b/Excavator/Drawing/DrawingMash.cs index 9b45e84..b93dbab 100644 --- a/Excavator/Drawing/DrawingMash.cs +++ b/Excavator/Drawing/DrawingMash.cs @@ -25,6 +25,7 @@ namespace Excavator.Drawing public int GetHeight => _mashHeight; public DrawingMash(int speed, double weight, Color bodyColor, int width, int height) { + if (width < _mashWidth || height < _mashHeight) { return; @@ -33,16 +34,17 @@ namespace Excavator.Drawing _pictureHeight = height; EntityMash = new EntityMash(speed, weight, bodyColor); } - protected DrawingMash(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight) + protected DrawingMash(int speed, double weight, Color bodyColor, int width, int height, int mashWidth, int mashHeight) { + if (width < _mashWidth || height < _mashHeight) { return; } _pictureWidth = width; _pictureHeight = height; - _mashWidth = busWidth; - _mashHeight = busHeight; + _mashWidth = mashWidth; + _mashHeight = mashHeight; EntityMash = new EntityMash(speed, weight, bodyColor); } public void SetPosition(int x, int y) @@ -121,6 +123,7 @@ namespace Excavator.Drawing g.DrawLine(blackPen, _startPosX + 27, _startPosY + 69, _startPosX + 165, _startPosY + 69); g.DrawLine(blackPen, _startPosX + 27, _startPosY + 99, _startPosX + 165, _startPosY + 99); } + public bool CanMove(DirectionType direction) { if (EntityMash == null) diff --git a/Excavator/Drawing/ExtentionDrawingMash.cs b/Excavator/Drawing/ExtentionDrawingMash.cs index 1e33ae3..b2758d2 100644 --- a/Excavator/Drawing/ExtentionDrawingMash.cs +++ b/Excavator/Drawing/ExtentionDrawingMash.cs @@ -29,7 +29,6 @@ namespace Excavator.Drawing } return null; } - public static string GetDataForSave(this DrawingMash DrawingMash, char separatorForObject) { var truck = DrawingMash.EntityMash; diff --git a/Excavator/Entities/EntityExcavator.cs b/Excavator/Entities/EntityExcavator.cs index 7a3f177..bbe80e9 100644 --- a/Excavator/Entities/EntityExcavator.cs +++ b/Excavator/Entities/EntityExcavator.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net.Sockets; using System.Text; using System.Threading.Tasks; @@ -10,17 +9,17 @@ namespace Excavator.Entities { public class EntityExcavator : EntityMash { - public Color Body { get; private set; } public Color AddColor { get; private set; } public bool IsBucket { get; private set; } public bool IsSupports { get; private set; } - public EntityExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool bucket, bool supports) : base(speed, weight, bodyColor) + public EntityExcavator(int speed, double weight, Color bodyColor, Color additionalColor, bool buket, bool supports) : base(speed, weight, bodyColor) { AddColor = additionalColor; - IsBucket = bucket; + IsBucket = buket; IsSupports = supports; } + public void ChangeAdditionalColor(Color additionalColor) { AddColor = additionalColor; diff --git a/Excavator/Excavator.csproj b/Excavator/Excavator.csproj index 13ee123..3b9e809 100644 --- a/Excavator/Excavator.csproj +++ b/Excavator/Excavator.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,6 @@ + + \ No newline at end of file diff --git a/Excavator/Exceptions/MashNotFoundException.cs b/Excavator/Exceptions/MashNotFoundException.cs new file mode 100644 index 0000000..5439ffd --- /dev/null +++ b/Excavator/Exceptions/MashNotFoundException.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 Excavator.Exceptions +{ + [Serializable] + internal class MashNotFoundException : ApplicationException + { + public MashNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public MashNotFoundException() : base() { } + public MashNotFoundException(string message) : base(message) { } + public MashNotFoundException(string message, Exception exception) : base(message, exception) { } + protected MashNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Excavator/Exceptions/StorageOverflowException.cs b/Excavator/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..7ef6bb4 --- /dev/null +++ b/Excavator/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 Excavator.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/Excavator/FormExcavatorCollection.Designer.cs b/Excavator/FormExcavatorCollection.Designer.cs index e60d297..e04bfaa 100644 --- a/Excavator/FormExcavatorCollection.Designer.cs +++ b/Excavator/FormExcavatorCollection.Designer.cs @@ -28,11 +28,11 @@ /// private void InitializeComponent() { - this.buttonAddMash = new System.Windows.Forms.Button(); + this.buttonAddBus = new System.Windows.Forms.Button(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.labelInstruments = new System.Windows.Forms.Label(); this.buttonUpdate = new System.Windows.Forms.Button(); - this.buttonDeleteMash = new System.Windows.Forms.Button(); + this.buttonDeleteBus = new System.Windows.Forms.Button(); this.colorDialog = new System.Windows.Forms.ColorDialog(); this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox(); this.label1 = new System.Windows.Forms.Label(); @@ -50,17 +50,17 @@ this.menuStrip.SuspendLayout(); this.SuspendLayout(); // - // buttonAddMash + // buttonAddBus // - this.buttonAddMash.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.buttonAddMash.Location = new System.Drawing.Point(982, 441); - this.buttonAddMash.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); - this.buttonAddMash.Name = "buttonAddMash"; - this.buttonAddMash.Size = new System.Drawing.Size(135, 37); - this.buttonAddMash.TabIndex = 0; - this.buttonAddMash.Text = "Добавить автобус"; - this.buttonAddMash.UseVisualStyleBackColor = true; - this.buttonAddMash.Click += new System.EventHandler(this.buttonAddMash_Click); + this.buttonAddBus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonAddBus.Location = new System.Drawing.Point(982, 441); + this.buttonAddBus.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.buttonAddBus.Name = "buttonAddBus"; + this.buttonAddBus.Size = new System.Drawing.Size(135, 37); + this.buttonAddBus.TabIndex = 0; + this.buttonAddBus.Text = "Добавить автобус"; + this.buttonAddBus.UseVisualStyleBackColor = true; + this.buttonAddBus.Click += new System.EventHandler(this.buttonAddMash_Click); // // pictureBoxCollection // @@ -94,17 +94,17 @@ this.buttonUpdate.UseVisualStyleBackColor = true; this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click); // - // buttonDeleteMash + // buttonDeleteBus // - this.buttonDeleteMash.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.buttonDeleteMash.Location = new System.Drawing.Point(982, 525); - this.buttonDeleteMash.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); - this.buttonDeleteMash.Name = "buttonDeleteMash"; - this.buttonDeleteMash.Size = new System.Drawing.Size(135, 37); - this.buttonDeleteMash.TabIndex = 4; - this.buttonDeleteMash.Text = "Удалить"; - this.buttonDeleteMash.UseVisualStyleBackColor = true; - this.buttonDeleteMash.Click += new System.EventHandler(this.buttonDeleteMash_Click); + this.buttonDeleteBus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonDeleteBus.Location = new System.Drawing.Point(982, 525); + this.buttonDeleteBus.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.buttonDeleteBus.Name = "buttonDeleteBus"; + this.buttonDeleteBus.Size = new System.Drawing.Size(135, 37); + this.buttonDeleteBus.TabIndex = 4; + this.buttonDeleteBus.Text = "Удалить"; + this.buttonDeleteBus.UseVisualStyleBackColor = true; + this.buttonDeleteBus.Click += new System.EventHandler(this.buttonDeleteMash_Click); // // maskedTextBoxNumber // @@ -218,9 +218,9 @@ this.Controls.Add(this.buttonAddStorage); this.Controls.Add(this.listBoxStorages); this.Controls.Add(this.label1); - this.Controls.Add(this.buttonAddMash); + this.Controls.Add(this.buttonAddBus); this.Controls.Add(this.maskedTextBoxNumber); - this.Controls.Add(this.buttonDeleteMash); + this.Controls.Add(this.buttonDeleteBus); this.Controls.Add(this.buttonUpdate); this.Controls.Add(this.labelInstruments); this.Controls.Add(this.pictureBoxCollection); @@ -239,11 +239,11 @@ #endregion - private Button buttonAddMash; + private Button buttonAddBus; private PictureBox pictureBoxCollection; private Label labelInstruments; private Button buttonUpdate; - private Button buttonDeleteMash; + private Button buttonDeleteBus; private ColorDialog colorDialog; private MaskedTextBox maskedTextBoxNumber; private Label label1; diff --git a/Excavator/FormExcavatorCollection.cs b/Excavator/FormExcavatorCollection.cs index 94380b1..50116f7 100644 --- a/Excavator/FormExcavatorCollection.cs +++ b/Excavator/FormExcavatorCollection.cs @@ -10,18 +10,22 @@ using System.Windows.Forms; using Excavator.Generic; using Excavator.Drawing; using Excavator.Move_Strategy; +using Microsoft.Extensions.Logging; +using Excavator.Exceptions; + namespace Excavator { public partial class FormExcavatorCollection : Form { - private readonly MashGenericStorage _storage; - - public FormExcavatorCollection() + private readonly MashsGenericStorage _storage; + private readonly ILogger _logger; + public FormExcavatorCollection(ILogger logger) { InitializeComponent(); - _storage = new MashGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _storage = new MashsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -50,6 +54,7 @@ namespace Excavator } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { @@ -61,13 +66,14 @@ namespace Excavator { 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}"); } } - private void buttonAddMash_Click(object sender, EventArgs e) { @@ -88,18 +94,26 @@ namespace Excavator { return; } - SelectedMash.ChangeBordersPicture(pictureBoxCollection.Width, pictureBoxCollection.Height); - if (obj + SelectedMash != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowMash(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } + SelectedMash.ChangeBordersPicture(Width, Height); + try + { + if (obj + SelectedMash != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowMash(); + _logger.LogInformation($"Добавлен объект: {SelectedMash.EntityMash.BodyColor}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); + } } - private void buttonDeleteMash_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) @@ -115,24 +129,29 @@ namespace Excavator { return; } - int pos = 0; try { - pos = Convert.ToInt32(maskedTextBoxNumber.Text); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowMash(); + _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.ShowMash(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } private void buttonUpdate_Click(object sender, EventArgs e) @@ -149,17 +168,21 @@ namespace Excavator } pictureBoxCollection.Image = obj.ShowMash(); } + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { 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); } } } @@ -167,18 +190,19 @@ namespace Excavator { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - ReloadObjects(); - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - pictureBoxCollection.Image = obj.ShowMash(); + _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/Excavator/FormMashConfig.Designer.cs b/Excavator/FormMashConfig.Designer.cs index 6e39766..c09c3eb 100644 --- a/Excavator/FormMashConfig.Designer.cs +++ b/Excavator/FormMashConfig.Designer.cs @@ -40,7 +40,7 @@ this.panelYellow = new System.Windows.Forms.Panel(); this.panelRoyalBlue = new System.Windows.Forms.Panel(); this.panelFirebrick = new System.Windows.Forms.Panel(); - this.checkBoxLadder = new System.Windows.Forms.CheckBox(); + this.checkBoxSupports = new System.Windows.Forms.CheckBox(); this.checkBoxBucket = new System.Windows.Forms.CheckBox(); this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown(); this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown(); @@ -65,7 +65,7 @@ this.groupBoxConfig.Controls.Add(this.labelAdvancedObject); this.groupBoxConfig.Controls.Add(this.labelSimpleObject); this.groupBoxConfig.Controls.Add(this.groupBoxColor); - this.groupBoxConfig.Controls.Add(this.checkBoxLadder); + this.groupBoxConfig.Controls.Add(this.checkBoxSupports); this.groupBoxConfig.Controls.Add(this.checkBoxBucket); this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed); this.groupBoxConfig.Controls.Add(this.numericUpDownWeight); @@ -181,15 +181,15 @@ this.panelFirebrick.Size = new System.Drawing.Size(50, 40); this.panelFirebrick.TabIndex = 0; // - // checkBoxLadder + // checkBoxSupports // - this.checkBoxLadder.AutoSize = true; - this.checkBoxLadder.Location = new System.Drawing.Point(13, 149); - this.checkBoxLadder.Name = "checkBoxLadder"; - this.checkBoxLadder.Size = new System.Drawing.Size(132, 24); - this.checkBoxLadder.TabIndex = 5; - this.checkBoxLadder.Text = "Наличие опор"; - this.checkBoxLadder.UseVisualStyleBackColor = true; + this.checkBoxSupports.AutoSize = true; + this.checkBoxSupports.Location = new System.Drawing.Point(13, 149); + this.checkBoxSupports.Name = "checkBoxSupports"; + this.checkBoxSupports.Size = new System.Drawing.Size(132, 24); + this.checkBoxSupports.TabIndex = 5; + this.checkBoxSupports.Text = "Наличие опор"; + this.checkBoxSupports.UseVisualStyleBackColor = true; // // checkBoxBucket // @@ -359,7 +359,7 @@ private NumericUpDown numericUpDownWeight; private Label labelWeight; private Label labelSpeed; - private CheckBox checkBoxLadder; + private CheckBox checkBoxSupports; private CheckBox checkBoxBucket; private GroupBox groupBoxColor; private Panel panelBlue; diff --git a/Excavator/FormMashConfig.cs b/Excavator/FormMashConfig.cs index ea4987f..4ad8cdd 100644 --- a/Excavator/FormMashConfig.cs +++ b/Excavator/FormMashConfig.cs @@ -14,7 +14,6 @@ namespace Excavator { public partial class FormMashConfig : Form { - DrawingMash? _mash = null; private event Action? EventAddMash; public FormMashConfig() @@ -49,7 +48,6 @@ namespace Excavator EventAddMash += ev; } } - private void LabelObject_MouseDown(object sender, MouseEventArgs e) { (sender as Label)?.DoDragDrop((sender as Label)?.Name, @@ -84,13 +82,12 @@ namespace Excavator (int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, - checkBoxBucket.Checked, checkBoxLadder.Checked, + checkBoxBucket.Checked, checkBoxSupports.Checked, pictureBoxObject.Width, pictureBoxObject.Height); break; } DrawMash(); } - private void PanelColor_MouseDown(object sender, MouseEventArgs e) { (sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, @@ -131,13 +128,15 @@ namespace Excavator { var color = (Color)e.Data.GetData(typeof(Color)); - EntityExcavator? _Excavator = _mash.EntityMash as EntityExcavator; - _Excavator.ChangeAdditionalColor(color); + EntityExcavator? _excavator = _mash.EntityMash as EntityExcavator; + _excavator.ChangeAdditionalColor(color); DrawMash(); } - private void ButtonAdd_Click(object sender, EventArgs e) { + if (_mash == null) + return; + EventAddMash?.Invoke(_mash); Close(); } diff --git a/Excavator/Generic/MashGenericCollection.cs b/Excavator/Generic/MashGenericCollection.cs index 78226a3..ebad22a 100644 --- a/Excavator/Generic/MashGenericCollection.cs +++ b/Excavator/Generic/MashGenericCollection.cs @@ -45,11 +45,11 @@ namespace Excavator.Generic } public IEnumerable GetMash => _collection.GetMash(); + public U? GetU(int pos) { return (U?)_collection[pos]?.GetMoveableObject; } - public Bitmap ShowMash() { Bitmap bmp = new(_pictureWidth, _pictureHeight); @@ -58,7 +58,6 @@ namespace Excavator.Generic DrawObjects(gr); return bmp; } - private void DrawBackground(Graphics gr) { Pen pen = new(Color.Black, 3); diff --git a/Excavator/Generic/MashsGenericStorage.cs b/Excavator/Generic/MashsGenericStorage.cs index c0469bd..e2febdf 100644 --- a/Excavator/Generic/MashsGenericStorage.cs +++ b/Excavator/Generic/MashsGenericStorage.cs @@ -8,7 +8,7 @@ using Excavator.Move_Strategy; namespace Excavator.Generic { - internal class MashGenericStorage + internal class MashsGenericStorage { readonly Dictionary> _mashStorages; public List Keys => _mashStorages.Keys.ToList(); @@ -18,26 +18,23 @@ namespace Excavator.Generic private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; - public MashGenericStorage(int pictureWidth, int pictureHeight) + public MashsGenericStorage(int pictureWidth, int pictureHeight) { _mashStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } - public void AddSet(string name) { foreach (string nameStorage in Keys) { if (nameStorage == name) { - MessageBox.Show("Набор с заданным именем уже есть", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } _mashStorages.Add(name, new MashGenericCollection(_pictureWidth, _pictureHeight)); } - public void DelSet(string name) { if (_mashStorages.ContainsKey(name)) @@ -57,69 +54,86 @@ namespace Excavator.Generic return null; } } - - 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 _mashStorages) { - sw.WriteLine($"ExcavatorStorage"); - foreach (var record in _mashStorages) + StringBuilder records = new(); + foreach (DrawingMash? elem in record.Value.GetMash) { - StringBuilder records = new(); - foreach (DrawingMash? elem in record.Value.GetMash) - { - 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($"BusStorage{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)) { - string? curLine = sr.ReadLine(); - if (curLine == null || !curLine.Contains("ExcavatorStorage")) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - return false; + bufferTextFromFile += temp.GetString(b); } - _mashStorages.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("BusStorage")) + { + throw new Exception("Неверный формат данных"); + } + _mashStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) { - string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - MashGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - - foreach (string elem in set) + continue; + } + MashGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawingMash? Mash = + elem?.CreateDrawingMash(_separatorForObject, _pictureWidth, _pictureHeight); + if (Mash != null) { - DrawingMash? Mash = elem?.CreateDrawingMash(_separatorForObject, _pictureWidth, _pictureHeight); - if (Mash != null) + if ((collection + Mash) == -1) { - if (collection + Mash == -1) - { - return false; - } + throw new Exception("Ошибка добавления в коллекцию"); } } - _mashStorages.Add(record[0], collection); - curLine = sr.ReadLine(); } + _mashStorages.Add(record[0], collection); } - return true; } } } diff --git a/Excavator/Generic/SetGeneric.cs b/Excavator/Generic/SetGeneric.cs index 155a866..ad2ff8d 100644 --- a/Excavator/Generic/SetGeneric.cs +++ b/Excavator/Generic/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using Excavator.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -17,30 +18,30 @@ namespace Excavator.Generic _maxCount = count; _places = new List(count); } - public int Insert(T bus) { - _places.Insert(0, bus); - return 0; + return Insert(bus, 0); } - - public bool Insert(T mash, int position) + public int Insert(T mash, int position) { - if (position < 0 || position >= Count || Count >= _maxCount) + if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new IndexOutOfRangeException("Индекс вне границ коллекции"); } _places.Insert(position, mash); - return true; + return 0; } public bool Remove(int position) { if (position < 0 || position >= Count) { - return false; + throw new MashNotFoundException(position); } _places.RemoveAt(position); - return true; } public T? this[int position] diff --git a/Excavator/Move_Strategy/AbstractStrategy.cs b/Excavator/Move_Strategy/AbstractStrategy.cs index 29aca81..5d4596d 100644 --- a/Excavator/Move_Strategy/AbstractStrategy.cs +++ b/Excavator/Move_Strategy/AbstractStrategy.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Excavator.Entities; using static System.Windows.Forms.VisualStyles.VisualStyleElement; - namespace Excavator.Move_Strategy { public abstract class AbstractStrategy diff --git a/Excavator/Move_Strategy/DrawingObjectMash.cs b/Excavator/Move_Strategy/DrawingObjectMash.cs index 377f42b..7c34bcf 100644 --- a/Excavator/Move_Strategy/DrawingObjectMash.cs +++ b/Excavator/Move_Strategy/DrawingObjectMash.cs @@ -13,24 +13,24 @@ namespace Excavator.Move_Strategy { public class DrawingObjectMash : IMoveableObject { - private readonly DrawingMash? _DrawingMash = null; + private readonly DrawingMash? _drawingMash = null; public DrawingObjectMash(DrawingMash DrawingMash) { - _DrawingMash = DrawingMash; + _drawingMash = DrawingMash; } public ObjectParameters? GetObjectPosition { get { - if (_DrawingMash == null || _DrawingMash.EntityMash == null) + if (_drawingMash == null || _drawingMash.EntityMash == null) { return null; } - return new ObjectParameters(_DrawingMash.GetPosX, _DrawingMash.GetPosY, _DrawingMash.GetWidth, _DrawingMash.GetHeight); + return new ObjectParameters(_drawingMash.GetPosX, _drawingMash.GetPosY, _drawingMash.GetWidth, _drawingMash.GetHeight); } } - public int GetStep => (int)(_DrawingMash?.EntityMash?.Step ?? 0); - public bool CheckCanMove(DirectionType direction) => _DrawingMash?.CanMove(direction) ?? false; - public void MoveObject(DirectionType direction) => _DrawingMash?.MoveTransport(direction); + public int GetStep => (int)(_drawingMash?.EntityMash?.Step ?? 0); + public bool CheckCanMove(DirectionType direction) => _drawingMash?.CanMove(direction) ?? false; + public void MoveObject(DirectionType direction) => _drawingMash?.MoveTransport(direction); } } \ No newline at end of file diff --git a/Excavator/Program.cs b/Excavator/Program.cs index 032fe7f..629b5f1 100644 --- a/Excavator/Program.cs +++ b/Excavator/Program.cs @@ -1,17 +1,40 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Excavator { internal static class Program { - /// - /// The main entry point for the application. - /// [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 FormExcavatorCollection()); + 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/Excavator/serilog.json b/Excavator/serilog.json new file mode 100644 index 0000000..d83ac59 --- /dev/null +++ b/Excavator/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/buslog.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ProjectAirbus" + } + } +} \ No newline at end of file