ISEbd-12_Osyagina_A.A._Simple_LabWork07 #7

Closed
Osyagina_Anna wants to merge 5 commits from LabWork07 into LabWork06
27 changed files with 334 additions and 153 deletions

View File

@ -1,4 +1,6 @@
using ProjectMotorboat.Drownings;

using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
@ -15,9 +17,8 @@ public abstract class AbstractCompany
protected ICollectionGenericObjects<DrawningBoat>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBoat> collection)
{
_pictureWidth = picWidth;
@ -48,8 +49,15 @@ public abstract class AbstractCompany
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;

View File

@ -1,5 +1,4 @@

namespace ProjectMotorboat.CollectionGenericObjects;
namespace ProjectMotorboat.CollectionGenericObjects;
public enum CollectionType
{

View File

@ -1,5 +1,5 @@

using ProjectMotorboat.Drownings;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
@ -36,12 +36,13 @@ public class HarborService : 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 * boatWidth + 20, boatHeight * _placeSizeHeight + 20);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (boatWidth < width - 1)
boatWidth++;
else

View File

@ -1,5 +1,4 @@

namespace ProjectMotorboat.CollectionGenericObjects;
namespace ProjectMotorboat.CollectionGenericObjects;
public interface ICollectionGenericObjects<T>

View File

@ -1,13 +1,16 @@
namespace ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
private readonly List<T?> _collection;
public CollectionType GetCollectionType => CollectionType.List;
private int _maxCount;
public int Count => _collection.Count;
@ -32,33 +35,33 @@ where T : class
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
public T Remove(int position)
{
if (position < 0 || position > Count) return null;
T? pos = _collection[position];
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return pos;
return obj;
}
public IEnumerable<T> GetItems()

View File

@ -1,4 +1,8 @@
namespace ProjectMotorboat.CollectionGenericObjects;

using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
@ -38,15 +42,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length)
{
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)
{
for (int i = 0; i < _collection.Length; i++)
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
@ -55,51 +57,55 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= _collection.Length) { return position; }
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
if (_collection[position] != null)
{
_collection[position] = obj;
return position;
}
else
{
for (int i = position + 1; i < _collection.Length; i++)
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
position = index;
pushed = true;
break;
}
}
for (int i = position - 1; i >= 0; i--)
if (!pushed)
{
if (_collection[i] == null)
for (int index = position - 1; index >= 0; index--)
{
_collection[i] = obj;
return i;
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
}
return -1;
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
_collection[position] = obj;
return position;
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Length)
{
return null;
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position];
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return obj;
return temp;
}
public IEnumerable<T> GetItems()
@ -113,3 +119,4 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>

View File

@ -1,6 +1,6 @@
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
using System.Text;
namespace ProjectMotorboat.CollectionGenericObjects;
public class StorageCollection<T>
@ -19,7 +19,6 @@ public class StorageCollection<T>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
@ -38,7 +37,7 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
@ -48,7 +47,7 @@ public class StorageCollection<T>
{
get
{
// TODO Продумать логику получения объекта
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
}
@ -60,19 +59,21 @@ public class StorageCollection<T>
private readonly string _separatorItems = ";";
public bool SaveData(string filename)
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
@ -80,7 +81,6 @@ public class StorageCollection<T>
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
@ -106,31 +106,35 @@ public class StorageCollection<T>
}
return true;
}
public bool LoadData(string filename)
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
@ -140,23 +144,30 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T boat)
if (elem?.CreateDrawningBoat() is T track)
{
if (collection.Insert(boat) == -1)
try
{
return false;
if (collection.Insert(track) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)

View File

@ -1,4 +1,5 @@

namespace ProjectMotorboat.Drownings
{
public enum DirectionType

View File

@ -1,4 +1,6 @@
using ProjectMotorboat.Entities;
namespace ProjectMotorboat.Drownings;
public class DrawningBoat
@ -108,14 +110,14 @@ public class DrawningBoat
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityBoat.Step > 0)
{
_startPosX -= (int)EntityBoat.Step;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityBoat.Step > 0)
{
@ -129,7 +131,7 @@ public class DrawningBoat
_startPosX += (int)EntityBoat.Step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + EntityBoat.Step + _drawningBoatHeight < _pictureHeight)
{
@ -149,7 +151,7 @@ public class DrawningBoat
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(EntityBoat.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX.Value + 5, _startPosY.Value + 0),
@ -161,6 +163,7 @@ public class DrawningBoat
g.FillPolygon(mainBrush, hull);
g.DrawPolygon(pen, hull);
Brush blockBrush = new SolidBrush(EntityBoat.BodyColor);
g.FillRectangle(blockBrush, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40);
g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40);

View File

@ -26,15 +26,12 @@ public class DrawningMotorboat : DrawningBoat
Brush additionalBrush = new SolidBrush(motorboat.AdditionalColor);
base.DrawTransport(g);
if (motorboat.Glass)
{
Brush glassBrush = new SolidBrush(Color.LightBlue);
g.FillEllipse(glassBrush, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40);
g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40);
}
if (motorboat.Motor)
{
Brush engineBrush = new

View File

@ -1,9 +1,15 @@
using ProjectMotorboat.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Drownings;
public static class ExtentionDrawningBoat
{
private static readonly string _separatorForObject = ":";
public static DrawningBoat? CreateDrawningBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);

View File

@ -0,0 +1,18 @@

using System.Runtime.Serialization;
namespace ProjectMotorboat.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) { }
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.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) { }
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.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) { }
}

