diff --git a/Hydroplane/AppSettings.json b/Hydroplane/AppSettings.json new file mode 100644 index 0000000..20b8033 --- /dev/null +++ b/Hydroplane/AppSettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "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": "WarmlyShip" + } + } +} \ No newline at end of file diff --git a/Hydroplane/FormHydroplaneCollection.cs b/Hydroplane/FormHydroplaneCollection.cs index b195ff7..9a0185b 100644 --- a/Hydroplane/FormHydroplaneCollection.cs +++ b/Hydroplane/FormHydroplaneCollection.cs @@ -1,6 +1,5 @@ -using Hydroplane.DrawningObjects; -using Hydroplane.Generics; -using Hydroplane.MovementStrategy; +using Microsoft.Extensions.Logging; + using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,18 +10,26 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Hydroplane.Exceptions; +using Hydroplane.DrawningObjects; +using Hydroplane.Generics; +using Hydroplane.MovementStrategy; + namespace Hydroplane { public partial class FormHydroplaneCollection : Form { private readonly PlanesGenericStorage _storage; + + private readonly ILogger _logger; /// /// Конструктор /// - public FormHydroplaneCollection() + public FormHydroplaneCollection(ILogger logger) { InitializeComponent(); _storage = new PlanesGenericStorage(DrawPlane.Width, DrawPlane.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -56,12 +63,12 @@ namespace Hydroplane { if (string.IsNullOrEmpty(SetTextBox.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Input not complete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _storage.AddSet(SetTextBox.Text); ReloadObjects(); + _logger.LogInformation($"Added set: {SetTextBox.Text}"); } /// /// Выбор набора @@ -85,12 +92,13 @@ namespace Hydroplane { return; } - if (MessageBox.Show($"Удалить объект {CollectionListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, - MessageBoxIcon.Question) == DialogResult.Yes) + string name = CollectionListBox.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Delete Object {name}?", "Deleting", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(CollectionListBox.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Deleted set: {name}"); } } @@ -100,32 +108,43 @@ namespace Hydroplane { return; } - - var formPlaneConfig = new FormPlaneConfig(); - - formPlaneConfig.AddEvent(plane => + var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { - if (CollectionListBox.SelectedIndex != -1) - { - var obj = _storage[CollectionListBox.SelectedItem?.ToString() ?? string.Empty]; - if (obj != null) - { - if (obj + plane) - { - MessageBox.Show("Объект добавлен"); - DrawPlane.Image = obj.ShowPlanes(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - } - }); - + return; + } + FormPlaneConfig formPlaneConfig = new FormPlaneConfig(); + formPlaneConfig.AddEvent(AddPlane); formPlaneConfig.Show(); } + private void AddPlane(DrawningPlane plane) + { + if (CollectionListBox.SelectedIndex == -1) + { + return; + } + var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + plane; + MessageBox.Show("Объект добавлен"); + DrawPlane.Image = obj.ShowPlanes(); + _logger.LogInformation($"plane added in set {CollectionListBox.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"plane not added in set {CollectionListBox.SelectedItem.ToString()}"); + } + + } + /// /// Удаление объекта из набора /// @@ -137,28 +156,40 @@ namespace Hydroplane { return; } - var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show("Delete Object?", "Delete", MessageBoxButtons.YesNo, + MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = 0; - if (PlaneTextBox != null) - pos = Convert.ToInt32(PlaneTextBox.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - DrawPlane.Image = obj.ShowPlanes(); + int pos = Convert.ToInt32(PlaneTextBox.Text); + if (obj - pos != null) + { + MessageBox.Show("Object deleted"); + DrawPlane.Image = obj.ShowPlanes(); + _logger.LogInformation($"plane deleted in set {CollectionListBox.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Object not deleted"); + _logger.LogWarning($"plane not deleted in set {CollectionListBox.SelectedItem.ToString()}"); + } } - else + catch (PlaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"PlaneNotFound: {ex.Message} in set {CollectionListBox.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Not input"); + _logger.LogWarning("Not input"); } } /// @@ -172,8 +203,7 @@ namespace Hydroplane { return; } - var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -185,15 +215,16 @@ namespace Hydroplane { if (SaveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(SaveFileDialog.FileName)) + try { - MessageBox.Show("Save Complete", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(SaveFileDialog.FileName); + MessageBox.Show("Saving complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"save in file {SaveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Save Not Complete", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Not saved: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Save to file {SaveFileDialog.FileName} not complete"); } } } @@ -201,19 +232,19 @@ namespace Hydroplane { if (OpenFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(OpenFileDialog.FileName)) + try { - MessageBox.Show("Load Complete", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(OpenFileDialog.FileName); + MessageBox.Show("Load complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadObjects(); + _logger.LogInformation($"load from file {OpenFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Load Not Complete", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Not loaded: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"load from file {OpenFileDialog.FileName} not complete"); } } } - } } diff --git a/Hydroplane/FormPlaneConfig.cs b/Hydroplane/FormPlaneConfig.cs index 2cbfc37..a55caca 100644 --- a/Hydroplane/FormPlaneConfig.cs +++ b/Hydroplane/FormPlaneConfig.cs @@ -9,6 +9,8 @@ using System.Threading.Tasks; using System.Windows.Forms; using Hydroplane.DrawningObjects; using Hydroplane.Entities; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace Hydroplane { @@ -105,6 +107,7 @@ namespace Hydroplane /// private void panel_dragDrop(object sender, DragEventArgs e) { + ILogger logger = new NullLogger(); switch (e.Data?.GetData(DataFormats.Text).ToString()) { case "labelOriginalObject": diff --git a/Hydroplane/Hydroplane.csproj b/Hydroplane/Hydroplane.csproj index 13ee123..4c0a284 100644 --- a/Hydroplane/Hydroplane.csproj +++ b/Hydroplane/Hydroplane.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/Hydroplane/PlaneNotFoundException .cs b/Hydroplane/PlaneNotFoundException .cs new file mode 100644 index 0000000..2edea30 --- /dev/null +++ b/Hydroplane/PlaneNotFoundException .cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Hydroplane.Exceptions +{ + [Serializable] + internal class PlaneNotFoundException : ApplicationException + { + public PlaneNotFoundException(int i) : base($"Not found object on position {i}") { } + public PlaneNotFoundException() : base() { } + public PlaneNotFoundException(string message) : base(message) { } + public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected PlaneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} \ No newline at end of file diff --git a/Hydroplane/PlanesGenericStorage.cs b/Hydroplane/PlanesGenericStorage.cs index f0e0bcd..4376bfa 100644 --- a/Hydroplane/PlanesGenericStorage.cs +++ b/Hydroplane/PlanesGenericStorage.cs @@ -1,5 +1,6 @@ using Hydroplane.DrawningObjects; using Hydroplane.MovementStrategy; +using Hydroplane.Exceptions; using System; using System.Collections.Generic; using System.DirectoryServices.ActiveDirectory; @@ -47,7 +48,7 @@ namespace Hydroplane.Generics private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -65,20 +66,19 @@ namespace Hydroplane.Generics } if (data.Length == 0) { - return false; + throw new ArgumentException("Invalid operation, there isn't any data"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.Write($"PlaneStorage{Environment.NewLine}{data}"); } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("File not found"); } using (StreamReader fs = File.OpenText(filename)) @@ -86,11 +86,11 @@ namespace Hydroplane.Generics string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new ArgumentException("There isn't any data for load"); } if (!str.StartsWith("PlaneStorage")) { - return false; + throw new InvalidDataException("Invalid format of data"); } _planeStorages.Clear(); @@ -100,7 +100,7 @@ namespace Hydroplane.Generics { if (strs == null) { - return false; + return; } string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); @@ -117,13 +117,23 @@ namespace Hydroplane.Generics { if (!(collection + plane)) { - return false; + try + { + _ = collection + plane; + } + catch (PlaneNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } } } } _planeStorages.Add(record[0], collection); } - return true; } } } diff --git a/Hydroplane/Program.cs b/Hydroplane/Program.cs index 149f3d5..06baeb6 100644 --- a/Hydroplane/Program.cs +++ b/Hydroplane/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace Hydroplane { internal static class Program @@ -11,7 +17,28 @@ namespace Hydroplane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormHydroplaneCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}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/Hydroplane/SetGeneric.cs b/Hydroplane/SetGeneric.cs index 3c90c01..3476633 100644 --- a/Hydroplane/SetGeneric.cs +++ b/Hydroplane/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Hydroplane.Exceptions; namespace Hydroplane.Generics { @@ -26,20 +27,20 @@ namespace Hydroplane.Generics public bool Insert(T plane, int position) { if (position < 0 || position >= _maxCount) - return false; + throw new StorageOverflowException("Impossible to insert"); if (Count >= _maxCount) - return false; + throw new StorageOverflowException(_maxCount); _places.Insert(0, plane); return true; } public bool Remove(int position) { - if (position < 0 || position > _maxCount) - return false; - if (position >= Count) - return false; + if (position >= Count || position < 0) + throw new PlaneNotFoundException("Invalid operation"); + if (_places[position] == null) + throw new PlaneNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/Hydroplane/StorageOverflowException.cs b/Hydroplane/StorageOverflowException.cs new file mode 100644 index 0000000..4a7f85d --- /dev/null +++ b/Hydroplane/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Hydroplane.Exceptions +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"There is exceeded a limit of allowed number: {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) { } + } +} \ No newline at end of file