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

This commit is contained in:
Sem730 2022-12-03 16:35:18 +03:00
parent 5d9ccfb1db
commit c424860090
10 changed files with 165 additions and 36 deletions

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ProjectLocomotive namespace ProjectLocomotive
{ {
internal class EntityElectricLocomotive : EntityLocomotive public class EntityElectricLocomotive : EntityLocomotive
{ {
/// <summary> /// <summary>
/// Дополнительный цвет /// Дополнительный цвет

View File

@ -69,11 +69,11 @@
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddLocomotive); this.groupBoxTools.Controls.Add(this.buttonAddLocomotive);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(580, 33); this.groupBoxTools.Location = new System.Drawing.Point(577, 33);
this.groupBoxTools.Margin = new System.Windows.Forms.Padding(4); this.groupBoxTools.Margin = new System.Windows.Forms.Padding(4);
this.groupBoxTools.Name = "groupBoxTools"; this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Padding = new System.Windows.Forms.Padding(4); this.groupBoxTools.Padding = new System.Windows.Forms.Padding(4);
this.groupBoxTools.Size = new System.Drawing.Size(220, 535); this.groupBoxTools.Size = new System.Drawing.Size(220, 510);
this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false; this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты"; this.groupBoxTools.Text = "Инструменты";
@ -248,7 +248,7 @@
this.pictureBox.Location = new System.Drawing.Point(0, 33); this.pictureBox.Location = new System.Drawing.Point(0, 33);
this.pictureBox.Margin = new System.Windows.Forms.Padding(4); this.pictureBox.Margin = new System.Windows.Forms.Padding(4);
this.pictureBox.Name = "pictureBox"; this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(580, 535); this.pictureBox.Size = new System.Drawing.Size(577, 510);
this.pictureBox.TabIndex = 1; this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false; this.pictureBox.TabStop = false;
// //
@ -259,7 +259,7 @@
this.fileToolStripMenuItem}); this.fileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip"; this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(800, 33); this.menuStrip.Size = new System.Drawing.Size(797, 33);
this.menuStrip.TabIndex = 2; this.menuStrip.TabIndex = 2;
// //
// fileToolStripMenuItem // fileToolStripMenuItem
@ -297,7 +297,7 @@
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 568); this.ClientSize = new System.Drawing.Size(797, 543);
this.Controls.Add(this.pictureBox); this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools); this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip); this.Controls.Add(this.menuStrip);

View File

