diff --git a/ProjectBoat_base/.editorconfig b/ProjectBoat_base/.editorconfig new file mode 100644 index 0000000..bc38818 --- /dev/null +++ b/ProjectBoat_base/.editorconfig @@ -0,0 +1,121 @@ +[*.cs] + +# IDE0005: Директива using не нужна. +dotnet_diagnostic.IDE0005.severity = silent +csharp_style_throw_expression = true:suggestion + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_collection_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +[*.cs] +#### Стили именования #### + +# Правила именования + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Спецификации символов + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Стили именования + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +[*.vb] +#### Стили именования #### + +# Правила именования + +dotnet_naming_rule.interface_should_be_начинается_с_i.severity = suggestion +dotnet_naming_rule.interface_should_be_начинается_с_i.symbols = interface +dotnet_naming_rule.interface_should_be_начинается_с_i.style = начинается_с_i + +dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.severity = suggestion +dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.symbols = типы +dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы + +dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.severity = suggestion +dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.symbols = не_являющиеся_полем_члены +dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы + +# Спецификации символов + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.типы.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.типы.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected +dotnet_naming_symbols.типы.required_modifiers = + +dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_kinds = property, event, method +dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected +dotnet_naming_symbols.не_являющиеся_полем_члены.required_modifiers = + +# Стили именования + +dotnet_naming_style.начинается_с_i.required_prefix = I +dotnet_naming_style.начинается_с_i.required_suffix = +dotnet_naming_style.начинается_с_i.word_separator = +dotnet_naming_style.начинается_с_i.capitalization = pascal_case + +dotnet_naming_style.всечастиспрописнойбуквы.required_prefix = +dotnet_naming_style.всечастиспрописнойбуквы.required_suffix = +dotnet_naming_style.всечастиспрописнойбуквы.word_separator = +dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case + +dotnet_naming_style.всечастиспрописнойбуквы.required_prefix = +dotnet_naming_style.всечастиспрописнойбуквы.required_suffix = +dotnet_naming_style.всечастиспрописнойбуквы.word_separator = +dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case diff --git a/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningBoat.cs b/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningBoat.cs index 1932b36..43bd97f 100644 --- a/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningBoat.cs +++ b/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningBoat.cs @@ -74,8 +74,16 @@ namespace ProjectBoat_bae.DrawningObjects // Установка позиции public void SetPosition(int x, int y) { - _startPosX = Math.Min(x, _pictureWidth - _boatWidth); - _startPosY = Math.Min(y, _pictureHeight - _boatHeight); + if (x < 0 || x + _boatWidth > _pictureWidth) + { + x = Math.Max(0, _pictureWidth - _boatWidth + 60); + } + if (y < 0 || y + _boatHeight > _pictureHeight) + { + y = Math.Max(0, _pictureHeight - _boatHeight + 60); + } + _startPosX = x; + _startPosY = y; } // Прорисовка объекта @@ -88,17 +96,17 @@ namespace ProjectBoat_bae.DrawningObjects Pen pen = new(Color.Black); //корпус Brush br = new SolidBrush(EntityBoat.BodyColor); - g.FillRectangle(br, _startPosX + 20, _startPosY + 65, 80, 50); + g.FillRectangle(br, _startPosX + 50, _startPosY + 85, 80, 50); //мотор Brush brRed = new SolidBrush(EntityBoat.BodyColor); - g.FillEllipse(brRed, _startPosX + 7, _startPosY + 72, 35, 35); + g.FillEllipse(brRed, _startPosX + 30, _startPosY + 92, 35, 35); //стекла Brush brBlue = new SolidBrush(Color.LightBlue); - g.FillRectangle(brBlue, _startPosX + 95, _startPosY + 67, 5, 45); - g.FillRectangle(brBlue, _startPosX + 45, _startPosY + 67, 55, 2); - g.FillRectangle(brBlue, _startPosX + 45, _startPosY + 111, 55, 2); + g.FillRectangle(brBlue, _startPosX + 125, _startPosY + 87, 5, 45); + g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 87, 55, 2); + g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 131, 55, 2); } // Проверка, что объект может переместится по указанному направлению diff --git a/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningMotorBoat.cs b/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningMotorBoat.cs index 7ecc25d..3d276c3 100644 --- a/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningMotorBoat.cs +++ b/ProjectBoat_base/ProjectBoat_bae/DrawningObjects/DrawningMotorBoat.cs @@ -40,9 +40,9 @@ namespace ProjectBoat_bae.DrawningObjects if (Boat.Wing) { //вёсла - g.FillRectangle(additionalBrush, _startPosX + 35, _startPosY + 40, 5, 100); - g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY + 40, 12, 8); - g.FillRectangle(additionalBrush, _startPosX + 28, _startPosY + 135, 12, 8); + g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 60, 5, 100); + g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 60, 12, 8); + g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 155, 12, 8); } base.DrawTransport(g); @@ -50,7 +50,7 @@ namespace ProjectBoat_bae.DrawningObjects //кресла if (Boat.Body) { - g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 70, 25, 40); + g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 90, 25, 40); } } } diff --git a/ProjectBoat_base/ProjectBoat_bae/Entities/EntityBoat.cs b/ProjectBoat_base/ProjectBoat_bae/Entities/EntityBoat.cs index 5f63e22..d53ef6a 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Entities/EntityBoat.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Entities/EntityBoat.cs @@ -16,7 +16,7 @@ namespace ProjectBoat_bae.Entities public int Speed { get; private set; } public double Weight { get; private set; } public Color BodyColor { get; private set; } - public double Step => (double)Speed * 100 / Weight; + public double Step => (double)Speed * 200 / Weight; public EntityBoat(int speed, double weight, Color bodyColor) { diff --git a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.Designer.cs b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.Designer.cs index 6cf08f4..8f64a96 100644 --- a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.Designer.cs +++ b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.Designer.cs @@ -51,7 +51,7 @@ // pictureBoxCollection.Location = new Point(0, 0); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(929, 647); + pictureBoxCollection.Size = new Size(784, 647); pictureBoxCollection.TabIndex = 0; pictureBoxCollection.TabStop = false; // diff --git a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs index 7d17853..c418804 100644 --- a/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs +++ b/ProjectBoat_base/ProjectBoat_bae/FormBoatCollection.cs @@ -341,24 +341,37 @@ namespace ProjectBoat_bae // _logger.LogWarning($"load from file {openFileDialog.FileName} not complete"); // } //} + //if (openFileDialog.ShowDialog() == DialogResult.OK) + //{ + // try + // { + // _storage.LoadData(openFileDialog.FileName); + // MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + // _logger.LogWarning($"Файл {openFileDialog.FileName} успешно загружен"); + // foreach (var collection in _storage.Keys) + // { + // listBoxStorages.Items.Add(collection); + // } + // ReloadObjects(); + // } + // catch (Exception ex) + // { + // _logger.LogWarning("Не удалось загрузить"); + // MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + // } + //} if (openFileDialog.ShowDialog() == DialogResult.OK) { try { _storage.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogWarning($"Файл {openFileDialog.FileName} успешно загружен"); - foreach (var collection in _storage.Keys) - { - listBoxStorages.Items.Add(collection); - } + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); ReloadObjects(); } catch (Exception ex) { - _logger.LogWarning("Не удалось загрузить"); - MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); } } } diff --git a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs index 12def1a..6b11b6c 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericCollection.cs @@ -20,10 +20,10 @@ namespace ProjectBoat_bae.Generics /// /// Размер занимаемого объектом места (ширина) /// - private readonly int _placeSizeWidth = 150; + private readonly int _placeSizeWidth = 200; // Размер занимаемого объектом места (высота) - private readonly int _placeSizeHeight = 150; + private readonly int _placeSizeHeight = 200; // Набор объектов private readonly SetGeneric _collection; @@ -102,8 +102,7 @@ namespace ProjectBoat_bae.Generics T? t = _collection[i]; if (t != null) { - t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, - (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); + t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); if (t is Drawningboat) (t as Drawningboat).DrawTransport(g); else t.DrawTransport(g); } diff --git a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs index 9f66385..5e3b952 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Generics/BoatsGenericStorage.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using ProjectBoat_bae.DrawningObjects; using ProjectBoat_bae.MovementStrategy; using ProjectBoat_bae.Entities; +using ProjectBoat_bae.Exceptions; namespace ProjectBoat_bae.Generics { @@ -76,6 +77,7 @@ namespace ProjectBoat_bae.Generics //UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}"); //fs.Write(info, 0, info.Length); //return; + if (File.Exists(filename)) { File.Delete(filename); @@ -97,13 +99,12 @@ namespace ProjectBoat_bae.Generics } using FileStream fs = new(filename, FileMode.Create); byte[] info = new - UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}"); + UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}"); fs.Write(info, 0, info.Length); return; } - //public bool LoadData(string filename) public void LoadData(string filename) { //if (!File.Exists(filename)) @@ -154,57 +155,223 @@ namespace ProjectBoat_bae.Generics // } // return true; //} + //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("Неверный формат данных"); + //} + //_boatStorages.Clear(); + //foreach (string data in strs) + //{ + // string[] record = data.Split(_separatorForKeyValue, + // StringSplitOptions.RemoveEmptyEntries); + // if (record.Length != 2) + // { + // continue; + // } + // BoatsGenericCollection + // collection = new(_pictureWidth, _pictureHeight); + // string[] set = record[1].Split(_separatorRecords, + // StringSplitOptions.RemoveEmptyEntries); + // foreach (string elem in set) + // { + // Drawningboat? boat = + // elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + // if (boat != null) + // { + // if (!(collection + boat)) + // { + // throw new Exception("Ошибка добавления в коллекцию"); + // } + // } + // } + // _boatStorages.Add(record[0], collection); + //} + + //using (StreamReader fs = File.OpenText(filename)) + //{ + + // string str = fs.ReadLine(); + + // if (str == null || str.Length == 0) + // { + // throw new IOException("Нет данных для загрузки"); + // } + + // if (!str.StartsWith("LocomotiveStorage")) + // { + // //если нет такой записи, то это не те данные + // throw new FileFormatException("Неверный формат данных"); + // } + + // _boatStorages.Clear(); + // string strs = ""; + + + // while ((strs = fs.ReadLine()) != null) + // { + + // if (strs == null) + // { + // throw new FileNotFoundException("Нет данных для загрузки"); + // } + + // string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + // if (record.Length != 2) + // { + // continue; + // } + // BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); + // string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + // foreach (string elem in set) + // { + // Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + // if (boat != null) + // { + // if (!(collection + boat)) // for my realization it's -1, for eegov's realization it's boolean + // { + // throw new Exception("Ошибка добавления "); + // } + // } + // } + // _boatStorages.Add(record[0], collection); + // } + // return; + //} + + //if (!File.Exists(filename)) + //{ + // throw new FileNotFoundException("Файл не найден"); + //} + + //using (StreamReader fs = File.OpenText(filename)) + //{ + + // string str = fs.ReadLine(); + + // if (str == null || str.Length == 0) + // { + // throw new IOException("Нет данных для загрузки"); + // } + + // if (!str.StartsWith("LocomotiveStorage")) + // { + // //если нет такой записи, то это не те данные + // throw new FileFormatException("Неверный формат данных"); + // } + + // _boatStorages.Clear(); + // string strs = ""; + + + // while ((strs = fs.ReadLine()) != null) + // { + + // if (strs == null) + // { + // throw new FileNotFoundException("Нет данных для загрузки"); + // } + + // string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + // if (record.Length != 2) + // { + // continue; + // } + // BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); + // string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + // foreach (string elem in set) + // { + // Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + // if (boat != null) + // { + // if ((collection + boat) == -1) // for my realization it's -1, for eegov's realization it's boolean + // { + // throw new Exception("Ошибка добавления "); + // } + // } + // } + // _boatStorages.Add(record[0], collection); + // } + // return; + //} if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + + using (StreamReader fs = File.OpenText(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str = fs.ReadLine(); + if (str == null || str.Length == 0) { - bufferTextFromFile += temp.GetString(b); + throw new ArgumentException("Нет объекта для добавления"); } - } - 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("Неверный формат данных"); - } - _boatStorages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + if (!str.StartsWith("BoatsStorage")) { - continue; + throw new InvalidDataException("Неверный формат данных"); } - BoatsGenericCollection - collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, - StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + + _boatStorages.Clear(); + string strs = ""; + + while ((strs = fs.ReadLine()) != null) { - Drawningboat? boat = - elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); - if (boat != null) + if (strs == null) { - if (!(collection + boat)) + return; + } + + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + BoatsGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight); + if (boat != null) { - throw new Exception("Ошибка добавления в коллекцию"); + if (!(collection + boat)) + { + try + { + _ = collection + boat; + } + catch (BoatNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } + } } } + _boatStorages.Add(record[0], collection); } - _boatStorages.Add(record[0], collection); } } } diff --git a/ProjectBoat_base/ProjectBoat_bae/Program.cs b/ProjectBoat_base/ProjectBoat_bae/Program.cs index b6a67c5..d556d7f 100644 --- a/ProjectBoat_base/ProjectBoat_bae/Program.cs +++ b/ProjectBoat_base/ProjectBoat_bae/Program.cs @@ -1,6 +1,9 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.VisualBasic.ApplicationServices; using NLog.Extensions.Logging; +using Serilog; namespace ProjectBoat_bae { @@ -25,11 +28,18 @@ namespace ProjectBoat_bae private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton() - .AddLogging(option => + 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.AddNLog("nlog.config"); + option.AddSerilog(logger); }); } } diff --git a/ProjectBoat_base/ProjectBoat_bae/ProjectBoat_bae.csproj b/ProjectBoat_base/ProjectBoat_bae/ProjectBoat_bae.csproj index f7377a1..19587fe 100644 --- a/ProjectBoat_base/ProjectBoat_bae/ProjectBoat_bae.csproj +++ b/ProjectBoat_base/ProjectBoat_bae/ProjectBoat_bae.csproj @@ -9,8 +9,29 @@ + + + + + + + + + + + + + + + + + + + + Always + diff --git a/ProjectBoat_base/ProjectBoat_bae/appSettings.json b/ProjectBoat_base/ProjectBoat_bae/appSettings.json new file mode 100644 index 0000000..d4831c9 --- /dev/null +++ b/ProjectBoat_base/ProjectBoat_bae/appSettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Boats" + } + } +} \ No newline at end of file diff --git a/ProjectBoat_base/ProjectBoat_base.sln b/ProjectBoat_base/ProjectBoat_base.sln index a6dcf8d..326656e 100644 --- a/ProjectBoat_base/ProjectBoat_base.sln +++ b/ProjectBoat_base/ProjectBoat_base.sln @@ -3,7 +3,12 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.34031.279 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9D03BD00-51B0-4389-84FD-8FF17153F0BE}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution