diff --git a/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs b/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs index 5434bca..032e286 100644 --- a/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs +++ b/ProjectMachine/ProjectMachine/FormMapWithSetTank.Designer.cs @@ -70,9 +70,9 @@ this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.buttonAddTank); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(819, 28); + this.groupBoxTools.Location = new System.Drawing.Point(441, 28); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(233, 738); + this.groupBoxTools.Size = new System.Drawing.Size(233, 758); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Инструменты"; @@ -150,7 +150,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::ProjectMachine.Properties.Resources.лево; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonLeft.Location = new System.Drawing.Point(69, 683); + this.buttonLeft.Location = new System.Drawing.Point(69, 703); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(34, 30); this.buttonLeft.TabIndex = 13; @@ -163,7 +163,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::ProjectMachine.Properties.Resources.вверх; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonUp.Location = new System.Drawing.Point(105, 647); + this.buttonUp.Location = new System.Drawing.Point(105, 667); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(34, 30); this.buttonUp.TabIndex = 12; @@ -176,7 +176,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::ProjectMachine.Properties.Resources.право; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonRight.Location = new System.Drawing.Point(141, 683); + this.buttonRight.Location = new System.Drawing.Point(141, 703); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(34, 30); this.buttonRight.TabIndex = 11; @@ -189,7 +189,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::ProjectMachine.Properties.Resources.вниз; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonDown.Location = new System.Drawing.Point(105, 683); + this.buttonDown.Location = new System.Drawing.Point(105, 703); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(34, 30); this.buttonDown.TabIndex = 10; @@ -256,7 +256,7 @@ this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Location = new System.Drawing.Point(0, 28); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(819, 738); + this.pictureBox.Size = new System.Drawing.Size(441, 758); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // @@ -267,7 +267,7 @@ this.файлToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; - this.menuStrip.Size = new System.Drawing.Size(1052, 28); + this.menuStrip.Size = new System.Drawing.Size(674, 28); this.menuStrip.TabIndex = 2; this.menuStrip.Text = "menuStrip1"; // @@ -283,14 +283,14 @@ // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26); this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // LoadToolStripMenuItem // this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26); this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // @@ -306,7 +306,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1052, 766); + this.ClientSize = new System.Drawing.Size(674, 786); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); this.Controls.Add(this.menuStrip); diff --git a/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs b/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs index 9502968..827e727 100644 --- a/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs +++ b/ProjectMachine/ProjectMachine/FormMapWithSetTank.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using Serilog; namespace ProjectMachine { @@ -26,11 +18,16 @@ namespace ProjectMachine /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetTank() + public FormMapWithSetTank(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -70,15 +67,18 @@ namespace ProjectMachine if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Information("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Карта была не выбрана" : "Карта была не названа"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Warning("Нет карты с названием: {0}", textBoxNewMapName.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.Information($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -88,6 +88,7 @@ namespace ProjectMachine private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.Information("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } /// /// Удаление карты @@ -104,6 +105,7 @@ namespace ProjectMachine if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + _logger.Information("Была удалена карта под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } } @@ -120,18 +122,29 @@ namespace ProjectMachine } private void AddTank(DrawningMachine tank) { - if (listBoxMaps.SelectedIndex == -1) + try { - MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(tank) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.Information("Добавлен объект:", tank); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.Warning("Не удалось добавить объект"); + } } - else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(tank) != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else + catch (StorageOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.Warning("Ошибка переполнения хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// @@ -154,14 +167,29 @@ namespace ProjectMachine return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedTank = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedTank != null) + { + MessageBox.Show("Объект удален"); + _logger.Information("Из текущей карты удален объект {@tank}", deletedTank); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.Warning("Не удалось удалить объект по позиции {0}", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (TankNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.Warning($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -230,13 +258,16 @@ namespace ProjectMachine { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.Information("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Warning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -249,14 +280,17 @@ namespace ProjectMachine { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.Information("Загрузка файла '{0}' прошла успешно", openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch(Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Warning("Не удалось загрузить файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); } } } diff --git a/ProjectMachine/ProjectMachine/MapsCollection.cs b/ProjectMachine/ProjectMachine/MapsCollection.cs index 0d1235b..ef83221 100644 --- a/ProjectMachine/ProjectMachine/MapsCollection.cs +++ b/ProjectMachine/ProjectMachine/MapsCollection.cs @@ -94,71 +94,58 @@ namespace ProjectMachine /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } - using (FileStream fs = new(filename, FileMode.Create)) + using (StreamWriter f = new(filename)) { - WriteToFile($"MapsCollection{Environment.NewLine}", fs); + f.Write($"MapsCollection{Environment.NewLine}"); foreach (var storage in _mapStorages) { - - WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs); + f.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// /// Загрузка нформации по автомобилям на парковках из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader f = new(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + if (!f.ReadLine().Contains("MapsCollection")) { - bufferTextFromFile += temp.GetString(b); + //если нет такой записи, то это не те данные + throw new Exception("Формат данных в файле не правильный"); + } + //очищаем записи + _mapStorages.Clear(); + while (!f.EndOfStream) + { + var elem = f.ReadLine().Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "TownMap": + map = new TownMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetTankGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (!strs[0].Contains("MapsCollection")) - { - //если нет такой записи, то это не те данные - return false; - } - //очищаем записи - _mapStorages.Clear(); - for (int i = 1; i < strs.Length; ++i) - { - var elem = strs[i].Split(separatorDict); - AbstractMap map = null; - switch (elem[1]) - { - case "SimpleMap": - map = new SimpleMap(); - break; - case "TownMap": - map = new TownMap(); - break; - } - _mapStorages.Add(elem[0], new - MapWithSetTankGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData,StringSplitOptions.RemoveEmptyEntries)); - } - return true; } } } diff --git a/ProjectMachine/ProjectMachine/Program.cs b/ProjectMachine/ProjectMachine/Program.cs index 3db1ecc..acd8a42 100644 --- a/ProjectMachine/ProjectMachine/Program.cs +++ b/ProjectMachine/ProjectMachine/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.Configuration; +using Serilog; + namespace ProjectMachine { internal static class Program @@ -8,10 +11,17 @@ namespace ProjectMachine [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appconfig.json") + .AddJsonFile($"appconfig.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true) + .Build(); + var Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .ReadFrom.Configuration(configuration) + .CreateLogger(); ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetTank()); + Application.Run(new FormMapWithSetTank(Logger)); } } } \ No newline at end of file diff --git a/ProjectMachine/ProjectMachine/ProjectMachine.csproj b/ProjectMachine/ProjectMachine/ProjectMachine.csproj index 13ee123..234bb9b 100644 --- a/ProjectMachine/ProjectMachine/ProjectMachine.csproj +++ b/ProjectMachine/ProjectMachine/ProjectMachine.csproj @@ -8,6 +8,23 @@ enable + + + + + + + Always + + + + + + + + + + True @@ -23,4 +40,24 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProjectMachine/ProjectMachine/SetTankGeneric.cs b/ProjectMachine/ProjectMachine/SetTankGeneric.cs index 26f9a79..2cb1432 100644 --- a/ProjectMachine/ProjectMachine/SetTankGeneric.cs +++ b/ProjectMachine/ProjectMachine/SetTankGeneric.cs @@ -50,6 +50,8 @@ namespace ProjectMachine /// public int Insert(T tank, int position) { + if (Count >= _maxCount) + throw new StorageOverflowException(Count); if (position < 0 || position >= _maxCount) return -1; _places.Insert(position, tank); @@ -65,6 +67,8 @@ namespace ProjectMachine if (position < 0 || position >= Count) return null; var result = _places[position]; + if (result == null) + throw new TankNotFoundException(position); _places.RemoveAt(position); return result; } diff --git a/ProjectMachine/ProjectMachine/StorageOverflowException.cs b/ProjectMachine/ProjectMachine/StorageOverflowException.cs new file mode 100644 index 0000000..7b99341 --- /dev/null +++ b/ProjectMachine/ProjectMachine/StorageOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectMachine +{ + [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 contex) : base(info, contex) { } + } +} diff --git a/ProjectMachine/ProjectMachine/TankNotFoundException.cs b/ProjectMachine/ProjectMachine/TankNotFoundException.cs new file mode 100644 index 0000000..697745e --- /dev/null +++ b/ProjectMachine/ProjectMachine/TankNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectMachine +{ + internal class TankNotFoundException : ApplicationException + { + + public TankNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public TankNotFoundException() : base() { } + public TankNotFoundException(string message) : base(message) { } + public TankNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected TankNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectMachine/ProjectMachine/appconfig.json b/ProjectMachine/ProjectMachine/appconfig.json new file mode 100644 index 0000000..323ce72 --- /dev/null +++ b/ProjectMachine/ProjectMachine/appconfig.json @@ -0,0 +1,16 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level}: {Message};{NewLine}" + } + } + ] + } +} \ No newline at end of file