diff --git a/Tank/Tank/ExtentionDrawingTank.cs b/Tank/Tank/ExtentionDrawingTank.cs index a3df396..468feac 100644 --- a/Tank/Tank/ExtentionDrawingTank.cs +++ b/Tank/Tank/ExtentionDrawingTank.cs @@ -45,5 +45,6 @@ namespace Tank } return $"{str}{separatorForObject}{tank.AdditionalColor.Name}{separatorForObject}{tank.BodyKit}{separatorForObject}{tank.Caterpillar}{separatorForObject}{tank.Tower}"; } + } -} \ No newline at end of file +} diff --git a/Tank/Tank/FormTanksCollections.Designer.cs b/Tank/Tank/FormTanksCollections.Designer.cs index 4f047a9..d3f58a3 100644 --- a/Tank/Tank/FormTanksCollections.Designer.cs +++ b/Tank/Tank/FormTanksCollections.Designer.cs @@ -63,9 +63,9 @@ panel1.Controls.Add(InputNum); panel1.Controls.Add(label1); panel1.Dock = DockStyle.Right; - panel1.Location = new Point(694, 0); + panel1.Location = new Point(649, 0); panel1.Name = "panel1"; - panel1.Size = new Size(237, 479); + panel1.Size = new Size(237, 471); panel1.TabIndex = 0; // // menuStrip1 @@ -208,7 +208,7 @@ DrawTank.Dock = DockStyle.Fill; DrawTank.Location = new Point(0, 0); DrawTank.Name = "DrawTank"; - DrawTank.Size = new Size(694, 479); + DrawTank.Size = new Size(649, 471); DrawTank.TabIndex = 1; DrawTank.TabStop = false; // @@ -220,7 +220,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(931, 479); + ClientSize = new Size(886, 471); Controls.Add(DrawTank); Controls.Add(panel1); Name = "FormTanksCollections"; diff --git a/Tank/Tank/FormTanksCollections.cs b/Tank/Tank/FormTanksCollections.cs index 0f1db6f..88b5830 100644 --- a/Tank/Tank/FormTanksCollections.cs +++ b/Tank/Tank/FormTanksCollections.cs @@ -1,4 +1,6 @@ -using Tank.DrawningObjects; +using Microsoft.Extensions.Logging; +using Tank.Exceptions; +using Tank.DrawningObjects; using Tank.Generics; using Tank.MovementStrategy; using System; @@ -17,11 +19,15 @@ namespace Tank { private readonly TanksGenericStorage _storage; + // Логгер + private readonly ILogger _logger; + // Конструктор - public FormTanksCollections() + public FormTanksCollections(ILogger logger) { InitializeComponent(); _storage = new TanksGenericStorage(DrawTank.Width, DrawTank.Height); + _logger = logger; } private void ReloadObjects() @@ -48,15 +54,18 @@ namespace Tank { if (string.IsNullOrEmpty(SetTextBox.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Коллекция не добавлена, не все данные заполнены"); return; } _storage.AddSet(SetTextBox.Text); ReloadObjects(); + + _logger.LogInformation($"Добавлен набор: {SetTextBox.Text}"); } - private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) + private void ListBoxObjects_SelectedIndexChanged(object sender, + EventArgs e) { DrawTank.Image = _storage[CollectionListBox.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks(); @@ -66,14 +75,18 @@ namespace Tank { if (CollectionListBox.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {CollectionListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, + string name = CollectionListBox.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(CollectionListBox.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Набор '{name}' удален"); } + _logger.LogWarning("Отмена удаления набора"); } private void AddTank(DrawArmoVehicle tank) @@ -85,16 +98,24 @@ namespace Tank var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning("Добавление пустого объекта"); return; } - if ((obj + tank) != false) + + try { - MessageBox.Show("Объект добавлен"); - DrawTank.Image = obj.ShowTanks(); + if ((obj + tank) != false) + { + MessageBox.Show("Объект добавлен"); + DrawTank.Image = obj.ShowTanks(); + _logger.LogInformation($"Добавлен объект {obj}"); + } } - else + catch (TankStorageOverflowException ex) { + MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {CollectionListBox.SelectedItem.ToString()}"); } } @@ -119,29 +140,39 @@ namespace Tank { if (CollectionListBox.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); 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("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning("Отмена удаления объекта"); return; } int pos = Convert.ToInt32(InputNum.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - DrawTank.Image = obj.ShowTanks(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект с позиции{pos}"); + DrawTank.Image = obj.ShowTanks(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {CollectionListBox.SelectedItem.ToString()}"); + } } - else + catch (TankNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {CollectionListBox.SelectedItem.ToString()}"); } } @@ -164,13 +195,16 @@ namespace Tank { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}"); } } } @@ -179,16 +213,19 @@ namespace Tank { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); } } } } -} +} \ No newline at end of file diff --git a/Tank/Tank/Program.cs b/Tank/Tank/Program.cs index afa7dde..2161e4e 100644 --- a/Tank/Tank/Program.cs +++ b/Tank/Tank/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Tank; + namespace Tank { internal static class Program @@ -8,10 +14,31 @@ namespace Tank [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 FormTanksCollections()); + 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}appSetting.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/Tank/Tank/SetGeneric.cs b/Tank/Tank/SetGeneric.cs index 234613f..b645f01 100644 --- a/Tank/Tank/SetGeneric.cs +++ b/Tank/Tank/SetGeneric.cs @@ -1,4 +1,5 @@ -using Microsoft.VisualBasic; +using Tank.Exceptions; +using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Linq; @@ -33,10 +34,10 @@ namespace Tank public bool Insert(T tank, int position) { if (position < 0 || position >= _maxCount) - return false; + throw new TankNotFoundException(position); if (Count >= _maxCount) - return false; + throw new TankStorageOverflowException(_maxCount); // Макс количество или позицию _places.Insert(0, tank); return true; } @@ -44,10 +45,9 @@ namespace Tank // Удаление объекта из набора с конкретной позиции public bool Remove(int position) { - if (position < 0 || position > _maxCount) - return false; - if (position >= Count) - return false; + if (position < 0 || position > _maxCount || position >= Count) + throw new TankNotFoundException(position); + _places.RemoveAt(position); return true; } @@ -57,13 +57,13 @@ namespace Tank { get { - if (position < 0 || position > _maxCount) + if (position < 0 || position >= Count) return null; return _places[position]; } set { - if (position < 0 || position > _maxCount) + if (position < 0 || position > _maxCount || Count == _maxCount) return; _places[position] = value; } diff --git a/Tank/Tank/Tank.csproj b/Tank/Tank/Tank.csproj index b57c89e..5bf0190 100644 --- a/Tank/Tank/Tank.csproj +++ b/Tank/Tank/Tank.csproj @@ -8,4 +8,16 @@ enable + + + + + + + + + + + + \ No newline at end of file diff --git a/Tank/Tank/TankNotFoundException.cs b/Tank/Tank/TankNotFoundException.cs new file mode 100644 index 0000000..19a4816 --- /dev/null +++ b/Tank/Tank/TankNotFoundException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + + +namespace Tank.Exceptions +{ + [Serializable] + internal class TankNotFoundException : ApplicationException + { + public TankNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public TankNotFoundException() : base() { } + public TankNotFoundException(string message) : base(message) { } + public TankNotFoundException(string message, Exception exception) : base(message, exception) { } + protected TankNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/Tank/Tank/TankStorageOverflowException.cs b/Tank/Tank/TankStorageOverflowException.cs new file mode 100644 index 0000000..bf1da01 --- /dev/null +++ b/Tank/Tank/TankStorageOverflowException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + + +namespace Tank +{ + [Serializable] + internal class TankStorageOverflowException : ApplicationException + { + public TankStorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } + public TankStorageOverflowException() : base() { } + public TankStorageOverflowException(string message) : base(message) { } + public TankStorageOverflowException(string message, Exception exception) : base(message, exception) { } + protected TankStorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file diff --git a/Tank/Tank/TanksGenericCollection.cs b/Tank/Tank/TanksGenericCollection.cs index dc13839..46db3fb 100644 --- a/Tank/Tank/TanksGenericCollection.cs +++ b/Tank/Tank/TanksGenericCollection.cs @@ -50,10 +50,7 @@ namespace Tank.Generics public static T? operator -(TanksGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return obj; } diff --git a/Tank/Tank/TanksGenericStorage.cs b/Tank/Tank/TanksGenericStorage.cs index 22d97dd..e4c7910 100644 --- a/Tank/Tank/TanksGenericStorage.cs +++ b/Tank/Tank/TanksGenericStorage.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Tank.Generics; using Tank.DrawningObjects; using Tank.MovementStrategy; +using Tank.Exceptions; namespace Tank { @@ -56,7 +57,7 @@ namespace Tank } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -72,40 +73,45 @@ namespace Tank records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); - } + } if (data.Length == 0) { - return false; + throw new InvalidOperationException("File not found, невалиданя операция, нет данных для сохранения"); + //throw new Exception("File not found, ошибка, нет данных"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine("TankStorage"); writer.Write(data.ToString()); - return true; } } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } + using (StreamReader reader = new StreamReader(filename)) { string checker = reader.ReadLine(); if (checker == null) - return false; + throw new NullReferenceException("Нет данных для загрузки"); if (!checker.StartsWith("TankStorage")) - return false; + { + //если нет такой записи, то это не те данные + throw new FormatException("Неверный формат данных"); + } + _tankStorages.Clear(); string strs; bool firstinit = true; while ((strs = reader.ReadLine()) != null) { if (strs == null && firstinit) - return false; + throw new NullReferenceException("Нет данных для загрузки"); if (strs == null) break; firstinit = false; @@ -116,15 +122,22 @@ namespace Tank DrawArmoVehicle? vehicle = data?.CreateDrawTank(_separatorForObject, _pictureWidth, _pictureHeight); if (vehicle != null) { - if (!(collection + vehicle)) + try { - return false; + _ = collection + vehicle; + } + catch (TankNotFoundException e) + { + throw e; + } + catch (TankStorageOverflowException e) + { + throw e; } } } _tankStorages.Add(name, collection); } - return true; } } } diff --git a/Tank/Tank/appSetting.json b/Tank/Tank/appSetting.json new file mode 100644 index 0000000..f6ef585 --- /dev/null +++ b/Tank/Tank/appSetting.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": "Tank" + } + } +} \ No newline at end of file