From f2bb1e99a82fe010c37d03b497f040a2761b6ff1 Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Mon, 21 Nov 2022 11:19:10 +0400 Subject: [PATCH 1/8] Lab 7 --- Catamaran/App.config | 54 +++++++++++++++++- Catamaran/BoatNotFoundException.cs | 21 +++++++ Catamaran/Catamaran.csproj | 80 +++++++++++++++++++++++++++ Catamaran/FormMapWithSetBoats.cs | 54 +++++++++++++----- Catamaran/MapsCollection.cs | 10 ++-- Catamaran/Program.cs | 24 ++++++-- Catamaran/StorageOverflowException.cs | 21 +++++++ Catamaran/nlog.config | 14 +++++ Catamaran/packages.config | 27 +++++++++ 9 files changed, 279 insertions(+), 26 deletions(-) create mode 100644 Catamaran/BoatNotFoundException.cs create mode 100644 Catamaran/StorageOverflowException.cs create mode 100644 Catamaran/nlog.config create mode 100644 Catamaran/packages.config diff --git a/Catamaran/App.config b/Catamaran/App.config index 56efbc7..99add49 100644 --- a/Catamaran/App.config +++ b/Catamaran/App.config @@ -1,6 +1,58 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Catamaran/BoatNotFoundException.cs b/Catamaran/BoatNotFoundException.cs new file mode 100644 index 0000000..a49c599 --- /dev/null +++ b/Catamaran/BoatNotFoundException.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 Catamaran +{ + [Serializable] + internal class BoatNotFoundException : ApplicationException + { + public BoatNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public BoatNotFoundException() : base() { } + public BoatNotFoundException(string message) : base(message) { } + public BoatNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Catamaran/Catamaran.csproj b/Catamaran/Catamaran.csproj index c83a6c2..23fce1a 100644 --- a/Catamaran/Catamaran.csproj +++ b/Catamaran/Catamaran.csproj @@ -33,8 +33,84 @@ 4 + + packages\Azure.Core.1.20.0\lib\net461\Azure.Core.dll + + + packages\Azure.Data.AppConfiguration.1.2.0\lib\netstandard2.0\Azure.Data.AppConfiguration.dll + + + packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + + + packages\Microsoft.Extensions.Configuration.Abstractions.2.1.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll + + + packages\Microsoft.Extensions.DependencyInjection.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll + + + packages\Microsoft.Extensions.DependencyInjection.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + packages\Microsoft.Extensions.Logging.7.0.0\lib\net462\Microsoft.Extensions.Logging.dll + + + packages\Microsoft.Extensions.Logging.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll + + + packages\Microsoft.Extensions.Options.7.0.0\lib\net462\Microsoft.Extensions.Options.dll + + + packages\Microsoft.Extensions.Primitives.7.0.0\lib\net462\Microsoft.Extensions.Primitives.dll + + + packages\NLog.5.0.5\lib\net46\NLog.dll + + + packages\NLog.Extensions.Logging.5.1.0\lib\net461\NLog.Extensions.Logging.dll + + + packages\Serilog.2.9.0\lib\net46\Serilog.dll + + + packages\Serilog.Extensions.Logging.3.1.0\lib\netstandard2.0\Serilog.Extensions.Logging.dll + + + packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + + + packages\System.Diagnostics.DiagnosticSource.7.0.0\lib\net462\System.Diagnostics.DiagnosticSource.dll + + + + packages\System.Memory.4.5.5\lib\net461\System.Memory.dll + + + packages\System.Memory.Data.1.0.2\lib\net461\System.Memory.Data.dll + + + + packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + packages\System.Text.Encodings.Web.4.7.2\lib\net461\System.Text.Encodings.Web.dll + + + packages\System.Text.Json.4.6.0\lib\net461\System.Text.Json.dll + + + packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + @@ -48,6 +124,7 @@ + @@ -81,6 +158,7 @@ + FormBoat.cs @@ -100,6 +178,8 @@ Resources.resx True + + SettingsSingleFileGenerator Settings.Designer.cs diff --git a/Catamaran/FormMapWithSetBoats.cs b/Catamaran/FormMapWithSetBoats.cs index 48c7d19..b1dde22 100644 --- a/Catamaran/FormMapWithSetBoats.cs +++ b/Catamaran/FormMapWithSetBoats.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -8,6 +9,8 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; + + namespace Catamaran { public partial class FormMapWithSetBoats : Form @@ -26,12 +29,19 @@ namespace Catamaran /// private readonly MapsCollection _mapsCollection; + /// + /// Логер + /// + private readonly ILogger _logger; + + /// /// Конструктор /// - public FormMapWithSetBoats() + public FormMapWithSetBoats(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -83,6 +93,8 @@ namespace Catamaran _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); + } /// @@ -135,15 +147,27 @@ namespace Catamaran 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(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + } + } /// /// Вывод набора @@ -238,17 +262,17 @@ namespace Catamaran { 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); } - } } private void loadToolStripMenuItem_Click(object sender, EventArgs e) @@ -256,15 +280,15 @@ namespace Catamaran // TODO продумать логику if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось открыть", "Результат", + MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/Catamaran/MapsCollection.cs b/Catamaran/MapsCollection.cs index f1aec84..51d7015 100644 --- a/Catamaran/MapsCollection.cs +++ b/Catamaran/MapsCollection.cs @@ -91,7 +91,7 @@ namespace Catamaran /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -106,7 +106,6 @@ namespace Catamaran sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"); } } - return true; } /// @@ -115,11 +114,11 @@ namespace Catamaran /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader sr = new StreamReader(filename)) { @@ -127,7 +126,7 @@ namespace Catamaran if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { //если нет такой записи, то это не те данные - return false; + throw new Exception("Формат данных в файле не правильный"); } //очищаем записи _mapStorages.Clear(); @@ -148,7 +147,6 @@ namespace Catamaran _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, (char)StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/Catamaran/Program.cs b/Catamaran/Program.cs index fb95aab..53e4ec9 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -3,20 +3,36 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; namespace Catamaran { internal static class Program { /// - /// Главная точка входа для приложения. + /// The main entry point for the application. /// [STAThread] static void Main() { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new FormMapWithSetBoats()); + ApplicationConfiguration.Initialize(); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } diff --git a/Catamaran/StorageOverflowException.cs b/Catamaran/StorageOverflowException.cs new file mode 100644 index 0000000..5357ebc --- /dev/null +++ b/Catamaran/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 Catamaran +{ + [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/Catamaran/nlog.config b/Catamaran/nlog.config new file mode 100644 index 0000000..249507c --- /dev/null +++ b/Catamaran/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Catamaran/packages.config b/Catamaran/packages.config new file mode 100644 index 0000000..258ab16 --- /dev/null +++ b/Catamaran/packages.config @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 0c640b3321a000725d560760878320e6c10f491a Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sat, 3 Dec 2022 20:28:56 +0400 Subject: [PATCH 2/8] 7 --- Catamaran/App.config | 54 +++++++++++------------ Catamaran/BoatDelegate.cs | 15 ------- Catamaran/Catamaran.csproj | 4 +- Catamaran/MapsCollection.cs | 12 +---- Catamaran/Program.cs | 4 +- Catamaran/Properties/Settings.Designer.cs | 30 ++++++------- 6 files changed, 46 insertions(+), 73 deletions(-) delete mode 100644 Catamaran/BoatDelegate.cs diff --git a/Catamaran/App.config b/Catamaran/App.config index 99add49..2744ee6 100644 --- a/Catamaran/App.config +++ b/Catamaran/App.config @@ -1,58 +1,58 @@ - + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - \ No newline at end of file + diff --git a/Catamaran/BoatDelegate.cs b/Catamaran/BoatDelegate.cs deleted file mode 100644 index c4bbd0b..0000000 --- a/Catamaran/BoatDelegate.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Catamaran -{ - - /// - /// Делегат для передачи объекта-лодки - /// - /// - public delegate void BoatDelegate(DrawingBoat boat); -} diff --git a/Catamaran/Catamaran.csproj b/Catamaran/Catamaran.csproj index 23fce1a..40a6757 100644 --- a/Catamaran/Catamaran.csproj +++ b/Catamaran/Catamaran.csproj @@ -8,10 +8,11 @@ WinExe Catamaran Catamaran - v4.7.2 + v4.8 512 true true + AnyCPU @@ -123,7 +124,6 @@ - diff --git a/Catamaran/MapsCollection.cs b/Catamaran/MapsCollection.cs index 51d7015..80ca7a6 100644 --- a/Catamaran/MapsCollection.cs +++ b/Catamaran/MapsCollection.cs @@ -80,17 +80,7 @@ namespace Catamaran /// /// Строка, которую следует записать /// Поток для записи - private static void WriteToFile(string text, FileStream stream) - { - byte[] info = new UTF8Encoding(true).GetBytes(text); - stream.Write(info, 0, info.Length); - } - - /// - /// Сохранение информации про лодки м в хранилище в файл - /// - /// Путь и имя файла - /// + public void SaveData(string filename) { if (File.Exists(filename)) diff --git a/Catamaran/Program.cs b/Catamaran/Program.cs index 53e4ec9..a331085 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -17,7 +17,9 @@ namespace Catamaran [STAThread] static void Main() { - ApplicationConfiguration.Initialize(); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + var services = new ServiceCollection(); ConfigureServices(services); using (ServiceProvider serviceProvider = services.BuildServiceProvider()) diff --git a/Catamaran/Properties/Settings.Designer.cs b/Catamaran/Properties/Settings.Designer.cs index 749d268..90ae974 100644 --- a/Catamaran/Properties/Settings.Designer.cs +++ b/Catamaran/Properties/Settings.Designer.cs @@ -1,28 +1,24 @@ //------------------------------------------------------------------------------ // -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 // -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. // //------------------------------------------------------------------------------ -namespace Catamaran.Properties -{ - - +namespace Catamaran.Properties { + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - + [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 - { + + public static Settings Default { + get { return defaultInstance; } } -- 2.25.1 From bc353c685f933c933c8dc62e3bd649992aec8558 Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sat, 3 Dec 2022 22:13:04 +0400 Subject: [PATCH 3/8] =?UTF-8?q?=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B2=20SetBoatsGeneric?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Catamaran/Program.cs | 1 + Catamaran/SetBoatsGeneric.cs | 13 +++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Catamaran/Program.cs b/Catamaran/Program.cs index a331085..0f4923c 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -17,6 +17,7 @@ namespace Catamaran [STAThread] static void Main() { + Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); diff --git a/Catamaran/SetBoatsGeneric.cs b/Catamaran/SetBoatsGeneric.cs index 811fe0c..445ecd9 100644 --- a/Catamaran/SetBoatsGeneric.cs +++ b/Catamaran/SetBoatsGeneric.cs @@ -48,7 +48,8 @@ namespace Catamaran return i; } } - return -1; + throw new StorageOverflowException(_maxCount); + } /// /// Добавление объекта в набор на конкретную позицию @@ -59,7 +60,11 @@ namespace Catamaran public int Insert(T boat, int position) { // TODO проверка позиции - if (position < 0 || position >= _maxCount) return -1; + if (position < 0 || position >= _maxCount) + { + throw new IndexOutOfRangeException(); + + } // TODO проверка, что элемент массива по этой позиции пустой,если нет, то // проверка, что после вставляемого элемента в массиве есть пустой элемент // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента @@ -82,7 +87,7 @@ namespace Catamaran return position; } } - return -1; + throw new BoatNotFoundException(_maxCount); } // TODO вставка по позиции } @@ -94,7 +99,7 @@ namespace Catamaran public T Remove(int position) { // TODO проверка позиции - if (position < 0 || position >= Count) return null; + if (position < 0 || position >= Count) throw new IndexOutOfRangeException(); // TODO удаление объекта из массива, присовив элементу массива значение null var result = _places[position]; _places.RemoveAt(position); -- 2.25.1 From e18445da4c73084c4ec5aa2cf9d99d753fd993fc Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sun, 4 Dec 2022 00:11:52 +0400 Subject: [PATCH 4/8] 7 --- Catamaran/FormMapWithSetBoats.cs | 46 ++++++++++++++++++++++++++------ Catamaran/MapsCollection.cs | 5 ++-- Catamaran/Program.cs | 1 - Catamaran/SetBoatsGeneric.cs | 6 ++--- Catamaran/nlog.config | 3 +-- 5 files changed, 45 insertions(+), 16 deletions(-) diff --git a/Catamaran/FormMapWithSetBoats.cs b/Catamaran/FormMapWithSetBoats.cs index b1dde22..44c7fcc 100644 --- a/Catamaran/FormMapWithSetBoats.cs +++ b/Catamaran/FormMapWithSetBoats.cs @@ -105,6 +105,8 @@ namespace Catamaran private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString()}"); + } /// @@ -121,6 +123,7 @@ namespace Catamaran if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}"); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } @@ -153,6 +156,8 @@ namespace Catamaran { MessageBox.Show("Объект удален"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удален объект {pos}"); + } else { @@ -161,10 +166,12 @@ namespace Catamaran } catch (BoatNotFoundException ex) { + _logger.LogWarning($"Ошибка {ex.Message}"); MessageBox.Show($"Ошибка удаления: {ex.Message}"); } catch (Exception ex) { + _logger.LogWarning($"Ошибка {ex.Message}"); MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } @@ -240,22 +247,38 @@ namespace Catamaran formBoatConfig.AddEvent(new Action(AddBoat)); // TODO Call method AddEvent from formBoatConfig formBoatConfig.Show(); + } private void AddBoat(DrawingBoat boat) { - if (listBoxMaps.SelectedIndex == -1) + try { - MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectBoat(boat) != -1) + { + _logger.LogInformation($"Добавлен лодку {boat}"); + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning("Не удалось добавить лодку"); + MessageBox.Show("Не удалось добавить объект"); + } } - else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectBoat(boat) != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}"); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } private void saveToolStripMenuItem_Click(object sender, EventArgs e) @@ -267,9 +290,12 @@ namespace Catamaran _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение данных"); + } catch (Exception ex) { + _logger.LogWarning($"Ошибка {ex.Message}"); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -282,12 +308,16 @@ namespace Catamaran { try { + _mapsCollection.LoadData(openFileDialog.FileName); + ReloadMaps(); MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - ReloadMaps(); + _logger.LogInformation($"Загрузка данных"); + } catch (Exception ex) { + _logger.LogWarning($"Ошибка {ex.Message}"); MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/Catamaran/MapsCollection.cs b/Catamaran/MapsCollection.cs index 80ca7a6..9c7db8f 100644 --- a/Catamaran/MapsCollection.cs +++ b/Catamaran/MapsCollection.cs @@ -108,7 +108,8 @@ namespace Catamaran { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException(filename); + } using (StreamReader sr = new StreamReader(filename)) { @@ -116,7 +117,7 @@ namespace Catamaran if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { //если нет такой записи, то это не те данные - throw new Exception("Формат данных в файле не правильный"); + throw new FormatException(str); } //очищаем записи _mapStorages.Clear(); diff --git a/Catamaran/Program.cs b/Catamaran/Program.cs index 0f4923c..a331085 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -17,7 +17,6 @@ namespace Catamaran [STAThread] static void Main() { - Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); diff --git a/Catamaran/SetBoatsGeneric.cs b/Catamaran/SetBoatsGeneric.cs index 445ecd9..0091e98 100644 --- a/Catamaran/SetBoatsGeneric.cs +++ b/Catamaran/SetBoatsGeneric.cs @@ -62,7 +62,7 @@ namespace Catamaran // TODO проверка позиции if (position < 0 || position >= _maxCount) { - throw new IndexOutOfRangeException(); + return -1 ; } // TODO проверка, что элемент массива по этой позиции пустой,если нет, то @@ -87,7 +87,7 @@ namespace Catamaran return position; } } - throw new BoatNotFoundException(_maxCount); + throw new StorageOverflowException(_maxCount); } // TODO вставка по позиции } @@ -99,7 +99,7 @@ namespace Catamaran public T Remove(int position) { // TODO проверка позиции - if (position < 0 || position >= Count) throw new IndexOutOfRangeException(); + if (position < 0 || position >= Count) throw new BoatNotFoundException(); // TODO удаление объекта из массива, присовив элементу массива значение null var result = _places[position]; _places.RemoveAt(position); diff --git a/Catamaran/nlog.config b/Catamaran/nlog.config index 249507c..65761ee 100644 --- a/Catamaran/nlog.config +++ b/Catamaran/nlog.config @@ -4,8 +4,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Info"> - + -- 2.25.1 From 0091fe4a9201ce18793a0b0adf12e639e4080a5e Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sun, 4 Dec 2022 14:11:37 +0400 Subject: [PATCH 5/8] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=85=D0=BE=D0=B4?= =?UTF-8?q?=20=D0=BD=D0=B0=20Serilog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Catamaran/App.config | 60 +++++++------ Catamaran/Catamaran.csproj | 100 ++++++++++++++++++++-- Catamaran/FormMapWithSetBoats.Designer.cs | 24 +++--- Catamaran/Program.cs | 17 ++-- Catamaran/appsettings.json | 20 +++++ Catamaran/nlog.config | 13 --- Catamaran/packages.config | 29 ++++++- 7 files changed, 194 insertions(+), 69 deletions(-) create mode 100644 Catamaran/appsettings.json delete mode 100644 Catamaran/nlog.config diff --git a/Catamaran/App.config b/Catamaran/App.config index 2744ee6..886bf17 100644 --- a/Catamaran/App.config +++ b/Catamaran/App.config @@ -1,57 +1,65 @@ - + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + + + diff --git a/Catamaran/Catamaran.csproj b/Catamaran/Catamaran.csproj index 40a6757..14a9808 100644 --- a/Catamaran/Catamaran.csproj +++ b/Catamaran/Catamaran.csproj @@ -43,8 +43,20 @@ packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll - - packages\Microsoft.Extensions.Configuration.Abstractions.2.1.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll + + packages\Microsoft.Extensions.Configuration.7.0.0\lib\net462\Microsoft.Extensions.Configuration.dll + + + packages\Microsoft.Extensions.Configuration.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.Configuration.Abstractions.dll + + + packages\Microsoft.Extensions.Configuration.Binder.2.0.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll + + + packages\Microsoft.Extensions.Configuration.FileExtensions.7.0.0\lib\net462\Microsoft.Extensions.Configuration.FileExtensions.dll + + + packages\Microsoft.Extensions.Configuration.Json.7.0.0\lib\net462\Microsoft.Extensions.Configuration.Json.dll packages\Microsoft.Extensions.DependencyInjection.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll @@ -52,6 +64,18 @@ packages\Microsoft.Extensions.DependencyInjection.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + packages\Microsoft.Extensions.DependencyModel.3.0.0\lib\net451\Microsoft.Extensions.DependencyModel.dll + + + packages\Microsoft.Extensions.FileProviders.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.FileProviders.Abstractions.dll + + + packages\Microsoft.Extensions.FileProviders.Physical.7.0.0\lib\net462\Microsoft.Extensions.FileProviders.Physical.dll + + + packages\Microsoft.Extensions.FileSystemGlobbing.7.0.0\lib\net462\Microsoft.Extensions.FileSystemGlobbing.dll + packages\Microsoft.Extensions.Logging.7.0.0\lib\net462\Microsoft.Extensions.Logging.dll @@ -64,6 +88,9 @@ packages\Microsoft.Extensions.Primitives.7.0.0\lib\net462\Microsoft.Extensions.Primitives.dll + + packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + packages\NLog.5.0.5\lib\net46\NLog.dll @@ -71,21 +98,37 @@ packages\NLog.Extensions.Logging.5.1.0\lib\net461\NLog.Extensions.Logging.dll - packages\Serilog.2.9.0\lib\net46\Serilog.dll + packages\Serilog.2.10.0\lib\net46\Serilog.dll packages\Serilog.Extensions.Logging.3.1.0\lib\netstandard2.0\Serilog.Extensions.Logging.dll + + packages\Serilog.Settings.Configuration.3.4.0\lib\net461\Serilog.Settings.Configuration.dll + + + packages\Serilog.Sinks.File.5.0.0\lib\net45\Serilog.Sinks.File.dll + packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + packages\System.Configuration.ConfigurationManager.7.0.0\lib\net462\System.Configuration.ConfigurationManager.dll + + packages\System.Diagnostics.DiagnosticSource.7.0.0\lib\net462\System.Diagnostics.DiagnosticSource.dll + + packages\System.IO.4.3.0\lib\net462\System.IO.dll + True + True + packages\System.Memory.4.5.5\lib\net461\System.Memory.dll @@ -93,22 +136,60 @@ packages\System.Memory.Data.1.0.2\lib\net461\System.Memory.Data.dll + packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + True + True + packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll - - packages\System.Text.Encodings.Web.4.7.2\lib\net461\System.Text.Encodings.Web.dll + + packages\System.Runtime.InteropServices.RuntimeInformation.4.0.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + True + True - - packages\System.Text.Json.4.6.0\lib\net461\System.Text.Json.dll + + + packages\System.Security.AccessControl.6.0.0\lib\net461\System.Security.AccessControl.dll + + + packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net463\System.Security.Cryptography.Algorithms.dll + True + True + + + packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + packages\System.Security.Permissions.7.0.0\lib\net462\System.Security.Permissions.dll + + + packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll + + + + packages\System.Text.Encodings.Web.7.0.0\lib\net462\System.Text.Encodings.Web.dll + + + packages\System.Text.Json.7.0.0\lib\net462\System.Text.Json.dll packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll @@ -121,6 +202,7 @@ + @@ -178,7 +260,9 @@ Resources.resx True - + + Always + SettingsSingleFileGenerator diff --git a/Catamaran/FormMapWithSetBoats.Designer.cs b/Catamaran/FormMapWithSetBoats.Designer.cs index 78eac40..110326b 100644 --- a/Catamaran/FormMapWithSetBoats.Designer.cs +++ b/Catamaran/FormMapWithSetBoats.Designer.cs @@ -70,9 +70,9 @@ this.groupBoxTools.Controls.Add(this.buttonUp); this.groupBoxTools.Controls.Add(this.buttonDown); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(653, 33); + this.groupBoxTools.Location = new System.Drawing.Point(653, 36); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(303, 614); + this.groupBoxTools.Size = new System.Drawing.Size(303, 611); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Tools"; @@ -192,7 +192,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::Catamaran.Properties.Resources.Left; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.buttonLeft.Location = new System.Drawing.Point(10, 529); + this.buttonLeft.Location = new System.Drawing.Point(10, 526); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(30, 30); this.buttonLeft.TabIndex = 4; @@ -204,7 +204,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::Catamaran.Properties.Resources.Right; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.buttonRight.Location = new System.Drawing.Point(70, 529); + this.buttonRight.Location = new System.Drawing.Point(70, 526); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(30, 30); this.buttonRight.TabIndex = 5; @@ -216,7 +216,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::Catamaran.Properties.Resources.Up; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.buttonUp.Location = new System.Drawing.Point(40, 507); + this.buttonUp.Location = new System.Drawing.Point(40, 504); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(30, 30); this.buttonUp.TabIndex = 2; @@ -228,7 +228,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::Catamaran.Properties.Resources.Down; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.buttonDown.Location = new System.Drawing.Point(40, 537); + this.buttonDown.Location = new System.Drawing.Point(40, 534); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(30, 30); this.buttonDown.TabIndex = 3; @@ -238,9 +238,9 @@ // pictureBox // this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.pictureBox.Location = new System.Drawing.Point(0, 33); + this.pictureBox.Location = new System.Drawing.Point(0, 36); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(653, 614); + this.pictureBox.Size = new System.Drawing.Size(653, 611); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // @@ -252,7 +252,7 @@ this.fileToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; - this.menuStrip.Size = new System.Drawing.Size(956, 33); + this.menuStrip.Size = new System.Drawing.Size(956, 36); this.menuStrip.TabIndex = 2; this.menuStrip.Text = "menuStrip"; // @@ -262,20 +262,20 @@ this.saveToolStripMenuItem, this.loadToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; - this.fileToolStripMenuItem.Size = new System.Drawing.Size(54, 29); + this.fileToolStripMenuItem.Size = new System.Drawing.Size(54, 32); this.fileToolStripMenuItem.Text = "File"; // // saveToolStripMenuItem // this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - this.saveToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.saveToolStripMenuItem.Size = new System.Drawing.Size(153, 34); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // loadToolStripMenuItem // this.loadToolStripMenuItem.Name = "loadToolStripMenuItem"; - this.loadToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.loadToolStripMenuItem.Size = new System.Drawing.Size(153, 34); this.loadToolStripMenuItem.Text = "Load"; this.loadToolStripMenuItem.Click += new System.EventHandler(this.loadToolStripMenuItem_Click); // diff --git a/Catamaran/Program.cs b/Catamaran/Program.cs index a331085..4f339df 100644 --- a/Catamaran/Program.cs +++ b/Catamaran/Program.cs @@ -1,11 +1,14 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; + +using Serilog; namespace Catamaran { @@ -30,11 +33,13 @@ namespace Catamaran private static void ConfigureServices(ServiceCollection services) { services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); + .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); + }); } } } diff --git a/Catamaran/appsettings.json b/Catamaran/appsettings.json new file mode 100644 index 0000000..433478a --- /dev/null +++ b/Catamaran/appsettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Catamaran" + } + } +} diff --git a/Catamaran/nlog.config b/Catamaran/nlog.config deleted file mode 100644 index 65761ee..0000000 --- a/Catamaran/nlog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/Catamaran/packages.config b/Catamaran/packages.config index 258ab16..1d3fde4 100644 --- a/Catamaran/packages.config +++ b/Catamaran/packages.config @@ -3,25 +3,46 @@ - + + + + + + + + + + - + + + + + + - - + + + + + + + + + \ No newline at end of file -- 2.25.1 From 3e84bde81fa6da76ca0c47880047f1088476dc29 Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Mon, 5 Dec 2022 10:14:19 +0400 Subject: [PATCH 6/8] Full_7 --- Catamaran/FormMapWithSetBoats.cs | 2 +- Catamaran/SetBoatsGeneric.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Catamaran/FormMapWithSetBoats.cs b/Catamaran/FormMapWithSetBoats.cs index 44c7fcc..11ae762 100644 --- a/Catamaran/FormMapWithSetBoats.cs +++ b/Catamaran/FormMapWithSetBoats.cs @@ -309,9 +309,9 @@ namespace Catamaran try { _mapsCollection.LoadData(openFileDialog.FileName); - ReloadMaps(); MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); _logger.LogInformation($"Загрузка данных"); } diff --git a/Catamaran/SetBoatsGeneric.cs b/Catamaran/SetBoatsGeneric.cs index 0091e98..4ebf8a9 100644 --- a/Catamaran/SetBoatsGeneric.cs +++ b/Catamaran/SetBoatsGeneric.cs @@ -39,12 +39,13 @@ namespace Catamaran /// public int Insert(T boat) { + for (int i = 0; i < _maxCount; i++) { if (i == Count) { - _places.Insert(i, boat); + _places.Insert(i,boat); return i; } } -- 2.25.1 From ed443decf04894e007680e33660244b173d9bd60 Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sun, 18 Dec 2022 18:05:15 +0400 Subject: [PATCH 7/8] mc --- Catamaran/MapsCollection.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Catamaran/MapsCollection.cs b/Catamaran/MapsCollection.cs index 9c7db8f..06e3389 100644 --- a/Catamaran/MapsCollection.cs +++ b/Catamaran/MapsCollection.cs @@ -74,12 +74,6 @@ namespace Catamaran return map; } } - - /// - /// Метод записи информации в файл - /// - /// Строка, которую следует записать - /// Поток для записи public void SaveData(string filename) { -- 2.25.1 From f95c1b3b60958a0ff0a6ddc14a40e4ada7a40f4f Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Sun, 18 Dec 2022 18:11:59 +0400 Subject: [PATCH 8/8] mc1 --- Catamaran/MapsCollection.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Catamaran/MapsCollection.cs b/Catamaran/MapsCollection.cs index 06e3389..91042ae 100644 --- a/Catamaran/MapsCollection.cs +++ b/Catamaran/MapsCollection.cs @@ -74,7 +74,12 @@ namespace Catamaran return map; } } - + + /// + /// Сохранение информации про лодки м в хранилище в файл + /// + /// Путь и имя файла + /// public void SaveData(string filename) { if (File.Exists(filename)) -- 2.25.1