diff --git a/HoistingCrane/HoistingCrane/App.config b/HoistingCrane/HoistingCrane/App.config new file mode 100644 index 0000000..bc02e6b --- /dev/null +++ b/HoistingCrane/HoistingCrane/App.config @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.Designer.cs b/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.Designer.cs index 7523fe8..78ff45b 100644 --- a/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.Designer.cs +++ b/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.Designer.cs @@ -121,7 +121,6 @@ this.comboBoxSelectorMap.Name = "comboBoxSelectorMap"; this.comboBoxSelectorMap.Size = new System.Drawing.Size(200, 28); this.comboBoxSelectorMap.TabIndex = 0; - this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged); // // textBoxNewMapName // @@ -155,7 +154,7 @@ // // maskedTextBoxPosition // - this.maskedTextBoxPosition.Location = new System.Drawing.Point(21, 459); + this.maskedTextBoxPosition.Location = new System.Drawing.Point(21, 436); this.maskedTextBoxPosition.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.maskedTextBoxPosition.Mask = "00"; this.maskedTextBoxPosition.Name = "maskedTextBoxPosition"; @@ -165,7 +164,7 @@ // // buttonRemoveHoistingCrane // - this.buttonRemoveHoistingCrane.Location = new System.Drawing.Point(20, 494); + this.buttonRemoveHoistingCrane.Location = new System.Drawing.Point(20, 471); this.buttonRemoveHoistingCrane.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.buttonRemoveHoistingCrane.Name = "buttonRemoveHoistingCrane"; this.buttonRemoveHoistingCrane.Size = new System.Drawing.Size(199, 47); @@ -176,7 +175,7 @@ // // buttonShowStorage // - this.buttonShowStorage.Location = new System.Drawing.Point(20, 549); + this.buttonShowStorage.Location = new System.Drawing.Point(20, 526); this.buttonShowStorage.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.buttonShowStorage.Name = "buttonShowStorage"; this.buttonShowStorage.Size = new System.Drawing.Size(199, 47); @@ -239,10 +238,10 @@ // // buttonShowOnMap // - this.buttonShowOnMap.Location = new System.Drawing.Point(20, 604); + this.buttonShowOnMap.Location = new System.Drawing.Point(21, 584); this.buttonShowOnMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.buttonShowOnMap.Name = "buttonShowOnMap"; - this.buttonShowOnMap.Size = new System.Drawing.Size(193, 47); + this.buttonShowOnMap.Size = new System.Drawing.Size(198, 47); this.buttonShowOnMap.TabIndex = 5; this.buttonShowOnMap.Text = "Посмотреть карту"; this.buttonShowOnMap.UseVisualStyleBackColor = true; @@ -250,7 +249,7 @@ // // buttonAddHoistingCrane // - this.buttonAddHoistingCrane.Location = new System.Drawing.Point(20, 404); + this.buttonAddHoistingCrane.Location = new System.Drawing.Point(20, 381); this.buttonAddHoistingCrane.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.buttonAddHoistingCrane.Name = "buttonAddHoistingCrane"; this.buttonAddHoistingCrane.Size = new System.Drawing.Size(199, 47); @@ -286,7 +285,7 @@ this.saveToolStripMenuItem, this.loadToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; - this.fileToolStripMenuItem.Size = new System.Drawing.Size(54, 29); + this.fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24); this.fileToolStripMenuItem.Text = "File"; // // saveToolStripMenuItem diff --git a/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.cs b/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.cs index 6a9c813..8b60519 100644 --- a/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.cs +++ b/HoistingCrane/HoistingCrane/FormMapWithSetHoistingCrane.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -21,13 +22,16 @@ namespace HoistingCrane }; /// /// Объект от коллекции карт + /// Логер /// + private readonly ILogger _logger; + /// private readonly MapsCollection _mapsCollection; /// - private MapWithSetHoistingCraneGeneric _mapHoistingCraneCollectionGeneric; - public FormMapWithSetHoistingCrane() + public FormMapWithSetHoistingCrane(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -57,29 +61,6 @@ namespace HoistingCrane listBoxMaps.SelectedIndex = index; } } - private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e) - { - AbstractMap map = null; - switch (comboBoxSelectorMap.Text) - { - case "Простая карта": - map = new SimpleMap(); - break; - case "Вторая карта": - map = new SecondMap(); - break; - - } - if (map != null) - { - _mapHoistingCraneCollectionGeneric = new MapWithSetHoistingCraneGeneric( - pictureBox.Width, pictureBox.Height, map); - } - else - { - _mapHoistingCraneCollectionGeneric = null; - } - } /// /// Добавление карты /// @@ -99,10 +80,12 @@ namespace HoistingCrane } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString()}"); } /// /// Удаление карты @@ -119,6 +102,7 @@ namespace HoistingCrane { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}"); } } private void ButtonAddHoistingCrane_Click(object sender, EventArgs e) @@ -133,15 +117,33 @@ namespace HoistingCrane } private void AddHoistingCrane(DrawingHoistingCrane drawingHoistingCrane) { - DrawingObjectHoistingCrane hoistingCrane = new DrawingObjectHoistingCrane(drawingHoistingCrane); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + hoistingCrane != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectHoistingCrane(drawingHoistingCrane) != -1) + { + _logger.LogInformation($"Добавлен кран {drawingHoistingCrane}"); + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning("Не удалось добавить кран"); + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}"); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } private void ButtonRemoveHoistingCrane_Click(object sender, EventArgs e) @@ -155,14 +157,28 @@ namespace HoistingCrane 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(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удален объект {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (HoistingCraneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Ошибка {ex.Message}"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning($"Ошибка {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } private void ButtonShowStorage_Click(object sender, EventArgs e) @@ -204,21 +220,24 @@ namespace HoistingCrane enums = Direction.Right; break; } - pictureBox.Image = _mapHoistingCraneCollectionGeneric.MoveObject(enums); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(enums); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение данных"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка {ex.Message}"); } } @@ -227,16 +246,19 @@ namespace HoistingCrane { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); + ReloadMaps(); MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - ReloadMaps(); + _logger.LogInformation($"Загрузка данных"); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось открыть", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка {ex.Message}"); } } } diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index b57c89e..f08bb8d 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -8,4 +8,18 @@ enable + + + + + + + + + + + + + + \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/HoistingCraneNotFoundException.cs b/HoistingCrane/HoistingCrane/HoistingCraneNotFoundException.cs new file mode 100644 index 0000000..4be24c4 --- /dev/null +++ b/HoistingCrane/HoistingCrane/HoistingCraneNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane +{ + [Serializable] + internal class HoistingCraneNotFoundException : ApplicationException + { + public HoistingCraneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public HoistingCraneNotFoundException() : base() { } + public HoistingCraneNotFoundException(string message) : base(message) { } + public HoistingCraneNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected HoistingCraneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/HoistingCrane/HoistingCrane/MapsCollection.cs b/HoistingCrane/HoistingCrane/MapsCollection.cs index bfefcfd..6ac3396 100644 --- a/HoistingCrane/HoistingCrane/MapsCollection.cs +++ b/HoistingCrane/HoistingCrane/MapsCollection.cs @@ -81,7 +81,7 @@ namespace HoistingCrane /// Сохранение информации про лодки м в хранилище в файл /// /// Путь и имя файла - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -99,15 +99,14 @@ namespace HoistingCrane ); } } - return true; } /// Загрузка информации по локомотивам в депо из файла - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException(filename); } using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) @@ -116,7 +115,7 @@ namespace HoistingCrane if (!curLine.Contains("MapsCollection")) { - return false; + throw new FormatException(curLine); } _mapStorages.Clear(); while ((curLine = sr.ReadLine()) != null) @@ -138,7 +137,6 @@ namespace HoistingCrane _mapStorages.Add(elems[0], new MapWithSetHoistingCraneGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[elems[0]].LoadData(elems[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } - return true; } } } diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 8b6d8ae..055801b 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,3 +1,9 @@ + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace HoistingCrane { internal static class Program @@ -8,10 +14,25 @@ namespace HoistingCrane [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 FormMapWithSetHoistingCrane()); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + 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 => + { + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: "appsettings.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/HoistingCrane/HoistingCrane/Properties/Settings.Designer.cs b/HoistingCrane/HoistingCrane/Properties/Settings.Designer.cs new file mode 100644 index 0000000..c1d4294 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace HoistingCrane.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/SetHoistingCraneGeneric.cs b/HoistingCrane/HoistingCrane/SetHoistingCraneGeneric.cs index 73c0856..710d61a 100644 --- a/HoistingCrane/HoistingCrane/SetHoistingCraneGeneric.cs +++ b/HoistingCrane/HoistingCrane/SetHoistingCraneGeneric.cs @@ -19,27 +19,52 @@ namespace HoistingCrane } public int Insert(T hoistingCrane) { - return Insert(hoistingCrane, 0); + for (int i = 0; i < _maxCount; i++) + { + if (i == Count) + { + _places.Insert(i, hoistingCrane); + return i; + } + } + throw new StorageOverflowException(_maxCount); + } public int Insert(T hoistingCrane, int position) { - if (position < 0 || position > Count || _maxCount == Count) + if (position < 0 || position >= _maxCount) { return -1; + + } + if (position == Count) + { + _places.Insert(position, hoistingCrane); + return position; + } + else + { + for (int i = position + 1; i < _maxCount; i++) + { + if (i == Count) + { + for (int j = i - 1; j >= position; j--) + { + _places[j + 1] = _places[j]; + } + _places.Insert(position, hoistingCrane); + return position; + } + } + throw new StorageOverflowException(_maxCount); } - _places.Insert(position, hoistingCrane); - return position; } public T Remove(int position) { - if (position < Count && position >= 0 && _places[position] != null) - { - _places[position] = null; - T removed = _places[position]; - return removed; - } - - return null; + if (position < 0 || position >= Count) throw new HoistingCraneNotFoundException(); + var result = _places[position]; + _places.RemoveAt(position); + return result; } public T this[int position] { diff --git a/HoistingCrane/HoistingCrane/StorageOverflowException.cs b/HoistingCrane/HoistingCrane/StorageOverflowException.cs new file mode 100644 index 0000000..7a74a0f --- /dev/null +++ b/HoistingCrane/HoistingCrane/StorageOverflowException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane +{ + [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/HoistingCrane/HoistingCrane/packages.config b/HoistingCrane/HoistingCrane/packages.config new file mode 100644 index 0000000..e05e131 --- /dev/null +++ b/HoistingCrane/HoistingCrane/packages.config @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file