PIbd-21_KozyrevSS_SewingDre.../SewingDresses/SewingDressesView/ComponentForm.cs

83 lines
2.9 KiB
C#

using SewingDressesContracts.BindingModels;
using SewingDressesContracts.BusinessLogicsContracts;
using SewingDressesContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace SewingDressesView
{
public partial class ComponentForm : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public ComponentForm(ILogger<ComponentForm> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ComponentForm_Load(object sender, EventArgs e)
{
if (!_id.HasValue)
{
return;
}
try
{
_logger.LogInformation("Get component");
var view = _logic.ReadElement(new ComponentSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.ComponentName;
textBoxCost.Text = view.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Get component error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Save component");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополительная информация в логах");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Save component error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}