diff --git a/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj b/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj index 13ee123..625fbd7 100644 --- a/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj +++ b/AircraftCarrier/AircraftCarrier/AircraftCarrier.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs index 54f43f5..ab619a2 100644 --- a/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs +++ b/AircraftCarrier/AircraftCarrier/FormWarshipCollection.cs @@ -1,7 +1,8 @@ -using ProjectAircraftCarrier.DrawingObjects; +using Microsoft.VisualBasic.Logging; +using Microsoft.Extensions.Logging; +using ProjectAircraftCarrier.DrawingObjects; using ProjectAircraftCarrier.Generics; -using ProjectAircraftCarrier.MovementStrategy; -using System.Windows.Forms; +using ProjectAircraftCarrier.Exceptions; namespace ProjectAircraftCarrier { /// @@ -14,13 +15,18 @@ namespace ProjectAircraftCarrier /// private readonly WarshipsGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormWarshipCollection() + public FormWarshipCollection(ILogger logger) { InitializeComponent(); _storage = new WarshipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -34,12 +40,12 @@ namespace ProjectAircraftCarrier listBoxStorages.Items.Add(_storage.Keys[i]); } if (listBoxStorages.Items.Count > 0 && (index == -1 || index - >= listBoxStorages.Items.Count)) + >= listBoxStorages.Items.Count)) { listBoxStorages.SelectedIndex = 0; } else if (listBoxStorages.Items.Count > 0 && index > -1 && - index < listBoxStorages.Items.Count) + index < listBoxStorages.Items.Count) { listBoxStorages.SelectedIndex = index; } @@ -59,6 +65,7 @@ namespace ProjectAircraftCarrier } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Added set: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -83,14 +90,15 @@ namespace ProjectAircraftCarrier { return; } - if (MessageBox.Show($"Delete an object" + - $"{ listBoxStorages.SelectedItem}?", - "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + string name = listBoxStorages.SelectedItem.ToString() ?? + string.Empty; + if (MessageBox.Show($"Delete an object {name}?", "Deletion", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Deleted set: {name}"); } } /// @@ -112,15 +120,22 @@ namespace ProjectAircraftCarrier } FormWarshipConfig form = new(); form.Show(); - Action? warshipDelegate = new((warship) => { - if (obj + warship) + Action? warshipDelegate = new((warship) => + { + try { - MessageBox.Show("Object added"); + bool q = obj + warship; + MessageBox.Show("Object Added"); + _logger.LogInformation($"Object added to collection " + + $"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); pictureBoxCollection.Image = obj.ShowWarships(); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Failed to add an object"); + _logger.LogWarning($"Collection " + + $"{listBoxStorages.SelectedItem.ToString() ?? string.Empty} " + + $"is full"); + MessageBox.Show(ex.Message); } }); form.AddEvent(warshipDelegate); @@ -137,26 +152,41 @@ namespace ProjectAircraftCarrier return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + string.Empty]; if (obj == null) { return; } if (MessageBox.Show("Delete an object?", "Deletion", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == - DialogResult.No) + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == + DialogResult.No) { return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Object deleted"); - pictureBoxCollection.Image = obj.ShowWarships(); + if (obj - pos != null) + { + MessageBox.Show("Object deleted"); + _logger.LogInformation($"Object has been removed from the " + + $"collection " + + $"{listBoxStorages.SelectedItem.ToString() ?? string.Empty} " + + $"at position {pos}"); + pictureBoxCollection.Image = obj.ShowWarships(); + } + else + { + MessageBox.Show("Failed to delete an object"); + _logger.LogWarning($"Failed to remove object from the " + + $"collection " + + $"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + } } - else + catch (WarshipNotFoundException ex) { - MessageBox.Show("Failed to delete an object"); + _logger.LogWarning($"No number was entered"); + MessageBox.Show(ex.Message); } } /// @@ -187,15 +217,19 @@ namespace ProjectAircraftCarrier { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Save was successful", "Result", + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Save was successful", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"File {saveFileDialog.FileName} " + + $"successfuly saved"); } - else + catch (Exception ex) { - MessageBox.Show("Not preserved", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Failed to save"); + MessageBox.Show($"Not preserved: {ex.Message}", + "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -208,19 +242,24 @@ namespace ProjectAircraftCarrier { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Load was successful", - "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Load was successful", "Result", + MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"File {openFileDialog.FileName} " + + $"successfully loaded"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } + ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Not loaded", "Result", - MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Failed to load"); + MessageBox.Show($"Didn't load: {ex.Message}", "Result", + MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/AircraftCarrier/AircraftCarrier/Program.cs b/AircraftCarrier/AircraftCarrier/Program.cs index 2a20b85..eb5ad04 100644 --- a/AircraftCarrier/AircraftCarrier/Program.cs +++ b/AircraftCarrier/AircraftCarrier/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; namespace ProjectAircraftCarrier { internal static class Program @@ -11,7 +14,22 @@ namespace ProjectAircraftCarrier // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormWarshipCollection()); + 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"); + }); } } -} \ No newline at end of file +} diff --git a/AircraftCarrier/AircraftCarrier/SetGeneric.cs b/AircraftCarrier/AircraftCarrier/SetGeneric.cs index 4bb19ed..d6fe64a 100644 --- a/AircraftCarrier/AircraftCarrier/SetGeneric.cs +++ b/AircraftCarrier/AircraftCarrier/SetGeneric.cs @@ -1,5 +1,5 @@ using System.Numerics; - +using ProjectAircraftCarrier.Exceptions; namespace ProjectAircraftCarrier.Generics { /// @@ -38,7 +38,7 @@ namespace ProjectAircraftCarrier.Generics public bool Insert(T warship) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(warship, 0); return true; } @@ -50,8 +50,9 @@ namespace ProjectAircraftCarrier.Generics /// public bool Insert(T warship, int position) { - if (!(position >= 0 && position <= Count && _places.Count < - _maxCount)) + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) return false; _places.Insert(position, warship); return true; @@ -64,7 +65,7 @@ namespace ProjectAircraftCarrier.Generics public bool Remove(int position) { if (!(position >= 0 && position < Count)) - return false; + throw new WarshipNotFoundException(position); _places.RemoveAt(position); return true; } @@ -77,15 +78,17 @@ namespace ProjectAircraftCarrier.Generics { get { - if (!(position >= 0 && position <= Count)) + if (!(position >= 0 && position < Count)) return null; return _places[position]; } set { - if (!(position >= 0 && position <= Count)) + if (!(position >= 0 && position < Count && _places.Count < + _maxCount)) return; _places.Insert(position, value); + return; } } /// diff --git a/AircraftCarrier/AircraftCarrier/StorageOverflowException.cs b/AircraftCarrier/AircraftCarrier/StorageOverflowException.cs new file mode 100644 index 0000000..fc1ec1b --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/StorageOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectAircraftCarrier.Exceptions +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"The allowed " + + $"number is exceeded in the set: { 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/AircraftCarrier/AircraftCarrier/WarshipNotFoundException.cs b/AircraftCarrier/AircraftCarrier/WarshipNotFoundException.cs new file mode 100644 index 0000000..957c703 --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/WarshipNotFoundException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; +namespace ProjectAircraftCarrier.Exceptions +{ + [Serializable] + internal class WarshipNotFoundException : ApplicationException + { + public WarshipNotFoundException(int i) : base($"Object not found at" + + $" position {i}") { } + public WarshipNotFoundException() : base() { } + public WarshipNotFoundException(string message) : base(message) { } + public WarshipNotFoundException(string message, Exception exception) : + base(message, exception) { } + protected WarshipNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs b/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs index 4f4ef52..48814a2 100644 --- a/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs +++ b/AircraftCarrier/AircraftCarrier/WarshipsGenericStorage.cs @@ -97,7 +97,7 @@ namespace ProjectAircraftCarrier.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -105,13 +105,13 @@ namespace ProjectAircraftCarrier.Generics } StringBuilder data = new(); foreach (KeyValuePair> record in - _warshipStorages) + > + record in _warshipStorages) { StringBuilder records = new(); foreach (DrawingWarship? elem in record.Value.GetWarships) { - records.Append($"" + + records.Append( $"{elem?.GetDataForSave(_separatorForObject)}" + $"{_separatorRecords}"); } @@ -120,24 +120,24 @@ namespace ProjectAircraftCarrier.Generics } if (data.Length == 0) { - return false; + throw new Exception("Invalid operation, no data to save"); } using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes($"WarshipStorage" + - $"{Environment.NewLine}{data}"); + byte[] info = new UTF8Encoding(true).GetBytes + ($"CarStorage{Environment.NewLine}{data}"); fs.Write(info, 0, info.Length); - return true; + return; } /// /// Загрузка информации по кораблям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("File not found"); } string bufferTextFromFile = ""; using (FileStream fs = new(filename, FileMode.Open)) @@ -150,19 +150,19 @@ namespace ProjectAircraftCarrier.Generics } } var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); + StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("No data to download"); } if (!strs[0].StartsWith("WarshipStorage")) { - return false; + throw new Exception("Invalid data format"); } _warshipStorages.Clear(); foreach (string data in strs) { - string[] record = data.Split(_separatorForKeyValue, + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { @@ -170,24 +170,23 @@ namespace ProjectAircraftCarrier.Generics } WarshipsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { DrawingWarship? warship = - elem?.CreateDrawingWarship(_separatorForObject, + elem?.CreateDrawingWarship(_separatorForObject, _pictureWidth, _pictureHeight); if (warship != null) { if (!(collection + warship)) { - return false; + throw new Exception("Error adding to collection"); } } } _warshipStorages.Add(record[0], collection); } - return true; } } -} +} \ No newline at end of file diff --git a/AircraftCarrier/AircraftCarrier/nlog.config b/AircraftCarrier/AircraftCarrier/nlog.config new file mode 100644 index 0000000..63b7d65 --- /dev/null +++ b/AircraftCarrier/AircraftCarrier/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file