View File

@ -1,48 +1,62 @@
using ProjectMotorboat.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Drownings;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectMotorboat;
public partial class FormBoatCollection : Form
{
private readonly StorageCollection<DrawningBoat> _storageCollection;
private AbstractCompany? _company = null;
public FormBoatCollection()
private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfig form = new();
form.Show();
form.AddEvent(SetBoat);
form.Show();
}
private void SetBoat(DrawningBoat? boat)
private void SetBoat(DrawningBoat boat)
{
if (_company == null || boat == null)
{
return;
}
if (_company + boat != -1)
try
{
var res = _company + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
@ -50,23 +64,30 @@ public partial class FormBoatCollection : Form
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
@ -85,12 +106,10 @@ public partial class FormBoatCollection : Form
break;
}
}
if (boat == null)
{
return;
}
FormMotorboat form = new()
{
SetBoat = boat
@ -98,6 +117,7 @@ public partial class FormBoatCollection : Form
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
@ -110,7 +130,8 @@ public partial class FormBoatCollection : Form
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
@ -126,22 +147,36 @@ public partial class FormBoatCollection : Form
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null)
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -166,7 +201,8 @@ public partial class FormBoatCollection : Form
return;
}
ICollectionGenericObjects<DrawningBoat>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningBoat>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -177,24 +213,27 @@ public partial class FormBoatCollection : Form
{
case "Хранилище":
_company = new HarborService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
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);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@ -203,15 +242,19 @@ public partial class FormBoatCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}
}

View File

@ -127,6 +127,6 @@
<value>310, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
<value>51</value>
</metadata>
</root>

View File

@ -1,6 +1,5 @@
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Entities;
namespace ProjectMotorboat
{
public partial class FormBoatConfig : Form
@ -72,11 +71,9 @@ namespace ProjectMotorboat
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectMotorboat.MovementStrategy;

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectMotorboat.MovementStrategy;

View File

@ -1,4 +1,5 @@

namespace ProjectMotorboat.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{

View File

@ -1,9 +1,5 @@
using ProjectMotorboat.Drownings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.MovementStrategy;

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.MovementStrategy;
namespace ProjectMotorboat.MovementStrategy;
public enum MovementDirection
{

View File

@ -1,5 +1,4 @@

namespace ProjectMotorboat.MovementStrategy;
namespace ProjectMotorboat.MovementStrategy;
public class ObjectParameters
{

View File

@ -1,4 +1,5 @@
namespace ProjectMotorboat.MovementStrategy;

namespace ProjectMotorboat.MovementStrategy;
public enum StrategyStatus
{

View File

@ -1,15 +1,43 @@
namespace ProjectMotorboat
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectMotorboat;
internal static class Program
{
internal static class Program
[STAThread]
static void Main()
{
[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<FormBoatCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().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);
});
}
}

View File

@ -8,4 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -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": "Motorboat"
}
}
}