PIbd-22. Smirnov A.A. Lab work 07 #10

Closed
spacyboy wants to merge 2 commits from laba_7 into laba_6
14 changed files with 265 additions and 110 deletions
Showing only changes of commit e236ed7ebc - Show all commits

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": "RoadTrain"
}
}
}

View File

@ -105,17 +105,33 @@ namespace RoadTrain.DrawingObjects
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityRoadTrain.Step;
if (_startPosX - EntityRoadTrain.Step > 0)
{
_startPosX -= (int)EntityRoadTrain.Step;
}
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityRoadTrain.Step;
if (_startPosY - EntityRoadTrain.Step > 0)
{
_startPosY -= (int)EntityRoadTrain.Step;
}
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityRoadTrain.Step;
if (_startPosX + EntityRoadTrain.Step + _roadTrainWidth < _pictureWidth)
{
_startPosX += (int)EntityRoadTrain.Step;
}
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityRoadTrain.Step;
if (_startPosY + EntityRoadTrain.Step + _roadTrainHeight < _pictureHeight)
{
_startPosY += (int)EntityRoadTrain.Step;
}
break;
}
}

View File

@ -10,7 +10,7 @@ namespace RoadTrain.Entities
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
public double Step => (double)Speed * 100 / Weight;
public EntityRoadTrain(int speed, double weight, Color bodyColor)
{

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace RoadTrain
{
internal static class Program
@ -6,7 +14,28 @@ namespace RoadTrain
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new TrainCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<TrainCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<TrainCollection>().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.AddSerilog(logger);
});
}
}
}
}

View File

@ -1,5 +1,13 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RoadTrain.Entities;
using RoadTrain.DrawingObjects;
using RoadTrain.MovementStrategy;

View File

@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Exceptions" Version="8.4.0" />
<PackageReference Include="Serilog.Exceptions.EntityFrameworkCore" Version="8.4.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,20 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace RoadTrain.Exceptions
{
[Serializable]
internal class RoadTrainNotFoundException : ApplicationException
{
public RoadTrainNotFoundException(int i) : base($"Not found object on position {i}") { }
public RoadTrainNotFoundException() : base() { }
public RoadTrainNotFoundException(string message) : base(message) { }
public RoadTrainNotFoundException(string message, Exception exception) : base(message, exception) { }
protected RoadTrainNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.Exceptions;
namespace RoadTrain.Generics
{
@ -16,30 +17,28 @@ namespace RoadTrain.Generics
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T>(count);
_places = new List<T?>(_maxCount);
}
public bool Insert(T roadtrain)
public bool Insert(T train)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(roadtrain, 0);
return true;
return Insert(train, 0);
}
public bool Insert(T roadtrain, int position)
public bool Insert(T train, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, roadtrain);
if (position < 0 || position >= _maxCount)
throw new StorageOverflowException("Impossible to insert");
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(0, train);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
return false;
if (position >= Count || position < 0)
throw new RoadTrainNotFoundException("Invalid operation");
if (_places[position] == null)
throw new RoadTrainNotFoundException(position);
_places.RemoveAt(position);
return true;
}
@ -47,21 +46,18 @@ namespace RoadTrain.Generics
{
get
{
if (position < 0 || position >= Count)
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
if (position < 0 || position > _maxCount)
return;
}
_places.Insert(position, value);
return;
_places[position] = value;
}
}
public IEnumerable<T> GetTrains(int? maxTrains = null)
{
for (int i = 0; i < _places.Count; ++i)

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace RoadTrain.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"There is exceeded a limit of allowed number: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -10,6 +11,7 @@ using System.Windows.Forms;
using RoadTrain.DrawingObjects;
using RoadTrain.Generics;
using RoadTrain.MovementStrategy;
using RoadTrain.Exceptions;
namespace RoadTrain
@ -18,11 +20,13 @@ namespace RoadTrain
{
private readonly TrainsGenericStorage _storage;
private readonly ILogger _logger;
public TrainCollection()
public TrainCollection(ILogger<TrainCollection> logger)
{
InitializeComponent();
_storage = new TrainsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
@ -52,6 +56,7 @@ namespace RoadTrain
return;
}
_storage.AddSet(textBoxStorageName.Text);
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
ReloadObjects();
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
@ -65,16 +70,21 @@ namespace RoadTrain
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
listBoxStorages.Items.Remove(listBoxStorages.SelectedItem);
_logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -83,24 +93,46 @@ namespace RoadTrain
{
return;
}
var formTrainConfig = new TrainConfig();
TrainConfig formTrainConfig = new TrainConfig();
formTrainConfig.AddEvent(AddTrain);
formTrainConfig.Show();
Action<DrawingRoadTrain>? trainDelegate = new((m) =>
}
private void AddTrain(DrawingRoadTrain train)
{
if (listBoxStorages.SelectedIndex == -1)
{
bool isAddSuccessful = (obj + m);
if (isAddSuccessful)
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
train.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
try
{
bool isAddedSuccessfully = obj + train;
if (isAddedSuccessfully)
{
MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowTrains();
}
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
}
else
{
{
MessageBox.Show("Не удалось добавить объект");
}
});
formTrainConfig.AddEvent(trainDelegate);
_logger.LogInformation($"Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.ToString());
}
}
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -116,17 +148,35 @@ namespace RoadTrain
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrains();
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTrains();
_logger.LogInformation($"Объект удален из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора{listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (RoadTrainNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Нет объекта: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Нет ввода");
_logger.LogWarning("Нет ввода");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -145,15 +195,16 @@ namespace RoadTrain
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранено успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не выполнено");
}
}
}
@ -161,15 +212,17 @@ namespace RoadTrain
{
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);
ReloadObjects();
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загружено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не выполнена");
}
}
ReloadObjects();

