From b54ee7b861e2c7b3e821d54c67d3a2a3940c4423 Mon Sep 17 00:00:00 2001 From: Stranni15k Date: Thu, 22 Dec 2022 23:10:46 +0400 Subject: [PATCH] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=207?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ElectricLocomotive.csproj | 16 ++- .../FormMapWithSetLocomotive.Designer.cs | 7 +- .../FormMapWithSetLocomotive.cs | 99 +++++++++++++------ .../LocomotiveNotFoundException.cs | 19 ++++ .../MapWithSetLocomotivGeneric.cs | 2 +- .../ElectricLocomotive/MapsCollection.cs | 75 +++++++------- .../ElectricLocomotive/Program.cs | 43 +++++++- .../ElectricLocomotive/SetLocomotivGeneric.cs | 26 ++--- .../StorageOverflowException.cs | 19 ++++ .../ElectricLocomotive/serilog.json | 20 ++++ 10 files changed, 242 insertions(+), 84 deletions(-) create mode 100644 ElectricLocomotive/ElectricLocomotive/LocomotiveNotFoundException.cs create mode 100644 ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs create mode 100644 ElectricLocomotive/ElectricLocomotive/serilog.json diff --git a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj index 7d7c710..b5d9331 100644 --- a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj +++ b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj @@ -9,8 +9,20 @@ - - + + + + + + + + + + + + + + diff --git a/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.Designer.cs b/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.Designer.cs index 65cbcb9..f00674f 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.Designer.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.Designer.cs @@ -59,9 +59,9 @@ this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.pictureBox1.Location = new System.Drawing.Point(0, 0); + this.pictureBox1.Location = new System.Drawing.Point(0, 27); this.pictureBox1.Name = "pictureBox1"; - this.pictureBox1.Size = new System.Drawing.Size(808, 721); + this.pictureBox1.Size = new System.Drawing.Size(808, 694); this.pictureBox1.TabIndex = 10; this.pictureBox1.TabStop = false; // @@ -263,8 +263,9 @@ // this.openFileDialog.FileName = "openFileDialog1"; this.openFileDialog.Filter = "txt file | *.txt"; - // + // // saveFileDialog + // this.saveFileDialog.Filter = "txt file | *.txt"; // // FormMapWithSetLocomotive diff --git a/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.cs b/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.cs index 8215527..b2f4918 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormMapWithSetLocomotive.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -20,9 +21,11 @@ namespace ElectricLocomotive {"Карта с кустами",new BushesMap() } }; private readonly MapsCollection _mapsCollection; - public FormMapWithSetLocomotive() + private readonly ILogger _logger; + public FormMapWithSetLocomotive(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapDict) @@ -81,23 +84,36 @@ namespace ElectricLocomotive FormLocmotiveConfig.AddEvent(new(AddLocomotive)); FormLocmotiveConfig.Show(); } - public void AddLocomotive(DrawningLocomotive aircraft) + public void AddLocomotive(DrawningLocomotive locomotive) { - if (ListBoxMaps.SelectedIndex == -1) + try { - return; + if (ListBoxMaps.SelectedIndex == -1) + { + return; + } + if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Locomotive}", locomotive); + pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - - if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(aircraft) != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Object is added"); - pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch (ArgumentException ex) { - MessageBox.Show("Unable to add object"); + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Locomotive}", ex.Message, locomotive); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - } private void ButtonRemoveLocomotive_Click(object sender, EventArgs e) { @@ -114,14 +130,30 @@ namespace ElectricLocomotive return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedLocomotive = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedLocomotive != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Locomotive}", deletedLocomotive); + pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LocomotiveNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } private void ButtonShowStorage_Click(object sender, EventArgs e) @@ -168,18 +200,23 @@ namespace ElectricLocomotive } private void ButtonAddMap_Click(object sender, EventArgs e) { - if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) + if (comboBoxSelectorMap.SelectedIndex == -1 || + string.IsNullOrEmpty(textBoxNewMapName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) { - MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); return; } - _mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]); + _mapsCollection.AddMap(textBoxNewMapName.Text, + _mapDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { @@ -202,14 +239,15 @@ namespace ElectricLocomotive { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -219,14 +257,17 @@ namespace ElectricLocomotive { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); - 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($"Не удалось загрузить: {openFileDialog.FileName} | {ex.Message}."); } } } diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotiveNotFoundException.cs b/ElectricLocomotive/ElectricLocomotive/LocomotiveNotFoundException.cs new file mode 100644 index 0000000..836613e --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/LocomotiveNotFoundException.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 ElectricLocomotive +{ + [Serializable] + internal class LocomotiveNotFoundException : ApplicationException + { + public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции{ i}") { } + public LocomotiveNotFoundException() : base() { } + public LocomotiveNotFoundException(string message) : base(message) { } + public LocomotiveNotFoundException(string message, Exception exception) : base(message, exception) { } + protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ElectricLocomotive/ElectricLocomotive/MapWithSetLocomotivGeneric.cs b/ElectricLocomotive/ElectricLocomotive/MapWithSetLocomotivGeneric.cs index 0da7333..7e7c322 100644 --- a/ElectricLocomotive/ElectricLocomotive/MapWithSetLocomotivGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/MapWithSetLocomotivGeneric.cs @@ -118,7 +118,7 @@ foreach (var HardLocomotive in _setLocomotive.GetLocomotive()) { (float Left, float Top, float Right, float Bottom) = HardLocomotive.GetCurrentPosition(); - HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 70), _pictureWidth, _pictureHeight); + HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 60), _pictureWidth, _pictureHeight); HardLocomotive.DrawningObject(g); if (ColumnIndex == xNumOfPlaces - 1) { diff --git a/ElectricLocomotive/ElectricLocomotive/MapsCollection.cs b/ElectricLocomotive/ElectricLocomotive/MapsCollection.cs index 34b5b94..b78922f 100644 --- a/ElectricLocomotive/ElectricLocomotive/MapsCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/MapsCollection.cs @@ -43,66 +43,71 @@ namespace ElectricLocomotive return null; } } - private static void WriteToFile(string text, FileStream stream) { byte[] info = new UTF8Encoding(true).GetBytes(text); stream.Write(info, 0, info.Length); } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } - using (StreamWriter fs = new StreamWriter(filename)) + using (FileStream fs = new(filename, FileMode.Create)) { - fs.Write($"MapsCollection{Environment.NewLine}"); + WriteToFile($"MapsCollection{Environment.NewLine}", fs); foreach (var storage in _mapStorages) { - fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); + WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs); } } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } - string str = ""; - using (StreamReader fs = new StreamReader(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - str = fs.ReadLine(); - if (!str.Contains("MapsCollection")) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - //если нет такой записи, то это не те данные - return false; - } - _mapStorages.Clear(); - while ((str = fs.ReadLine()) != null) - { - var elem = str.Split(separatorDict); - AbstractMap map = null; - switch (elem[1]) - { - case "SimpleMap": - map = new SimpleMap(); - break; - case "BushesMap": - map = new BushesMap(); - break; - case "FieldMap": - map = new FieldMap(); - break; - } - _mapStorages.Add(elem[0], new MapWithSetLocomotivGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + bufferTextFromFile += temp.GetString(b); } } - return true; + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (!strs[0].Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + throw new Exception("Формат данных в файле не правильный"); + } + //очищаем записи + _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 "FieldMap": + map = new FieldMap(); + break; + case "BushesMap": + map = new BushesMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetLocomotivGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } } } } diff --git a/ElectricLocomotive/ElectricLocomotive/Program.cs b/ElectricLocomotive/ElectricLocomotive/Program.cs index c8d658b..3d94872 100644 --- a/ElectricLocomotive/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/ElectricLocomotive/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; +using System.Diagnostics; +using System.Reflection; + namespace ElectricLocomotive { internal static class Program @@ -11,7 +19,40 @@ namespace ElectricLocomotive // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetLocomotive()); + + var services = new ServiceCollection(); + ConfigureServices(services); + + using (ServiceProvider serviceProvider =services.BuildServiceProvider()) + { + + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(ServiceCollection services) + { + string path = Directory.GetCurrentDirectory(); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); + + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: path + "\\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/ElectricLocomotive/ElectricLocomotive/SetLocomotivGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetLocomotivGeneric.cs index 05c32fa..db34f66 100644 --- a/ElectricLocomotive/ElectricLocomotive/SetLocomotivGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/SetLocomotivGeneric.cs @@ -19,33 +19,33 @@ namespace ElectricLocomotive } public int Insert(T locomotive) { - if (_places.Count > _maxCount) - { - return -1; - } - // вставка в начало набора return Insert(locomotive, 0); } public int Insert(T locomotive, int position) { - if (position >= _maxCount || position < 0) return -1; + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position > _maxCount) return -1; _places.Insert(position, locomotive); return position; } public T Remove(int position) { - // проверка позиции - if (position >= _maxCount || position < 0) return null; - // удаление объекта из массива, присовив элементу массива значение null - T temp = _places[position]; + if (position >= Count || position < 0) + { + throw new LocomotiveNotFoundException(position); + } + T ship = _places[position]; _places.RemoveAt(position); - return temp; + return ship; } public T this[int position] { get { - if (position >= _places.Count || position < 0) + if (position >= Count || position < 0) { return null; } @@ -53,7 +53,7 @@ namespace ElectricLocomotive } set { - if (position >= _places.Count || position < 0) + if (position >= Count || position < 0) { return; } diff --git a/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs b/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs new file mode 100644 index 0000000..2e84a33 --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/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 ElectricLocomotive +{ + [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/ElectricLocomotive/ElectricLocomotive/serilog.json b/ElectricLocomotive/ElectricLocomotive/serilog.json new file mode 100644 index 0000000..593281c --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Locomotive" + } + } +} \ No newline at end of file -- 2.25.1