diff --git a/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs b/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs deleted file mode 100644 index 3def398..0000000 --- a/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DoubleDeckerBus.DrawningObjects; - -namespace DoubleDeckerBus -{ - public delegate void BusDelegate(DrawningBus bus); -} diff --git a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj index b57c89e..257fc89 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj +++ b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj @@ -8,4 +8,22 @@ enable + + + + + + + + + + + + + + + Always + + + \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs new file mode 100644 index 0000000..0fd89c2 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.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 DoubleDeckerBus.Exceptions +{ + [Serializable] + internal class BusNotFoundException : ApplicationException + { + public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public BusNotFoundException() : base() { } + public BusNotFoundException(string message) : base(message) { } + public BusNotFoundException(string message, Exception exception) : base(message, exception){ } + protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..908e54c --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace DoubleDeckerBus.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 contex) : base(info, contex) { } + } +} diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs index 654573f..f4e4064 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs @@ -44,6 +44,7 @@ saveToolStripMenuItem = new ToolStripMenuItem(); openFileDialog = new OpenFileDialog(); saveFileDialog = new SaveFileDialog(); + SaveToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); panel.SuspendLayout(); menuStrip.SuspendLayout(); @@ -165,7 +166,7 @@ // // ToolStripMenuItem // - ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, saveToolStripMenuItem }); + ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, SaveToolStripMenuItem }); ToolStripMenuItem.Name = "ToolStripMenuItem"; ToolStripMenuItem.Size = new Size(48, 20); ToolStripMenuItem.Text = "файл"; @@ -193,6 +194,13 @@ // saveFileDialog.Filter = "«txt file | *.txt»"; // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.Size = new Size(180, 22); + SaveToolStripMenuItem.Text = "Сохранить"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // // FormBusCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -228,6 +236,6 @@ private MenuStrip menuStrip; private ToolStripMenuItem ToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem; - private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; } } \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs index 3e2c112..78b69e5 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs @@ -12,16 +12,23 @@ using DoubleDeckerBus.Generics; using DoubleDeckerBus.MovementStrategy; using static System.Windows.Forms.DataFormats; using System.Windows.Forms; +using DoubleDeckerBus.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; + + namespace DoubleDeckerBus { public partial class FormBusCollection : Form { private readonly BusesGenericStorage _storage; - public FormBusCollection() + private readonly ILogger _logger; + public FormBusCollection(ILogger logger) { InitializeComponent(); _storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -32,13 +39,12 @@ namespace DoubleDeckerBus { listBoxStorages.Items.Add(_storage.Keys[i]); } - if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) { listBoxStorages.SelectedIndex = 0; } - - else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count) + else if (listBoxStorages.Items.Count > 0 && index > -1 && + index < listBoxStorages.Items.Count) { listBoxStorages.SelectedIndex = index; } @@ -49,7 +55,6 @@ namespace DoubleDeckerBus } private void ButtonAddObject_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -57,6 +62,7 @@ namespace DoubleDeckerBus } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } private void ButtonDelObject_Click(object sender, EventArgs e) { @@ -64,15 +70,87 @@ namespace DoubleDeckerBus { return; } - if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, - MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void buttonAddBus_Click(object sender, EventArgs e) + { + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? + string.Empty]; + if (obj == null) + { + return; + } + FormBusConfig form = new(); + form.Show(); + Action? busDelegate = new((m) => + { + try + { + bool q = obj + m; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + pictureBoxCollection.Image = obj.ShowBuses(); + } + catch (StorageOverflowException ex) + { + _logger.LogWarning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); + } + }); + form.AddEvent(busDelegate); + } + private void buttonRemoveBus_Click(object sender, EventArgs e) + { + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + return; + } + if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + try + { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBuses(); + _logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Объект не удален"); + _logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + } + } + catch (BusNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Объект не добавлен"); _logger.LogWarning("Not input"); + } + } + private void ButtonRefreshCollection_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) { @@ -83,96 +161,47 @@ namespace DoubleDeckerBus { return; } - FormBusConfig form = new FormBusConfig(); - form.AddEvent(AddBus); - form.Show(); - } - private void AddBus(DrawningBus boat) - { - boat._pictureWidth = pictureBoxCollection.Width; - boat._pictureHeight = pictureBoxCollection.Height; if (listBoxStorages.SelectedIndex == -1) return; - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) return; - if (obj + boat) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowBuses(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - private void buttonRemoveBus_Click(object sender, EventArgs e) - { - if (listBoxStorages.SelectedIndex == -1) - { - return; - } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; - if (obj == null) - { - return; - } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBuses(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } - } - private void ButtonRefreshCollection_Click(object sender, EventArgs e) - { - if (listBoxStorages.SelectedIndex == -1) - { - return; - } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; - if (obj == null) - { - return; - } pictureBoxCollection.Image = obj.ShowBuses(); } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { 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($"Файл {saveFileDialog.FileName} успешно сохранен"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить"); + MessageBox.Show($"Не сохранилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } + } private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } + ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx index 7ea2349..11110dc 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx @@ -120,6 +120,9 @@ 11, 17 + + 11, 17 + 132, 17 diff --git a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs index d3b1c0d..263df3a 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs @@ -23,86 +23,6 @@ namespace DoubleDeckerBus.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } - public bool SaveData(string filename) - { - if (File.Exists(filename)) - { - File.Delete(filename); - } - StringBuilder data = new(); - foreach (KeyValuePair> record in _busStorages) - { - StringBuilder records = new(); - foreach (DrawningBus? elem in record.Value.GetTheBuses) - { - records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); - } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); - } - - if (data.Length == 0) - { - return false; - } - string toWrite = $"BusStorage{Environment.NewLine}{data}"; - var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - - using (StreamWriter sw = new(filename)) - { - foreach (var str in strs) - { - sw.WriteLine(str); - } - } - return true; - } - public bool LoadData(string filename) - { - if (!File.Exists(filename)) - { - return false; - } - using (StreamReader sr = new(filename)) - { - string str = sr.ReadLine(); - var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].StartsWith("BusStorage")) - { - return false; - } - _busStorages.Clear(); - do - { - string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) - { - str = sr.ReadLine(); - continue; - } - BusesGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - DrawningBus? bus = elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight); - if (bus != null) - { - if (!(collection + bus)) - { - return false; - } - } - } - _busStorages.Add(record[0], collection); - - str = sr.ReadLine(); - } while (str != null); - } - return true; - } public void AddSet(string name) { _busStorages.Add(name, new BusesGenericCollection(_pictureWidth, _pictureHeight)); @@ -116,8 +36,7 @@ namespace DoubleDeckerBus.Generics _busStorages.Remove(name); } - public BusesGenericCollection? - this[string ind] + public BusesGenericCollection?this[string ind] { get { @@ -129,5 +48,90 @@ namespace DoubleDeckerBus.Generics return null; } } + public void SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _busStorages) + { + StringBuilder records = new(); + foreach (DrawningBus? elem in record.Value.GetTheBuses) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + throw new Exception("Невалидная операция, нет данных для сохранения"); + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return; + } + public void LoadData(string filename) + { + if (!File.Exists(filename)) + { + throw new Exception("Файл не найден"); + } + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new Exception("Нет данных для загрузки"); + } + if (!strs[0].StartsWith("BusStorage")) + { + //если нет такой записи, то это не те данные + throw new Exception("Неверный формат данных"); + } + _busStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + BusesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningBus? car = + elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight); + if (car != null) + { + if (!(collection + car)) + { + throw new Exception("Ошибка добавления в коллекцию"); + } + } + } + _busStorages.Add(record[0], collection); + } + } } } + + + diff --git a/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs b/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs index 22e9633..b0df051 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using DoubleDeckerBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -21,30 +22,23 @@ namespace DoubleDeckerBus.Generics public bool Insert(T bus) { if (_places.Count == _maxCount) - { - return false; - } - + throw new StorageOverflowException(_maxCount); Insert(bus, 0); return true; } public bool Insert(T bus, 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, bus); return true; } public bool Remove(int position) { - if (position < 0 || position >= Count) - { - return false; - } - + if (!(position >= 0 && position < Count)) + throw new BusNotFoundException(position); _places.RemoveAt(position); return true; } @@ -52,20 +46,14 @@ namespace DoubleDeckerBus.Generics { get { - if (position < 0 || position >= _maxCount) - { + if (!(position >= 0 && position < Count)) return null; - } - return _places[position]; } set { if (!(position >= 0 && position < Count && _places.Count < _maxCount)) - { return; - } - _places.Insert(position, value); return; } diff --git a/DoubleDeckerBus/DoubleDeckerBus/Program.cs b/DoubleDeckerBus/DoubleDeckerBus/Program.cs index 08776e0..a4f778c 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Program.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Program.cs @@ -1,4 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; using System.Drawing; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; namespace DoubleDeckerBus { @@ -7,8 +12,33 @@ namespace DoubleDeckerBus [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 FormBusCollection()); + 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: $"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/DoubleDeckerBus/DoubleDeckerBus/appSettings.json b/DoubleDeckerBus/DoubleDeckerBus/appSettings.json new file mode 100644 index 0000000..5d067ed --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/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": "DoubleDeckerBus" + } + } +}