diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs
index 0bdeb11..b290193 100644
--- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs
+++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs
@@ -1,4 +1,5 @@
using ProjectCatamaran.Drawnings;
+using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -32,7 +33,8 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
-private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
+
///
/// Конструктор
///
@@ -88,8 +90,15 @@ private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawningBoat? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawningBoat? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException e)
+ { }
+ catch (PositionOutOfCollectionException e)
+ { }
}
return bitmap;
}
diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs
index bddbc58..288b017 100644
--- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs
+++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs
@@ -1,4 +1,5 @@
using ProjectCatamaran.Drawnings;
+using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,14 +28,14 @@ public class BoatHarborService : AbstractCompany
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
- Pen pen = new(Color.Black, 4);
- for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
+ Pen pen = new(Color.Black, 2);
+ for (int i = 0; i < width + 1; i++)
{
- for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
+ for (int j = 0; j < height + 1; ++j)
{
- g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + 5, i * _placeSizeWidth + _placeSizeWidth - 90, j * _placeSizeHeight + 5);
+ g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight);
+ g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight);
}
- g.DrawLine(pen, i * _placeSizeWidth,0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight + 5);
}
}
@@ -48,23 +49,27 @@ public class BoatHarborService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- if (_collection.Get(i) != null)
+ try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
}
+ catch (ObjectNotFoundException) { }
+ catch (PositionOutOfCollectionException e) { }
+
if (curWidth < width - 1)
- curWidth++;
- else
- {
- curWidth = 0;
- curHeight--;
- }
- if (curHeight < 0)
- {
- return;
- }
- }
+ curWidth++;
+ else
+ {
+ curWidth = 0;
+ curHeight--;
+ }
+ if (curHeight < 0)
+ {
+ return;
+ }
+
+ }
}
}
diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs
index a53a145..7e700ea 100644
--- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs
+++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using ProjectCatamaran.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -31,39 +32,30 @@ public class ListGenericObjects : ICollectionGenericObjects
}
public T? Get(int position)
{
- if (position >= 0 && position < Count)
- {
- return _collection[position];
- }
- return null;
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ return _collection[position];
}
public int Insert(T obj)
{
- if (Count <= _maxCount)
- {
- _collection.Add(obj);
- return Count;
- }
- return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ _collection.Add(obj);
+ return Count;
+
}
+
public int Insert(T obj, int position)
{
- if (Count < _maxCount && position >= 0 && position < _maxCount)
- {
- _collection.Insert(position, obj);
- return position;
- }
- return -1;
+ if (Count == _maxCount) throw new CollectionOverflowException(Count);
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ _collection.Insert(position, obj);
+ return position;
}
public T Remove(int position)
{
- T temp = _collection[position];
- if (position >= 0 && position < _maxCount)
- {
- _collection.RemoveAt(position);
- return temp;
- }
- return null;
+ if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
+ T obj = _collection[position];
+ _collection.RemoveAt(position);
+ return obj;
}
public IEnumerable GetItems()
diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs
index 7ce31df..2666ad8 100644
--- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using ProjectCatamaran.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -53,67 +54,77 @@ namespace ProjectCatamaran.CollectiongGenericObjects;
}
public T? Get(int position)
{
- // проверка позиции
- if (position >= _collection.Length || position < 0)
- {
- return null;
- }
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
- // вставка в свободное место набора
- int index = 0;
- while (index < _collection.Length)
+ // вставка в свободное место набора
+ for (int i = 0; i < Count; i++)
{
- if (_collection[index] == null)
+ if (_collection[i] == null)
{
- _collection[index] = obj;
- return index;
+ _collection[i] = obj;
+ return i;
}
- index++;
}
- return -1;
+
+ throw new CollectionOverflowException(Count);
+
}
public int Insert(T obj, int position)
{
+ // проверка позиции
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
- if (position >= _collection.Length || position < 0)
- { return -1; }
-
- if (_collection[position] == null)
+ if (_collection[position] != null)
{
- _collection[position] = obj;
- return position;
- }
- int index;
- for (index = position + 1; index < _collection.Length; ++index)
- {
- if (_collection[index] == null)
+ bool pushed = false;
+
+ int index;
+ for (index = position + 1; index < _collection.Length; index++)
{
- _collection[position] = obj;
- return position;
+ if (_collection[index] == null)
+ {
+ position = index;
+ pushed = true;
+ break;
+ }
}
- }
- for (index = position - 1; index >= 0; --index)
- {
- if (_collection[index] == null)
+ if (!pushed)
{
- _collection[position] = obj;
- return position;
+
+ for (index = position - 1; index >= 0; index--)
+ {
+ if (_collection[index] == null)
+ {
+ position = index;
+ pushed = true;
+ break;
+ }
+ }
}
+ if (!pushed)
+ {
+ throw new CollectionOverflowException(Count);
+ }
+
}
- return -1;
+ _collection[position] = obj;
+ return position;
}
- public T Remove(int position)
+ public T? Remove(int position)
{
- if (position >= _collection.Length || position < 0)
- { return null; }
- T DrawningBoat = _collection[position];
+ // проверка позиции
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
+
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
+ T temp = _collection[position];
_collection[position] = null;
- return DrawningBoat;
+ return temp;
}
public IEnumerable GetItems()
diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs
index 38ac934..85a7fb3 100644
--- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs
+++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs
@@ -1,9 +1,11 @@
using ProjectCatamaran.Drawnings;
+using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectCatamaran.CollectiongGenericObjects;
@@ -93,12 +95,12 @@ public class StorageCollection
/// Сохранение информации по автомобилям в хранилище в файл
///
/// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
+
}
@@ -144,7 +146,6 @@ public class StorageCollection
}
}
- return true;
}
@@ -153,11 +154,11 @@ public class StorageCollection
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
@@ -166,7 +167,7 @@ public class StorageCollection
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
- return false;
+ throw new Exception("В файле нет данных");
_storages.Clear();
@@ -183,7 +184,7 @@ public class StorageCollection
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -191,17 +192,24 @@ public class StorageCollection
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
- if (elem?.CreateDrawningBoat() is T Truck)
+ if (elem?.CreateDrawningBoat() is T boat)
{
- if (collection.Insert(Truck) == -1)
- return false;
+ try
+ {
+ if (collection.Insert(boat) == -1)
+ {
+ throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new Exception("Коллекция переполнена", ex);
+ }
}
}
-
_storages.Add(record[0], collection);
}
}
- return true;
}
///
diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..b418cb6
--- /dev/null
+++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectCatamaran.Exceptions;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal class CollectionOverflowException : ApplicationException
+{
+ public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
+
+ public CollectionOverflowException() : base() { }
+
+ public CollectionOverflowException(string message) : base(message) { }
+
+ public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
+
+ protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
+
diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..6b5afca
--- /dev/null
+++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectCatamaran.Exceptions;
+
+///
+/// Класс, описывающий ошибку, что по указанной позиции нет элемента
+///
+[Serializable]
+internal class ObjectNotFoundException : ApplicationException
+{
+ public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
+
+ public ObjectNotFoundException() : base() { }
+
+ public ObjectNotFoundException(string message) : base(message) { }
+
+ public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
+ protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+}
+
diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..50378b9
--- /dev/null
+++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectCatamaran.Exceptions;
+
+///
+/// Класс, описывающий ошибку выхода за границы коллекции
+///
+[Serializable]
+internal class PositionOutOfCollectionException : ApplicationException
+{
+ public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
+
+ public PositionOutOfCollectionException() : base() { }
+
+ public PositionOutOfCollectionException(string message) : base(message) { }
+
+ public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
+ protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+
+}
\ No newline at end of file
diff --git a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs
index 0691440..e4da5eb 100644
--- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs
+++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs
@@ -1,5 +1,7 @@
-using ProjectCatamaran.CollectiongGenericObjects;
+using Microsoft.Extensions.Logging;
+using ProjectCatamaran.CollectiongGenericObjects;
using ProjectCatamaran.Drawnings;
+using ProjectCatamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -9,6 +11,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectCatamaran;
@@ -22,12 +25,19 @@ public partial class FormBoatCollection : Form
///
/// Компания
///
- private AbstractCompany? _company;
+ private AbstractCompany? _company = null;
- public FormBoatCollection()
+ ///
+ /// Конструктор
+ ///
+ private readonly ILogger _logger;
+
+ public FormBoatCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
+ _logger.LogInformation("Форма загрузилась");
}
///
@@ -60,19 +70,22 @@ public partial class FormBoatCollection : Form
///
private void SetBoat(DrawningBoat boat)
{
- if (_company == null || boat == null)
+ if (_company == null || boat == null)
+ {
+ return;
+ }
+ try
{
- return;
- }
-
- if (_company + boat != -1)
- {
- MessageBox.Show("объект добавлен");
+ var res = _company + boat;
+ MessageBox.Show("Объект добавлен");
+ _logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxBoat.Image = _company.Show();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("не удалось добавить объект");
+ MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@@ -96,14 +109,18 @@ public partial class FormBoatCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
+ try
{
+ var res = _company - pos;
MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxBoat.Image = _company.Show();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message, "Не удалось удалить объект",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
@@ -121,24 +138,32 @@ public partial class FormBoatCollection : Form
DrawningBoat? boat = null;
int counter = 100;
- while (boat == null)
+ try
{
- boat = _company.GetRandomObject();
- counter--;
- if (counter <= 0)
+ while (boat == null)
{
- break;
+ boat = _company.GetRandomObject();
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
}
+ if (boat == null)
+ {
+ return;
+ }
+ FormCatamaran form = new()
+ {
+ SetBoat = boat
+ };
+ form.ShowDialog();
}
- if (boat == null)
+ catch (Exception ex)
+
{
- return;
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
- FormCatamaran form = new()
- {
- SetBoat = boat
- };
- form.ShowDialog();
}
///
@@ -170,16 +195,25 @@ public partial class FormBoatCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
- CollectionType collectionType = CollectionType.None;
- if (radioButtonMassive.Checked)
+ try
{
- collectionType = CollectionType.Massive;
+ CollectionType collectionType = CollectionType.None;
+ if (radioButtonMassive.Checked)
+ {
+ collectionType = CollectionType.Massive;
+ }
+ else if (radioButtonList.Checked)
+ {
+ collectionType = CollectionType.List;
+ }
+ _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
- else if (radioButtonList.Checked)
+ catch (Exception ex)
{
- collectionType = CollectionType.List;
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
- _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
@@ -196,13 +230,20 @@ public partial class FormBoatCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
- if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ try
{
- return;
+ if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ {
+ return;
+ }
+ _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ RerfreshListBoxItems();
+ _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
- _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
- RerfreshListBoxItems();
-
}
///
@@ -261,13 +302,16 @@ public partial class FormBoatCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@@ -281,14 +325,18 @@ public partial class FormBoatCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
+ _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
+
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectCatamaran/ProjectCatamaran/Program.cs b/ProjectCatamaran/ProjectCatamaran/Program.cs
index 59feea7..46bb482 100644
--- a/ProjectCatamaran/ProjectCatamaran/Program.cs
+++ b/ProjectCatamaran/ProjectCatamaran/Program.cs
@@ -1,17 +1,45 @@
-namespace ProjectCatamaran
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+using Serilog;
+
+
+namespace ProjectCatamaran;
+
+internal static class Program
{
- internal static class Program
+ [STAThread]
+ static void Main()
{
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
+ // To customize application configuration such as set high DPI settings or default font,
+ // see https://aka.ms/applicationconfiguration.
+ ApplicationConfiguration.Initialize();
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
- // To customize application configuration such as set high DPI settings or default font,
- // see https://aka.ms/applicationconfiguration.
- ApplicationConfiguration.Initialize();
- Application.Run(new FormBoatCollection());
+ 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}serilogConfig.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/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj
index 244387d..8397199 100644
--- a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj
+++ b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj
@@ -8,6 +8,17 @@
enable
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +34,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/ProjectCatamaran/ProjectCatamaran/serilogConfig.json b/ProjectCatamaran/ProjectCatamaran/serilogConfig.json
new file mode 100644
index 0000000..63d86d9
--- /dev/null
+++ b/ProjectCatamaran/ProjectCatamaran/serilogConfig.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": "Catamaran"
+ }
+ }
+}
\ No newline at end of file