@ -1,4 +1,5 @@
using Locomotive; using Locomotive;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -23,10 +24,14 @@ namespace ProjectLocomotive
}; };
/// Объект от коллекции карт /// Объект от коллекции карт
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotives() /// Логер
/// </summary>
private readonly ILogger _logger;
public FormMapWithSetLocomotives(ILogger<FormMapWithSetLocomotives> logger)
{ {
InitializeComponent(); InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
_logger = logger;
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
{ {
@ -63,27 +68,27 @@ namespace ProjectLocomotive
{ {
if (listBoxMaps.SelectedIndex == -1) if (listBoxMaps.SelectedIndex == -1)
{ {
return; MessageBox.Show("Перед добавлением объекта необходимо создать карту");
} }
try try
{ {
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(locomotive) != -1) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(locomotive) != -1)
{ {
MessageBox.Show("Object added"); MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@locomotive}", locomotive);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Failed to add object"); MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект {@locomotive}", locomotive);
} }
} }
catch(StorageOverflowException ex) catch(StorageOverflowException ex)
{ {
MessageBox.Show($"Storage overflow error: {ex.Message}"); MessageBox.Show("Не удалось добавить объект");
} _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
catch (Exception ex) MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
{
MessageBox.Show($"Unknown error: {ex.Message}");
} }
} }
/// Удаление объекта /// Удаление объекта
@ -104,23 +109,23 @@ namespace ProjectLocomotive
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try try
{ {
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) var deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedLocomotive != null)
{ {
MessageBox.Show("Object removed"); MessageBox.Show("Объект удалён");
_logger.LogInformation("Из текущей карты удалён объект {@locomotive}", deletedLocomotive);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Failed to remove object"); _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (LocomotiveNotFoundException ex) catch (LocomotiveNotFoundException ex)
{ {
MessageBox.Show($"Delete error: {ex.Message}"); _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
} MessageBox.Show($"Ошибка удаления: {ex.Message}");
catch (Exception ex)
{
MessageBox.Show($"Unknown error: {ex.Message}");
} }
} }
/// Вывод набора /// Вывод набора
@ -180,6 +185,7 @@ namespace ProjectLocomotive
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
} }
} }
@ -187,6 +193,7 @@ namespace ProjectLocomotive
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
} }
/// Добавление карты /// Добавление карты
private void buttonAddMap_Click(object sender, EventArgs e) private void buttonAddMap_Click(object sender, EventArgs e)
@ -194,15 +201,18 @@ namespace ProjectLocomotive
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return; return;
} }
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
} }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
@ -211,11 +221,13 @@ namespace ProjectLocomotive
try try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName); _mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Saving success", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Saving error: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
} }
} }
} }
@ -226,13 +238,14 @@ namespace ProjectLocomotive
try try
{ {
_mapsCollection.LoadData(loadFileDialog.FileName); _mapsCollection.LoadData(loadFileDialog.FileName);
MessageBox.Show("Loaded successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Открытие прошло успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", loadFileDialog.FileName);
ReloadMaps(); ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Loading failed + {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", loadFileDialog.FileName, ex.Message);
} }
} }
} }

View File

@ -16,6 +16,5 @@ namespace ProjectLocomotive
base(message, exception) base(message, exception)
{ } { }
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
} }
} }

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectLocomotive namespace ProjectLocomotive
{ {
internal static class Program internal static class Program
@ -11,7 +17,28 @@ namespace ProjectLocomotive
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetLocomotives()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetLocomotives>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetLocomotives>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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.1.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +47,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -15,14 +15,13 @@ namespace ProjectLocomotive
{ {
/// Список хранимых объектов /// Список хранимых объектов
private readonly List<T> _places; private readonly List<T> _places;
/// Количество объектов в списке /// Количество объектов в списке
public int Count => _places.Count; public int Count => _places.Count;
private readonly int _maxCount; private readonly int _maxCount = 15;
/// Конструктор /// Конструктор
public SetLocomotivesGeneric(int count) public SetLocomotivesGeneric(int count)
{ {
_maxCount = count; _maxCount = count = 15;
_places = new List<T>(); _places = new List<T>();
} }
/// Добавление объекта в набор /// Добавление объекта в набор
@ -41,7 +40,6 @@ namespace ProjectLocomotive
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
public T Remove(int position) public T Remove(int position)
{ {
//if (position >= _maxCount || position < 0) return null;
if (_places[position] is null) throw new LocomotiveNotFoundException(position); if (_places[position] is null) throw new LocomotiveNotFoundException(position);
T result = _places[position]; T result = _places[position];
_places[position] = null; _places[position] = null;

View File

@ -16,6 +16,5 @@ namespace ProjectLocomotive
base(message, exception) base(message, exception)
{ } { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
} }
} }

View File

@ -0,0 +1,48 @@
{
"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" ],
"Destructure": [
{
"Name": "ByTransforming",
"Args": {
"returnType": "ProjectLocomotive.EntityLocomotive",
"transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }"
}
},
{
"Name": "ByTransforming",
"Args": {
"returnType": "ProjectLocomotive.EntityElectricLocomotive",
"transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.ElectroLines, r.ElectroBattery, r.Speed, r.Weight }"
}
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 15 }
}
],
"Properties": {
"Application": "ProjectLocomotive"
}
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-progect.org/schemas/NLog.xsd"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instanse"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="locomotivelog-${shortdate}.log"/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile"/>
</rules>
</nlog>
</configuration>