diff --git a/ProjectBulldozer/Exceptions/BulldozerNotFoundException.cs b/ProjectBulldozer/Exceptions/BulldozerNotFoundException.cs new file mode 100644 index 0000000..ad76077 --- /dev/null +++ b/ProjectBulldozer/Exceptions/BulldozerNotFoundException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; +namespace ProjectBulldozer.Exceptions +{ + [Serializable] + internal class BulldozerNotFoundException : ApplicationException + { + public BulldozerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + + public BulldozerNotFoundException() : base() { } + + public BulldozerNotFoundException(string message) : base(message) { } + + public BulldozerNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected BulldozerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/ProjectBulldozer/Exceptions/StorageOverflowException.cs b/ProjectBulldozer/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..3a180e8 --- /dev/null +++ b/ProjectBulldozer/Exceptions/StorageOverflowException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; +namespace ProjectBulldozer.Exceptions +{ + [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 context) : base(info, context) { } + } +} diff --git a/ProjectBulldozer/FormBulldozerCollections.Designer.cs b/ProjectBulldozer/FormBulldozerCollections.Designer.cs index fc7a868..0b6c7d3 100644 --- a/ProjectBulldozer/FormBulldozerCollections.Designer.cs +++ b/ProjectBulldozer/FormBulldozerCollections.Designer.cs @@ -1,4 +1,6 @@ -namespace ProjectBulldozer +using System.ComponentModel; + +namespace ProjectBulldozer { partial class FormTractorCollections { @@ -23,7 +25,7 @@ сохранитьToolStripMenuItem = new ToolStripMenuItem(); загрузитьToolStripMenuItem = new ToolStripMenuItem(); toolStripMenuItem1 = new ToolStripMenuItem(); - ((System.ComponentModel.ISupportInitialize)pictureBoxCollections).BeginInit(); + ((ISupportInitialize)pictureBoxCollections).BeginInit(); groupBox1.SuspendLayout(); Instruments.SuspendLayout(); menuStrip1.SuspendLayout(); @@ -34,7 +36,7 @@ maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBoxNumber.Location = new Point(33, 356); maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2); - maskedTextBoxNumber.Mask = "0"; + maskedTextBoxNumber.Mask = "00"; maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Size = new Size(131, 23); maskedTextBoxNumber.TabIndex = 4; @@ -217,7 +219,7 @@ Margin = new Padding(3, 2, 3, 2); Name = "FormTractorCollections"; Text = "Набор объектов"; - ((System.ComponentModel.ISupportInitialize)pictureBoxCollections).EndInit(); + ((ISupportInitialize)pictureBoxCollections).EndInit(); groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); Instruments.ResumeLayout(false); @@ -227,6 +229,22 @@ ResumeLayout(false); PerformLayout(); } + + private void файлToolStripMenuItem_Click(object sender, EventArgs e) + { + throw new NotImplementedException(); + } + + private void saveFileDialog_FileOk(object sender, CancelEventArgs e) + { + throw new NotImplementedException(); + } + + private void openFileDialog_FileOk(object sender, CancelEventArgs e) + { + throw new NotImplementedException(); + } + private void pictureBoxCollections_Click(object sender, EventArgs e) { throw new NotImplementedException(); diff --git a/ProjectBulldozer/FormBulldozerCollections.cs b/ProjectBulldozer/FormBulldozerCollections.cs index d65c129..015a40a 100644 --- a/ProjectBulldozer/FormBulldozerCollections.cs +++ b/ProjectBulldozer/FormBulldozerCollections.cs @@ -1,6 +1,10 @@ using Bulldozer; using ProjectBulldozer.Generics; using ProjectBulldozer.Drawning; +using ProjectBulldozer.Exceptions; +using Microsoft.Extensions.Logging; +using System.ComponentModel; +using System.Xml.Linq; namespace ProjectBulldozer { public partial class FormTractorCollections : Form @@ -8,11 +12,20 @@ namespace ProjectBulldozer private readonly TractorGenericStorage _storage; private readonly TractorGenericCollection _tractors; readonly int countPlace = 10; + private readonly ILogger _logger; + public FormTractorCollections() { InitializeComponent(); _storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height); } + public FormTractorCollections(ILogger logger) + { + InitializeComponent(); + _storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height); + _logger = logger; + } + private void ReloadObjects() { int index = listBoxStorage.SelectedIndex; @@ -36,10 +49,12 @@ namespace ProjectBulldozer if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"!!Ошибка!! Не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e) { @@ -49,13 +64,16 @@ namespace ProjectBulldozer { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning($"Удаление не выбранного набора"); return; } + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void ButtonAddTractor_Click(object sender, EventArgs e) @@ -81,22 +99,30 @@ namespace ProjectBulldozer tractor._pictureHeight = pictureBoxCollections.Height; if (listBoxStorage.SelectedIndex == -1) return; - var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; - + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; if (obj == null) { return; } - int addedIndex = obj + tractor; - if (addedIndex != -1 && addedIndex < countPlace) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollections.Image = obj.ShowTractors(); + if (obj + tractor) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollections.Image = obj.ShowTractors(); + _logger.LogInformation($"В набор {name} добавлен объект"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось добавить объект"); } } private void ButtonRemoveTractor_Click(object sender, EventArgs e) @@ -111,17 +137,30 @@ namespace ProjectBulldozer { return; } + if (maskedTextBoxNumber.Text == "") { return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollections.Image = obj.ShowTractors(); + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollections.Image = obj.ShowTractors(); + _logger.LogInformation($"Из набора {name} удален объект"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Не удалось удалить объект"); + } } - else + catch (BulldozerNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось удалить объект"); } } + private void ButtonRefreshCollection_Click(object sender, EventArgs e) { if (listBoxStorage.SelectedIndex == -1) return; @@ -136,15 +175,16 @@ namespace ProjectBulldozer { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка сохранения"); } } } @@ -152,21 +192,21 @@ namespace ProjectBulldozer { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + ReloadObjects(); + MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка загрузки"); } - ReloadObjects(); } } } } - diff --git a/ProjectBulldozer/FormBulldozerCollections.resx b/ProjectBulldozer/FormBulldozerCollections.resx index 1c86d73..0a3f5bf 100644 --- a/ProjectBulldozer/FormBulldozerCollections.resx +++ b/ProjectBulldozer/FormBulldozerCollections.resx @@ -18,9 +18,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, ... System.Resources.ResXResourceWriter, System.Windows.Forms, ... this is my long stringthis is a comment - Blue + Blue [base64 mime encoded serialized .NET Framework object] @@ -119,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 153, 17 + + + 286, 17 + \ No newline at end of file diff --git a/ProjectBulldozer/Generics/BulldozerGenericCollection.cs b/ProjectBulldozer/Generics/BulldozerGenericCollection.cs index 6c407b9..65f3235 100644 --- a/ProjectBulldozer/Generics/BulldozerGenericCollection.cs +++ b/ProjectBulldozer/Generics/BulldozerGenericCollection.cs @@ -19,12 +19,9 @@ namespace ProjectBulldozer.Generics _pictureHeight = picHeight; _collection = new SetGeneric(width * height); } - public static int operator +(TractorGenericCollection collect, T? tract) + public static bool operator +(TractorGenericCollection collect, T? tract) { - if (tract == null) - { - return -1; - } + if (tract == null) return false; return collect._collection.Insert(tract); } public static T? operator -(TractorGenericCollection collect, int pos) diff --git a/ProjectBulldozer/Generics/SetGeneric.cs b/ProjectBulldozer/Generics/SetGeneric.cs index 85feb5c..e72614a 100644 --- a/ProjectBulldozer/Generics/SetGeneric.cs +++ b/ProjectBulldozer/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -namespace ProjectBulldozer.Generics +using ProjectBulldozer.Exceptions; +namespace ProjectBulldozer.Generics { internal class SetGeneric where T : class { @@ -12,24 +13,35 @@ _places = new List(count); } /// Добавление объекта в набор - public int Insert(T tract) + public bool Insert(T tract) { return Insert(tract, 0); } - public int Insert(T tract, int position) + public bool Insert(T tract, int position) { - if (position < 0 || position >= _maxCount) return -1; + if (position < 0 || position >= _maxCount) + { + throw new BulldozerNotFoundException(position); + } + if (Count >= _maxCount) + { + throw new StorageOverflowException(_maxCount); + } _places.Insert(position, tract); - return position; + return true; } - public T? Remove(int position) + public bool Remove(int position) { - if (position >= Count || position < 0) - return null; - - T? tmp = _places[position]; + if (position < 0 || position >= _maxCount) + { + return false; + } + if (_places[position] == null) + { + throw new BulldozerNotFoundException(position); + } _places[position] = null; - return tmp; + return true; } public T? this[int position] { diff --git a/ProjectBulldozer/Generics/TractorGenericStorage.cs b/ProjectBulldozer/Generics/TractorGenericStorage.cs index 115c21a..07a2f5d 100644 --- a/ProjectBulldozer/Generics/TractorGenericStorage.cs +++ b/ProjectBulldozer/Generics/TractorGenericStorage.cs @@ -64,7 +64,7 @@ namespace ProjectBulldozer.Generics } if (data.Length == 0) { - return false; + throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения"); } using StreamWriter sw = new(filename); sw.Write($"TractorsStorage{Environment.NewLine}{data}"); @@ -74,7 +74,7 @@ namespace ProjectBulldozer.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = File.OpenText(filename)) { @@ -85,7 +85,7 @@ namespace ProjectBulldozer.Generics } if (!str.StartsWith("TractorsStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _TractorsStorage.Clear(); @@ -112,9 +112,9 @@ namespace ProjectBulldozer.Generics _pictureWidth, _pictureHeight); if (tractor != null) { - if ((collection + tractor) == -1) + if ((collection + tractor)) { - return false; + throw new ApplicationException("Ошибка добавления в коллекцию"); } } } diff --git a/ProjectBulldozer/Program.cs b/ProjectBulldozer/Program.cs index 075760c..7dfd5d5 100644 --- a/ProjectBulldozer/Program.cs +++ b/ProjectBulldozer/Program.cs @@ -1,14 +1,40 @@ using ProjectBulldozer; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; namespace Bulldozer { internal static class Program { + private static Serilog.ILogger? logger; [STAThread] static void Main() { - https://aka.ms/applicationconfiguration. + // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTractorCollections()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + private static void ConfigureServices(IServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string appPath = ""; + for (int i = 0; i < path.Length - 3; i++) + { + appPath += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").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/ProjectBulldozer/ProjectBulldozer.csproj b/ProjectBulldozer/ProjectBulldozer.csproj index 13ee123..cec3516 100644 --- a/ProjectBulldozer/ProjectBulldozer.csproj +++ b/ProjectBulldozer/ProjectBulldozer.csproj @@ -8,6 +8,20 @@ enable + + + + + + + + + + + + + + True diff --git a/ProjectBulldozer/appsettings.json b/ProjectBulldozer/appsettings.json new file mode 100644 index 0000000..99ad4bf --- /dev/null +++ b/ProjectBulldozer/appsettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "logs/bulldozerlog-.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Bulldozer" + } + } +} \ No newline at end of file