View File

@ -1,5 +1,4 @@
using RoadTrain.DrawingObjects;
using RoadTrain.Entities;

using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -9,6 +8,10 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RoadTrain.DrawingObjects;
using RoadTrain.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace RoadTrain
{
@ -16,7 +19,7 @@ namespace RoadTrain
{
DrawingRoadTrain? _train = null;
private event Action<DrawingRoadTrain>? EventAddTrain;
public event Action<DrawingRoadTrain>? EventAddTrain;
public TrainConfig()
{
@ -69,6 +72,8 @@ namespace RoadTrain
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
ILogger<TrainCollection> logger = new NullLogger<TrainCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":

View File

@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.DrawingObjects;
namespace RoadTrain
{
internal class TrainDelegate
{
public delegate void Action(DrawingRoadTrain train);
}
}

View File

@ -89,4 +89,3 @@ namespace RoadTrain.Generics
}
}
}

View File

@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.DrawingObjects;
using RoadTrain.Exceptions;
using RoadTrain.MovementStrategy;
namespace RoadTrain.Generics
@ -52,7 +54,7 @@ namespace RoadTrain.Generics
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -70,68 +72,59 @@ namespace RoadTrain.Generics
}
if (data.Length == 0)
{
return false;
throw new ArgumentException("Invalid operation, there isn't any data");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"TrainStorage{Environment.NewLine}{data}");
}
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException($"Файл {filename} не найден");
}
using (StreamReader fs = File.OpenText(filename))
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
string line;
if (!(((line = sr.ReadLine()) != null) && line.StartsWith("TrainStorage")))
{
return false;
}
if (!str.StartsWith("TrainStorage"))
{
return false;
//если нет такой записи, то это не те данные
throw new ArgumentException("Неверный формат данных");
}
_trainStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{
if (strs == null)
{
return false;
}
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
string[] record = line.Split(
_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain> collection = new(_pictureWidth, _pictureHeight);
TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingRoadTrain? train = elem?.CreateDrawingTrain(_separatorForObject, _pictureWidth, _pictureHeight);
DrawingRoadTrain? train =
elem?.CreateDrawingTrain(
_separatorForObject,
_pictureWidth, _pictureHeight);
if (train != null)
{
if (!(collection + train))
{
return false;
throw new InvalidOperationException("Ошибка добавления в коллекцию");
}
}
}
_trainStorages.Add(record[0], collection);
}
return true;
}
return true;
}
}
}