PIbd-22. Fedorenko G.Y. Lab Work 7 #8

Closed
fedorenko wants to merge 2 commits from lab7 into lab6
9 changed files with 217 additions and 77 deletions

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

View File

@ -1,6 +1,5 @@
using Hydroplane.DrawningObjects;
using Hydroplane.Generics;
using Hydroplane.MovementStrategy;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -11,18 +10,26 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Hydroplane.Exceptions;
using Hydroplane.DrawningObjects;
using Hydroplane.Generics;
using Hydroplane.MovementStrategy;
namespace Hydroplane
{
public partial class FormHydroplaneCollection : Form
{
private readonly PlanesGenericStorage _storage;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormHydroplaneCollection()
public FormHydroplaneCollection(ILogger<FormHydroplaneCollection> logger)
{
InitializeComponent();
_storage = new PlanesGenericStorage(DrawPlane.Width, DrawPlane.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
@ -56,12 +63,12 @@ namespace Hydroplane
{
if (string.IsNullOrEmpty(SetTextBox.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Input not complete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(SetTextBox.Text);
ReloadObjects();
_logger.LogInformation($"Added set: {SetTextBox.Text}");
}
/// <summary>
/// Выбор набора
@ -85,12 +92,13 @@ namespace Hydroplane
{
return;
}
if (MessageBox.Show($"Удалить объект {CollectionListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
string name = CollectionListBox.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Delete Object {name}?", "Deleting",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(CollectionListBox.SelectedItem.ToString()
?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
}
}
@ -100,32 +108,43 @@ namespace Hydroplane
{
return;
}
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(plane =>
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
if (CollectionListBox.SelectedIndex != -1)
{
var obj = _storage[CollectionListBox.SelectedItem?.ToString() ?? string.Empty];
if (obj != null)
{
if (obj + plane)
{
MessageBox.Show("Объект добавлен");
DrawPlane.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
});
return;
}
FormPlaneConfig formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlane);
formPlaneConfig.Show();
}
private void AddPlane(DrawningPlane plane)
{
if (CollectionListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + plane;
MessageBox.Show("Объект добавлен");
DrawPlane.Image = obj.ShowPlanes();
_logger.LogInformation($"plane added in set {CollectionListBox.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"plane not added in set {CollectionListBox.SelectedItem.ToString()}");
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
@ -137,28 +156,40 @@ namespace Hydroplane
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Delete Object?", "Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = 0;
if (PlaneTextBox != null)
pos = Convert.ToInt32(PlaneTextBox.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
DrawPlane.Image = obj.ShowPlanes();
int pos = Convert.ToInt32(PlaneTextBox.Text);
if (obj - pos != null)
{
MessageBox.Show("Object deleted");
DrawPlane.Image = obj.ShowPlanes();
_logger.LogInformation($"plane deleted in set {CollectionListBox.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Object not deleted");
_logger.LogWarning($"plane not deleted in set {CollectionListBox.SelectedItem.ToString()}");
}
}
else
catch (PlaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"PlaneNotFound: {ex.Message} in set {CollectionListBox.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Not input");
_logger.LogWarning("Not input");
}
}
/// <summary>
@ -172,8 +203,7 @@ namespace Hydroplane
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
@ -185,15 +215,16 @@ namespace Hydroplane
{
if (SaveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(SaveFileDialog.FileName))
try
{
MessageBox.Show("Save Complete", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(SaveFileDialog.FileName);
MessageBox.Show("Saving complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"save in file {SaveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Save Not Complete", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Not saved: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Save to file {SaveFileDialog.FileName} not complete");
}
}
}
@ -201,19 +232,19 @@ namespace Hydroplane
{
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(OpenFileDialog.FileName))
try
{
MessageBox.Show("Load Complete", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.LoadData(OpenFileDialog.FileName);
MessageBox.Show("Load complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation($"load from file {OpenFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Load Not Complete", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Not loaded: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"load from file {OpenFileDialog.FileName} not complete");
}
}
}
}
}

View File

@ -9,6 +9,8 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using Hydroplane.DrawningObjects;
using Hydroplane.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Hydroplane
{
@ -105,6 +107,7 @@ namespace Hydroplane
/// <param name="e"></param>
private void panel_dragDrop(object sender, DragEventArgs e)
{
ILogger<FormHydroplaneCollection> logger = new NullLogger<FormHydroplaneCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelOriginalObject":

View File

@ -8,6 +8,16 @@
<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="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Hydroplane.Exceptions
{
[Serializable]
internal class PlaneNotFoundException : ApplicationException
{
public PlaneNotFoundException(int i) : base($"Not found object on position {i}") { }
public PlaneNotFoundException() : base() { }
public PlaneNotFoundException(string message) : base(message) { }
public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected PlaneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,5 +1,6 @@
using Hydroplane.DrawningObjects;
using Hydroplane.MovementStrategy;
using Hydroplane.Exceptions;
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
@ -47,7 +48,7 @@ namespace Hydroplane.Generics
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -65,20 +66,19 @@ namespace Hydroplane.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($"PlaneStorage{Environment.NewLine}{data}");
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("File not found");
}
using (StreamReader fs = File.OpenText(filename))
@ -86,11 +86,11 @@ namespace Hydroplane.Generics
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new ArgumentException("There isn't any data for load");
}
if (!str.StartsWith("PlaneStorage"))
{
return false;
throw new InvalidDataException("Invalid format of data");
}
_planeStorages.Clear();
@ -100,7 +100,7 @@ namespace Hydroplane.Generics
{
if (strs == null)
{
return false;
return;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@ -117,13 +117,23 @@ namespace Hydroplane.Generics
{
if (!(collection + plane))
{
return false;
try
{
_ = collection + plane;
}
catch (PlaneNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
}
_planeStorages.Add(record[0], collection);
}
return true;
}
}
}

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 Hydroplane
{
internal static class Program
@ -11,7 +17,28 @@ namespace Hydroplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormHydroplaneCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormHydroplaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormHydroplaneCollection>().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

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hydroplane.Exceptions;
namespace Hydroplane.Generics
{
@ -26,20 +27,20 @@ namespace Hydroplane.Generics
public bool Insert(T plane, int position)
{
if (position < 0 || position >= _maxCount)
return false;
throw new StorageOverflowException("Impossible to insert");
if (Count >= _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
_places.Insert(0, plane);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false;
if (position >= Count || position < 0)
throw new PlaneNotFoundException("Invalid operation");
if (_places[position] == null)
throw new PlaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}

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 Hydroplane.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) { }
}
}