Лабораторная работа 7

This commit is contained in:
Efi 2023-04-20 23:31:51 +04:00
parent 214931344f
commit d7880d438d
9 changed files with 297 additions and 114 deletions

View File

@ -8,37 +8,40 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
namespace Monorail
{
public partial class FormMapWithSetLocomotive : Form
{
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
private MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap> _mapLocomotiveCollectionGeneric;
private readonly Dictionary<string, AbstractMap> _mapDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Карта с грязью", new FieldMap() },
{ "Карта с кустами", new BushesMap() }
{"Простая карта", new SimpleMap() },
{"Карта с грязью", new FieldMap() },
{"Карта с кустами",new BushesMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotive()
private readonly ILogger _logger;
public FormMapWithSetLocomotive(ILogger<FormMapWithSetLocomotive> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
foreach (var elem in _mapDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
foreach (var list in _mapsCollection.Keys)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
listBoxMaps.Items.Add(list);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
@ -50,68 +53,69 @@ namespace Monorail
listBoxMaps.SelectedIndex = index;
}
}
private void ButtonAddMap_Click(object sender, EventArgs e)
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender,
EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
case "Простая карта":
map = new SimpleMap();
break;
case "Карта с грязью":
map = new FieldMap();
break;
case "Карта с кустами":
map = new BushesMap();
break;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
if (map != null)
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
_mapLocomotiveCollectionGeneric = new MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>(
pictureBoxLocomotive.Width, pictureBoxLocomotive.Height, map);
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
else
{
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_mapLocomotiveCollectionGeneric = null;
}
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
var FormLocmotiveConfig = new FormLocomotiveConfig();
FormLocmotiveConfig.AddEvent(new(AddLocomotive));
FormLocmotiveConfig.Show();
}
public void AddLocomotive(DrawingLocomotive locomotive)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectLocomotive(locomotive) != -1)
{
MessageBox.Show("Object is added");
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Locomotive}", locomotive);
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Unable to add object");
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Locomotive}", ex.Message, locomotive);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
@ -127,17 +131,32 @@ namespace Monorail
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
var deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedLocomotive != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Locomotive}", deletedLocomotive);
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (LocomotiveNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
@ -146,7 +165,6 @@ namespace Monorail
}
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
@ -155,13 +173,13 @@ namespace Monorail
}
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
@ -181,20 +199,56 @@ namespace Monorail
}
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 ||
string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -204,17 +258,19 @@ namespace Monorail
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Данные загружены успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_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} | {ex.Message}.");
}
}
}
}
}

View File

@ -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 Monorail
{
[Serializable]
internal class LocomotiveNotFoundException : ApplicationException
{
public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции{i}") { }
public LocomotiveNotFoundException() : base() { }
public LocomotiveNotFoundException(string message) : base(message) { }
public LocomotiveNotFoundException(string message, Exception exception) : base(message, exception) { }
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
namespace Monorail
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetLocomotiveGeneric<IDrawingObject, AbstractMap>> _mapStorages;
@ -43,67 +44,72 @@ namespace Monorail
return null;
}
}
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new StreamWriter(filename))
using (FileStream fs = new(filename, FileMode.Create))
{
fs.Write($"MapsCollection{Environment.NewLine}");
WriteToFile($"MapsCollection{Environment.NewLine}", fs);
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs);
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
string str = "";
using (StreamReader fs = new StreamReader(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
str = fs.ReadLine();
if (!str.Contains("MapsCollection"))
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[0].Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while ((str = fs.ReadLine()) != null)
for (int i = 1; i < strs.Length; ++i)
{
var elem = str.Split(separatorDict);
var elem = strs[i].Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "BushesMap":
map = new BushesMap();
break;
case "FieldMap":
map = new FieldMap();
break;
case "BushesMap":
map = new BushesMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotiveGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

@ -8,6 +8,23 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.3" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.InfluxDBv2" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -1,17 +1,62 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using System.Diagnostics;
using System.Reflection;
namespace Monorail
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[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 FormMapWithSetLocomotive());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetLocomotive>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormMapWithSetLocomotive>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
logger.Information("Ñîçäàíèå Ëîãà");
});
}
}
}

View File

@ -25,26 +25,26 @@ namespace Monorail
}
public int Insert(T locomotive, int position)
{
if (position <= _places.Count && _places.Count < _maxCount && position >= 0)
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > _maxCount) return -1;
_places.Insert(position, locomotive);
return position;
}
else
return -1;
}
public T Remove(int position)
{
if (position < _places.Count && position >= 0)
if (position >= Count || position < 0)
{
var locomotive = _places[position];
throw new LocomotiveNotFoundException(position);
}
T ship = _places[position];
_places.RemoveAt(position);
return locomotive;
}
else
return null;
return ship;
}
public T this[int position]
{
get

View File

@ -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 Monorail
{
[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 context) : base(info, context) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._Monorail_Base\\Monorail\\log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotive"
}
}
}

1
Monorail20230420 Normal file
View File

@ -0,0 +1 @@
[23:29:36.152]INFO: Создание Лога