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

This commit is contained in:
Stranni15k 2022-12-22 23:10:46 +04:00
parent e3b123b725
commit b54ee7b861
10 changed files with 242 additions and 84 deletions

View File

@ -9,8 +9,20 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Include="ElectricLocomotive.csproj" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<None Include="ElectricLocomotive.csproj.user" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.0" />
<PackageReference Include="Serilog" Version="2.12.1-dev-01594" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.1-dev-10301" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.5.0-dev-00359" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00947" />
<PackageReference Include="Serilog.Sinks.InfluxDBv2" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -59,9 +59,9 @@
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right))); | System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Location = new System.Drawing.Point(0, 27);
this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(808, 721); this.pictureBox1.Size = new System.Drawing.Size(808, 694);
this.pictureBox1.TabIndex = 10; this.pictureBox1.TabIndex = 10;
this.pictureBox1.TabStop = false; this.pictureBox1.TabStop = false;
// //
@ -265,6 +265,7 @@
this.openFileDialog.Filter = "txt file | *.txt"; this.openFileDialog.Filter = "txt file | *.txt";
// //
// saveFileDialog // saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt"; this.saveFileDialog.Filter = "txt file | *.txt";
// //
// FormMapWithSetLocomotive // FormMapWithSetLocomotive

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -20,9 +21,11 @@ namespace ElectricLocomotive
{"Карта с кустами",new BushesMap() } {"Карта с кустами",new BushesMap() }
}; };
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotive() private readonly ILogger _logger;
public FormMapWithSetLocomotive(ILogger<FormMapWithSetLocomotive> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height); _mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapDict) foreach (var elem in _mapDict)
@ -81,23 +84,36 @@ namespace ElectricLocomotive
FormLocmotiveConfig.AddEvent(new(AddLocomotive)); FormLocmotiveConfig.AddEvent(new(AddLocomotive));
FormLocmotiveConfig.Show(); FormLocmotiveConfig.Show();
} }
public void AddLocomotive(DrawningLocomotive aircraft) public void AddLocomotive(DrawningLocomotive locomotive)
{ {
if (ListBoxMaps.SelectedIndex == -1) try
{ {
return; if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Locomotive}", locomotive);
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
} }
catch (StorageOverflowException ex)
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(aircraft) != -1)
{ {
MessageBox.Show("Object is added"); _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
else catch (ArgumentException ex)
{ {
MessageBox.Show("Unable to add object"); _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Locomotive}", ex.Message, locomotive);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e) private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{ {
@ -114,14 +130,30 @@ namespace ElectricLocomotive
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{ {
MessageBox.Show("Объект удален"); var deletedLocomotive = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); if (deletedLocomotive != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Locomotive}", deletedLocomotive);
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (LocomotiveNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); _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) private void ButtonShowStorage_Click(object sender, EventArgs e)
@ -168,18 +200,23 @@ namespace ElectricLocomotive
} }
private void ButtonAddMap_Click(object sender, EventArgs e) private void ButtonAddMap_Click(object sender, EventArgs e)
{ {
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);
return; return;
} }
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text,
_mapDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
@ -202,14 +239,15 @@ namespace ElectricLocomotive
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -219,14 +257,17 @@ namespace ElectricLocomotive
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps(); 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 ElectricLocomotive
{
[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

@ -118,7 +118,7 @@
foreach (var HardLocomotive in _setLocomotive.GetLocomotive()) foreach (var HardLocomotive in _setLocomotive.GetLocomotive())
{ {
(float Left, float Top, float Right, float Bottom) = HardLocomotive.GetCurrentPosition(); (float Left, float Top, float Right, float Bottom) = HardLocomotive.GetCurrentPosition();
HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 70), _pictureWidth, _pictureHeight); HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 60), _pictureWidth, _pictureHeight);
HardLocomotive.DrawningObject(g); HardLocomotive.DrawningObject(g);
if (ColumnIndex == xNumOfPlaces - 1) if (ColumnIndex == xNumOfPlaces - 1)
{ {

View File

@ -43,66 +43,71 @@ namespace ElectricLocomotive
return null; return null;
} }
} }
private static void WriteToFile(string text, FileStream stream) private static void WriteToFile(string text, FileStream stream)
{ {
byte[] info = new UTF8Encoding(true).GetBytes(text); byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length); stream.Write(info, 0, info.Length);
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(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) 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)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
string str = ""; string bufferTextFromFile = "";
using (StreamReader fs = new StreamReader(filename)) using (FileStream fs = new(filename, FileMode.Open))
{ {
str = fs.ReadLine(); byte[] b = new byte[fs.Length];
if (!str.Contains("MapsCollection")) UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{ {
//если нет такой записи, то это не те данные bufferTextFromFile += temp.GetString(b);
return false;
}
_mapStorages.Clear();
while ((str = fs.ReadLine()) != null)
{
var elem = str.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;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotivGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
} }
return true; var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (!strs[0].Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
for (int i = 1; i < strs.Length; ++i)
{
var elem = strs[i].Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "FieldMap":
map = new FieldMap();
break;
case "BushesMap":
map = new BushesMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotivGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
} }
} }
} }

View File

@ -1,3 +1,11 @@
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 ElectricLocomotive namespace ElectricLocomotive
{ {
internal static class Program internal static class Program
@ -11,7 +19,40 @@ namespace ElectricLocomotive
// 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 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);
});
} }
} }
} }

View File

@ -19,33 +19,33 @@ namespace ElectricLocomotive
} }
public int Insert(T locomotive) public int Insert(T locomotive)
{ {
if (_places.Count > _maxCount)
{
return -1;
}
// вставка в начало набора
return Insert(locomotive, 0); return Insert(locomotive, 0);
} }
public int Insert(T locomotive, int position) public int Insert(T locomotive, int position)
{ {
if (position >= _maxCount || position < 0) return -1; if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > _maxCount) return -1;
_places.Insert(position, locomotive); _places.Insert(position, locomotive);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
// проверка позиции if (position >= Count || position < 0)
if (position >= _maxCount || position < 0) return null; {
// удаление объекта из массива, присовив элементу массива значение null throw new LocomotiveNotFoundException(position);
T temp = _places[position]; }
T ship = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);
return temp; return ship;
} }
public T this[int position] public T this[int position]
{ {
get get
{ {
if (position >= _places.Count || position < 0) if (position >= Count || position < 0)
{ {
return null; return null;
} }
@ -53,7 +53,7 @@ namespace ElectricLocomotive
} }
set set
{ {
if (position >= _places.Count || position < 0) if (position >= Count || position < 0)
{ {
return; return;
} }

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 ElectricLocomotive
{
[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": "log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotive"
}
}
}