diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/AppSettings.json b/ProjectWarmlyShip/ProjectWarmlyShip/AppSettings.json new file mode 100644 index 0000000..20b8033 --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/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/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs index 2fd283e..2e00fb2 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipCollection.cs @@ -13,6 +13,8 @@ using System.Windows.Forms; using ProjectWarmlyShip.DrawingObjects; using ProjectWarmlyShip.Generics; using ProjectWarmlyShip.MovementStrategy; +using ProjectWarmlyShip.Exceptions; +using Microsoft.Extensions.Logging; namespace ProjectWarmlyShip { @@ -27,11 +29,13 @@ namespace ProjectWarmlyShip return pictureBoxCollection.Height; } private readonly ShipsGenericStorage _storage; - public FormShipCollection() + private readonly ILogger _logger; + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -61,6 +65,7 @@ namespace ProjectWarmlyShip } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Added set: {textBoxStorageName.Text}"); } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { @@ -73,11 +78,13 @@ namespace ProjectWarmlyShip { return; } - if (MessageBox.Show($"Delete Object {listBoxStorage.SelectedItem}?", "Deleting", + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Delete Object {name}?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Deleted set: {name}"); } } private void ButtonAddShip_Click(object sender, EventArgs e) @@ -106,14 +113,17 @@ namespace ProjectWarmlyShip { return; } - if (obj + ship) + try { - MessageBox.Show("Object Inserted"); + _ = obj + ship; + MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"ship added in set {listBoxStorage.SelectedItem.ToString()}"); } - else + catch (Exception ex) { - MessageBox.Show("Object Not Inserted"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"ship not added in set {listBoxStorage.SelectedItem.ToString()}"); } } private void ButtonRemoveShip_Click(Object sender, EventArgs e) @@ -132,15 +142,30 @@ namespace ProjectWarmlyShip { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Object Deleted"); - pictureBoxCollection.Image = obj.ShowShips(); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos != null) + { + MessageBox.Show("Object deleted"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"ship deleted in set {listBoxStorage.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Object not deleted"); + _logger.LogWarning($"ship not deleted in set {listBoxStorage.SelectedItem.ToString()}"); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Object Not Deleted"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"ShipNotFound: {ex.Message} in set {listBoxStorage.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Not input"); + _logger.LogWarning("Not input"); } } private void ButtonRefreshCollection(object sender, EventArgs e) @@ -160,15 +185,16 @@ namespace ProjectWarmlyShip { 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"); } } } @@ -176,16 +202,17 @@ namespace ProjectWarmlyShip { 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/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.cs b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.cs index 541ec9e..46aed94 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/FormShipConfig.cs @@ -10,6 +10,8 @@ using System.Windows.Forms; using ProjectWarmlyShip.Entities; using ProjectWarmlyShip.DrawingObjects; using static System.Windows.Forms.DataFormats; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace ProjectWarmlyShip { @@ -66,8 +68,8 @@ namespace ProjectWarmlyShip } private void panelObject_DragDrop(object sender, DragEventArgs e) { - - FormShipCollection form = new FormShipCollection(); + ILogger logger = new NullLogger(); + FormShipCollection form = new FormShipCollection(logger); switch (e.Data?.GetData(DataFormats.Text).ToString()) { case "labelSimpleObject": diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs index 2c7e667..e835664 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/Program.cs @@ -1,3 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace ProjectWarmlyShip { internal static class Program @@ -11,7 +18,28 @@ namespace ProjectWarmlyShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + 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/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj index 13ee123..2d6a006 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ProjectWarmlyShip.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs b/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs index 5f3b0b8..e94836e 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectWarmlyShip.Exceptions; namespace ProjectWarmlyShip.Generics { @@ -22,18 +23,26 @@ namespace ProjectWarmlyShip.Generics } public bool Insert(T ship, int position) { - if (position < 0 || position > _maxCount || _places.Count >= _maxCount) + if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new StorageOverflowException("Impossible to insert"); } _places.Insert(position, ship); return true; } public bool Remove(int position) { - if (position >= _places.Count || position < 0) + if (position >= Count || position < 0) { - return false; + throw new ShipNotFoundException("Invalid operation"); + } + if (_places[position] == null) + { + throw new ShipNotFoundException(position); } _places.RemoveAt(position); return true; @@ -69,4 +78,4 @@ namespace ProjectWarmlyShip.Generics } } } -} +} \ No newline at end of file diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs b/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.cs new file mode 100644 index 0000000..8902346 --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ShipNotFoundException.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 ProjectWarmlyShip.Exceptions +{ + [Serializable] + internal class ShipNotFoundException : ApplicationException + { + public ShipNotFoundException(int i) : base($"Not found object on position {i}") { } + public ShipNotFoundException() : base() { } + public ShipNotFoundException(string message) : base(message) { } + public ShipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ShipNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs b/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs index 245c43f..96ce75b 100644 --- a/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs +++ b/ProjectWarmlyShip/ProjectWarmlyShip/ShipsGenericStorage.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading.Tasks; using ProjectWarmlyShip.MovementStrategy; using ProjectWarmlyShip.DrawingObjects; -using ProjectWarmlyShip.Generics; +using ProjectWarmlyShip.Exceptions; namespace ProjectWarmlyShip.Generics { @@ -50,7 +50,7 @@ namespace ProjectWarmlyShip.Generics return null; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -68,20 +68,19 @@ namespace ProjectWarmlyShip.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($"ShipStorage{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"); } string bufferTextFromFile = ""; using (StreamReader reader = new StreamReader(filename)) @@ -96,11 +95,11 @@ namespace ProjectWarmlyShip.Generics StringSplitOptions.RemoveEmptyEntries); if (strs.Length == 0 || strs == null) { - return false; + throw new ArgumentException("There isn't any data for load"); } if (!strs[0].StartsWith("ShipStorage")) { - return false; + throw new InvalidDataException("Invalid format of data"); } _shipStorages.Clear(); foreach (string data in strs) @@ -119,13 +118,23 @@ namespace ProjectWarmlyShip.Generics { if (!(collection + ship)) { - return false; + try + { + _ = collection + ship; + } + catch (ShipNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } } } } _shipStorages.Add(record[0], collection); } - return true; } } -} +} \ No newline at end of file diff --git a/ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs b/ProjectWarmlyShip/ProjectWarmlyShip/StorageOverflowException.cs new file mode 100644 index 0000000..b35bd3b --- /dev/null +++ b/ProjectWarmlyShip/ProjectWarmlyShip/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 ProjectWarmlyShip.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