убрали асинхронность + для студентов ключ не guid, а перечисление, доавбили условие в GenericControlEntityList, LaunchControl

This commit is contained in:
kotcheshir73 2022-03-15 22:02:13 +04:00
parent 2acaecbf8d
commit d79be9a8dc
15 changed files with 661 additions and 677 deletions

View File

@ -8,18 +8,17 @@ using ModuleTools.Models;
using ModuleTools.ViewModels; using ModuleTools.ViewModels;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace DatabaseCore namespace DatabaseCore
{ {
public abstract class AbstractGenerticEntityService<G, S, T, L, E> : IGenerticEntityService<G, S> public abstract class AbstractGenerticEntityService<G, S, T, L, E> : IGenerticEntityService<G, S>
where G : GetBindingModel where G : GetBindingModel
where S : SetBindingModel where S : SetBindingModel
where T : BaseEntity where T : BaseEntity
where L : ListViewModel<E>, new() where L : ListViewModel<E>, new()
where E : ElementViewModel where E : ElementViewModel
{ {
public async Task<OperationResultModel> CreateAsync(S model) public OperationResultModel Create(S model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -33,8 +32,8 @@ namespace DatabaseCore
if (exsistEntity == null) if (exsistEntity == null)
{ {
var entity = Mapper.MapToClass<S, T>(model, true); var entity = Mapper.MapToClass<S, T>(model, true);
await context.Set<T>().AddAsync(entity); context.Set<T>().Add(entity);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true));
} }
else else
@ -43,7 +42,7 @@ namespace DatabaseCore
{ {
exsistEntity = Mapper.MapToClass(model, exsistEntity, true); exsistEntity = Mapper.MapToClass(model, exsistEntity, true);
exsistEntity.IsDeleted = false; exsistEntity.IsDeleted = false;
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(exsistEntity, true)); return OperationResultModel.Success(Mapper.MapToClass<T, E>(exsistEntity, true));
} }
else else
@ -53,13 +52,13 @@ namespace DatabaseCore
} }
} }
public async Task<OperationResultModel> DeleteAsync(G model) public OperationResultModel Delete(G model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
using var transaction = context.Database.BeginTransaction(); using var transaction = context.Database.BeginTransaction();
try try
{ {
var entity = await context.Set<T>().FirstOrDefaultAsync(x => x.Id == model.Id); var entity = context.Set<T>().FirstOrDefault(x => x.Id == model.Id);
if (entity == null) if (entity == null)
{ {
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
@ -78,22 +77,22 @@ namespace DatabaseCore
entity.IsDeleted = true; entity.IsDeleted = true;
entity.DateDelete = DateTime.Now; entity.DateDelete = DateTime.Now;
await context.SaveChangesAsync(); context.SaveChanges();
AdditionalDeleting(context, entity, model); AdditionalDeleting(context, entity, model);
await transaction.CommitAsync(); transaction.Commit();
} }
catch (Exception) catch (Exception)
{ {
await transaction.RollbackAsync(); transaction.Rollback();
throw; throw;
} }
return OperationResultModel.Success(true); return OperationResultModel.Success(true);
} }
public async Task<OperationResultModel> RestoreAsync(G model) public OperationResultModel Restore(G model)
{ {
if (model.Id.HasValue || AdditionalCheckForSingleGet(model)) if (model.Id.HasValue || AdditionalCheckForSingleGet(model))
{ {
@ -110,14 +109,14 @@ namespace DatabaseCore
} }
entity.IsDeleted = false; entity.IsDeleted = false;
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true));
} }
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
} }
public async Task<OperationResultModel> ReadAsync(G model) public OperationResultModel Read(G model)
{ {
int countPages = 0; int countPages = 0;
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -146,27 +145,23 @@ namespace DatabaseCore
query = IncludingWhenReading(query); query = IncludingWhenReading(query);
return await Task.Run(() => if (model.PageNumber.HasValue && model.PageSize.HasValue)
{ {
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
var result = new L
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<T, E>(x, model.HaveRight)).ToList()
};
if (model.PageNumber.HasValue && model.PageSize.HasValue) return OperationResultModel.Success(result);
{
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
query = query
.Skip(model.PageSize.Value * model.PageNumber.Value)
.Take(model.PageSize.Value);
}
var result = new L
{
MaxCount = countPages,
List = query.Select(x => Mapper.MapToClass<T, E>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result);
});
} }
public async Task<OperationResultModel> UpdateAsync(S model) public OperationResultModel Update(S model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -193,7 +188,7 @@ namespace DatabaseCore
} }
entity = Mapper.MapToClass(model, entity, true); entity = Mapper.MapToClass(model, entity, true);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<T, E>(entity, true));
} }

View File

@ -18,396 +18,396 @@ using System.Xml.Linq;
namespace DesktopTools.Controls namespace DesktopTools.Controls
{ {
public partial class GenericControlEntityElement<G, S, L, E, BL> : MainControlViewEntityElement, IControlViewEntityElement public partial class GenericControlEntityElement<G, S, L, E, BL> : MainControlViewEntityElement, IControlViewEntityElement
where G : GetBindingModel, new() where G : GetBindingModel, new()
where S : SetBindingModel, new() where S : SetBindingModel, new()
where L : ListViewModel<E> where L : ListViewModel<E>
where E : ElementViewModel where E : ElementViewModel
where BL : GenericBusinessLogic<G, S, L, E> where BL : GenericBusinessLogic<G, S, L, E>
{ {
/// <summary> /// <summary>
/// Объект бизнес-логики для получения данных /// Объект бизнес-логики для получения данных
/// </summary> /// </summary>
protected readonly BL _businessLogic; protected readonly BL _businessLogic;
/// <summary> /// <summary>
/// Методы для реализации в generic-контроле /// Методы для реализации в generic-контроле
/// </summary> /// </summary>
protected IGenericControlEntityElement _genericControlViewEntityElement; protected IGenericControlEntityElement _genericControlViewEntityElement;
/// <summary> /// <summary>
/// Признак налиичия изменений /// Признак налиичия изменений
/// </summary> /// </summary>
private bool _haveChages = false; private bool _haveChages = false;
/// <summary> /// <summary>
/// Ширина контрола по умолчанию /// Ширина контрола по умолчанию
/// </summary> /// </summary>
private readonly int _defaultControlWidth = 350; private readonly int _defaultControlWidth = 350;
protected E _element = null; protected E _element = null;
/// <summary> /// <summary>
/// Событие, вызываемое при закрытии контрола /// Событие, вызываемое при закрытии контрола
/// </summary> /// </summary>
private event Action<Guid> CloseElementEvent; private event Action<Guid> CloseElementEvent;
/// <summary> /// <summary>
/// События установки одинаковой ширины для заголовков контролов /// События установки одинаковой ширины для заголовков контролов
/// </summary> /// </summary>
private event Action<int> SetTitleWidth; private event Action<int> SetTitleWidth;
/// <summary> /// <summary>
/// Событие установки значения /// Событие установки значения
/// </summary> /// </summary>
private event Action<object> SetValues; private event Action<object> SetValues;
/// <summary> /// <summary>
/// Событие сброса значения в исходное состояние /// Событие сброса значения в исходное состояние
/// </summary> /// </summary>
private event Action DropValues; private event Action DropValues;
/// <summary> /// <summary>
/// Событие проверки заполненности контрола /// Событие проверки заполненности контрола
/// </summary> /// </summary>
private event Func<bool> CheckValues; private event Func<bool> CheckValues;
/// <summary> /// <summary>
/// Событие получения значения из контрола /// Событие получения значения из контрола
/// </summary> /// </summary>
private event Action<object> GetValues; private event Action<object> GetValues;
private E Element private E Element
{ {
get { return _element; } get { return _element; }
set set
{ {
try try
{ {
_element = value; _element = value;
if (_element != null) if (_element != null)
{ {
SetValues?.Invoke(_element); SetValues?.Invoke(_element);
if (tabControl.Visible) if (tabControl.Visible)
{ {
foreach (TabPage page in tabControl.TabPages) foreach (TabPage page in tabControl.TabPages)
{ {
if (page.Name == tabPageMain.Name) if (page.Name == tabPageMain.Name)
{ {
continue; continue;
} }
if (page.Controls[0] is IControlChildEntity cntrl) if (page.Controls[0] is IControlChildEntity cntrl)
{ {
cntrl.ParentId = _element.Id; cntrl.ParentId = _element.Id;
cntrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.Child }); cntrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.Child });
} }
} }
} }
} }
_haveChages = false; _haveChages = false;
} }
catch (Exception ex) catch (Exception ex)
{ {
DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при установки значений"); DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при установки значений");
} }
} }
} }
public GenericControlEntityElement() public GenericControlEntityElement()
{ {
InitializeComponent(); InitializeComponent();
InitEvents(); InitEvents();
_businessLogic = DependencyManager.Instance.Resolve<BL>(); _businessLogic = DependencyManager.Instance.Resolve<BL>();
_controlViewEntityElement = this; _controlViewEntityElement = this;
} }
public async void OpenControl(ControlOpenModel model) public void OpenControl(ControlOpenModel model)
{ {
if (model.CloseElement != null) if (model.CloseElement != null)
{ {
CloseElementEvent += model.CloseElement; CloseElementEvent += model.CloseElement;
} }
if (panelContainer.Controls.Count == 0) if (panelContainer.Controls.Count == 0)
{ {
try try
{ {
Configurate(GetConfig()); Configurate(GetConfig());
} }
catch (Exception ex) catch (Exception ex)
{ {
DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации"); DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации");
} }
} }
if (model.ElementId.HasValue) if (model.ElementId.HasValue)
{ {
Element = await _businessLogic.GetElementAsync(new G { Id = model.ElementId }); Element = _businessLogic.GetElement(new G { Id = model.ElementId });
if (Element == null) if (Element == null)
{ {
DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении элемента"); DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении элемента");
} }
} }
Dock = DockStyle.Fill; Dock = DockStyle.Fill;
} }
public IControl GetInstanceControl() => _genericControlViewEntityElement?.GetInstanceGenericControl(); public IControl GetInstanceControl() => _genericControlViewEntityElement?.GetInstanceGenericControl();
public string SaveControlToXml() => new XElement("Control", public string SaveControlToXml() => new XElement("Control",
new XAttribute("Type", GetType().FullName), new XAttribute("Type", GetType().FullName),
new XAttribute("ControlId", ControlId), new XAttribute("ControlId", ControlId),
new XAttribute("Title", Title)).ToString(); new XAttribute("Title", Title)).ToString();
public void LoadControlFromXml(string xml) public void LoadControlFromXml(string xml)
{ {
var control = XElement.Parse(xml).Element("Control"); var control = XElement.Parse(xml).Element("Control");
ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); ControlId = new Guid(control.Attribute("ControlId").Value.ToString());
Title = control.Attribute("Title").Value.ToString(); Title = control.Attribute("Title").Value.ToString();
} }
private void InitEvents() private void InitEvents()
{ {
toolStripButtonSave.Click += async (object sender, EventArgs e) => { await SaveAsync(); }; toolStripButtonSave.Click += (object sender, EventArgs e) => { Save(); };
toolStripButtonReload.Click += (object sender, EventArgs e) => toolStripButtonReload.Click += (object sender, EventArgs e) =>
{ {
if (DialogHelper.MessageQuestion("Отменить все внесенные изменения?") == DialogResult.Yes) if (DialogHelper.MessageQuestion("Отменить все внесенные изменения?") == DialogResult.Yes)
{ {
try try
{ {
DropValues?.Invoke(); DropValues?.Invoke();
} }
catch (Exception ex) catch (Exception ex)
{ {
DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при сбросе значений"); DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при сбросе значений");
} }
} }
}; };
toolStripButtonClose.Click += async (object sender, EventArgs e) => toolStripButtonClose.Click += (object sender, EventArgs e) =>
{ {
if (_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == DialogResult.Yes) if (_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == DialogResult.Yes)
{ {
if (!(await SaveAsync())) if (!Save())
{ {
return; return;
} }
} }
CloseElementEvent?.Invoke(ControlId); CloseElementEvent?.Invoke(ControlId);
Dispose(); Dispose();
}; };
} }
private void Configurate(ControlViewEntityElementConfiguration config) private void Configurate(ControlViewEntityElementConfiguration config)
{ {
// Загрузка подпунктов в контекстное меню и в пункт меню "Действие" // Загрузка подпунктов в контекстное меню и в пункт меню "Действие"
if (config.ControlOnMoveElem != null) if (config.ControlOnMoveElem != null)
{ {
foreach (var elem in config.ControlOnMoveElem) foreach (var elem in config.ControlOnMoveElem)
{ {
ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key }; ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key };
item.Click += elem.Value.Event; item.Click += elem.Value.Event;
toolStripSplitButtonActions.DropDownItems.Add(item); toolStripSplitButtonActions.DropDownItems.Add(item);
ToolStripMenuItem itemContext = new() { Text = elem.Value.Title, Name = elem.Key }; ToolStripMenuItem itemContext = new() { Text = elem.Value.Title, Name = elem.Key };
itemContext.Click += elem.Value.Event; itemContext.Click += elem.Value.Event;
contextMenuStripElement.Items.Add(itemContext); contextMenuStripElement.Items.Add(itemContext);
} }
} }
// либо скрытие пункта, если не предусмотренно подпунктов // либо скрытие пункта, если не предусмотренно подпунктов
else else
{ {
toolStripSplitButtonActions.Visible = false; toolStripSplitButtonActions.Visible = false;
toolStripSeparator1.Visible = false; toolStripSeparator1.Visible = false;
} }
var attributeClass = typeof(E).GetCustomAttribute<ViewModelControlElementClassAttribute>(); var attributeClass = typeof(E).GetCustomAttribute<ViewModelControlElementClassAttribute>();
if (attributeClass == null) if (attributeClass == null)
{ {
return; return;
} }
tabControl.Visible = attributeClass.HaveDependenceEntities; tabControl.Visible = attributeClass.HaveDependenceEntities;
panelContainer.Visible = !attributeClass.HaveDependenceEntities; panelContainer.Visible = !attributeClass.HaveDependenceEntities;
Width = attributeClass.Width != 0 ? attributeClass.Width : _defaultControlWidth; Width = attributeClass.Width != 0 ? attributeClass.Width : _defaultControlWidth;
int positionY = 5; int positionY = 5;
int positionX = 5; int positionX = 5;
int interval = 15; int interval = 15;
int titleWidth = 0; int titleWidth = 0;
foreach (var property in typeof(E).GetProperties()) foreach (var property in typeof(E).GetProperties())
{ {
var attribute = property.GetCustomAttribute<ViewModelControlElementPropertyAttribute>(); var attribute = property.GetCustomAttribute<ViewModelControlElementPropertyAttribute>();
if (attribute != null) if (attribute != null)
{ {
AbstractBaseControl control = null; AbstractBaseControl control = null;
switch (attribute.ControlType) switch (attribute.ControlType)
{ {
case ControlType.ControlString: case ControlType.ControlString:
control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength); control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength);
break; break;
case ControlType.ControlText: case ControlType.ControlText:
control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height); control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height);
break; break;
case ControlType.ControlInt: case ControlType.ControlInt:
control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue); control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue);
break; break;
case ControlType.ControlDecimal: case ControlType.ControlDecimal:
control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue,
attribute.MaxValue, attribute.DecimalPlaces); attribute.MaxValue, attribute.DecimalPlaces);
break; break;
case ControlType.ControlBool: case ControlType.ControlBool:
control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly); control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly);
break; break;
case ControlType.ControlDateTime: case ControlType.ControlDateTime:
control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate, control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate,
attribute.MaxDate, attribute.CustomDateFormat); attribute.MaxDate, attribute.CustomDateFormat);
break; break;
case ControlType.ControlImage: case ControlType.ControlImage:
control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height); control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height);
break; break;
case ControlType.ControlEnum: case ControlType.ControlEnum:
control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType); control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType);
break; break;
case ControlType.ControlGuid: case ControlType.ControlGuid:
if (attribute.ControlTypeObject.IsNotEmpty() && Type.GetType(attribute.ControlTypeObject) != null) if (attribute.ControlTypeObject.IsNotEmpty() && Type.GetType(attribute.ControlTypeObject) != null)
{ {
control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly, control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly,
DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as IControlEntitySelectable, DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as IControlEntitySelectable,
property.Name == ParentPropertyName ? ParentId : null); property.Name == ParentPropertyName ? ParentId : null);
} }
break; break;
} }
if (control == null) if (control == null)
{ {
continue; continue;
} }
var widthTitle = control.SetTitle(attribute.DisplayName); var widthTitle = control.SetTitle(attribute.DisplayName);
if (widthTitle > titleWidth) if (widthTitle > titleWidth)
{ {
titleWidth = widthTitle; titleWidth = widthTitle;
} }
control.OnValueChangeEvent += () => { _haveChages = true; }; control.OnValueChangeEvent += () => { _haveChages = true; };
SetValues += control.SetValue; SetValues += control.SetValue;
DropValues += control.DropValue; DropValues += control.DropValue;
CheckValues += control.CheckValue; CheckValues += control.CheckValue;
SetTitleWidth += control.SetTitleWidth; SetTitleWidth += control.SetTitleWidth;
GetValues += control.GetValue; GetValues += control.GetValue;
control.Location = new System.Drawing.Point(positionX, positionY); control.Location = new System.Drawing.Point(positionX, positionY);
control.Width = Width - positionX * 2 - (tabControl.Visible ? 10 : 0); control.Width = Width - positionX * 2 - (tabControl.Visible ? 10 : 0);
control.Anchor = AnchorStyles.Top | AnchorStyles.Left; control.Anchor = AnchorStyles.Top | AnchorStyles.Left;
if (panelContainer.Visible) if (panelContainer.Visible)
{ {
control.Anchor |= AnchorStyles.Right; control.Anchor |= AnchorStyles.Right;
} }
positionY += control.Height + interval; positionY += control.Height + interval;
if (panelContainer.Visible) if (panelContainer.Visible)
{ {
panelContainer.Controls.Add(control); panelContainer.Controls.Add(control);
} }
if (tabControl.Visible) if (tabControl.Visible)
{ {
tabPageMain.Controls.Add(control); tabPageMain.Controls.Add(control);
} }
} }
} }
SetTitleWidth(titleWidth); SetTitleWidth(titleWidth);
Height = attributeClass.Height != 0 ? attributeClass.Height : positionY; Height = attributeClass.Height != 0 ? attributeClass.Height : positionY;
if (attributeClass.HaveDependenceEntities) if (attributeClass.HaveDependenceEntities)
{ {
var attrDependences = typeof(E).GetCustomAttributes<ViewModelControlElementDependenceEntityAttribute>(); var attrDependences = typeof(E).GetCustomAttributes<ViewModelControlElementDependenceEntityAttribute>();
if (attrDependences != null) if (attrDependences != null)
{ {
foreach (var attr in attrDependences) foreach (var attr in attrDependences)
{ {
if (DependencyManager.Instance.Resolve(Type.GetType(attr.ControlTypeObject)) is IControlChildEntity control) if (DependencyManager.Instance.Resolve(Type.GetType(attr.ControlTypeObject)) is IControlChildEntity control)
{ {
var cntrl = control.GetInstance() as IControlChildEntity; var cntrl = control.GetInstance() as IControlChildEntity;
cntrl.ParentPropertyName = attr.ParentPropertyName; cntrl.ParentPropertyName = attr.ParentPropertyName;
//cntrl.Open(null); //cntrl.Open(null);
var tabPage = new TabPage var tabPage = new TabPage
{ {
Location = new System.Drawing.Point(4, 24), Location = new System.Drawing.Point(4, 24),
Name = "tabPage", Name = "tabPage",
Padding = new Padding(3), Padding = new Padding(3),
Size = new System.Drawing.Size(122, 99), Size = new System.Drawing.Size(122, 99),
TabIndex = 0, TabIndex = 0,
Text = attr.Title, Text = attr.Title,
UseVisualStyleBackColor = true UseVisualStyleBackColor = true
}; };
tabPage.Controls.Add(cntrl as UserControl); tabPage.Controls.Add(cntrl as UserControl);
tabControl.TabPages.Add(tabPage); tabControl.TabPages.Add(tabPage);
if (attr.IsActive) if (attr.IsActive)
{ {
tabPage.Select(); tabPage.Select();
} }
} }
} }
} }
} }
} }
private async Task<bool> SaveAsync() private bool Save()
{ {
if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x))
{ {
return false; return false;
} }
var model = Element == null ? new S() : Mapper.MapToClass<E, S>(Element, true); var model = Element == null ? new S() : Mapper.MapToClass<E, S>(Element, true);
try try
{ {
GetValues(model); GetValues(model);
} }
catch (Exception ex) catch (Exception ex)
{ {
DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); DialogHelper.MessageException(ex.Message, "Ошибка при получении значений");
} }
if (model != null) if (model != null)
{ {
if (Element == null) if (Element == null)
{ {
Element = await _businessLogic.CreateAsync(model); Element = _businessLogic.Create(model);
} }
else else
{ {
Element = await _businessLogic.UpdateAsync(model); Element = _businessLogic.Update(model);
} }
if (Element == null) if (Element == null)
{ {
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении элемента"); DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении элемента");
return false; return false;
} }
_haveChages = false; _haveChages = false;
DialogHelper.MessageInformation("Сохранение прошло успешно", "Сообщение"); DialogHelper.MessageInformation("Сохранение прошло успешно", "Сообщение");
return true; return true;
} }
return false; return false;
} }
private ControlViewEntityElementConfiguration GetConfig() => _genericControlViewEntityElement?.GetConfigControl(); private ControlViewEntityElementConfiguration GetConfig() => _genericControlViewEntityElement?.GetConfigControl();
protected bool FillModel(S model) protected bool FillModel(S model)
{ {
if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x))
{ {
return false; return false;
} }
try try
{ {
GetValues(model); GetValues(model);
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
{ {
DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); DialogHelper.MessageException(ex.Message, "Ошибка при получении значений");
} }
return false; return false;
} }
} }
} }

View File

@ -12,13 +12,12 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq; using System.Xml.Linq;
namespace DesktopTools.Controls namespace DesktopTools.Controls
{ {
public partial class GenericControlEntityList<G, S, L, E, BL> : MainControlViewEntityList, IControlViewEntityList public partial class GenericControlEntityList<G, S, L, E, BL> : MainControlViewEntityList, IControlViewEntityList
where G : GetBindingModel, new() where G : GetBindingModel, new()
where S : SetBindingModel, new() where S : SetBindingModel, new()
where L : ListViewModel<E> where L : ListViewModel<E>
@ -68,7 +67,7 @@ namespace DesktopTools.Controls
} }
#region IControlViewEntityList #region IControlViewEntityList
public async void OpenControl(ControlOpenModel model) public void OpenControl(ControlOpenModel model)
{ {
_openMode = model.OpenMode; _openMode = model.OpenMode;
if (model.CloseList != null) if (model.CloseList != null)
@ -93,13 +92,13 @@ namespace DesktopTools.Controls
} }
if (!model.LazyLoading) if (!model.LazyLoading)
{ {
await LoadListAsync(); LoadList();
} }
} }
public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl(); public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl();
public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElementAsync(new G { Id = id }).Result?.ToString(); public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString();
public string SaveControlToXml() => new XElement("Control", public string SaveControlToXml() => new XElement("Control",
new XAttribute("Type", GetType().FullName), new XAttribute("Type", GetType().FullName),
@ -114,7 +113,7 @@ namespace DesktopTools.Controls
new XElement("Value", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Value ?? "-"))), new XElement("Value", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Value ?? "-"))),
new XElement("ParentId", ParentId?.ToString() ?? "-"))).ToString(); new XElement("ParentId", ParentId?.ToString() ?? "-"))).ToString();
public async void LoadControlFromXml(string xml) public void LoadControlFromXml(string xml)
{ {
var control = XElement.Parse(xml); var control = XElement.Parse(xml);
ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); ControlId = new Guid(control.Attribute("ControlId").Value.ToString());
@ -142,7 +141,7 @@ namespace DesktopTools.Controls
{ {
ParentId = new Guid(config.Element("ParentId").Value.ToString()); ParentId = new Guid(config.Element("ParentId").Value.ToString());
} }
await LoadListAsync(); LoadList();
} }
#endregion #endregion
@ -290,10 +289,10 @@ namespace DesktopTools.Controls
{ {
toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); }; toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); };
toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); }; toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); };
toolStripButtonDel.Click += async (object sender, EventArgs e) => { await DelElementAsync(); }; toolStripButtonDel.Click += (object sender, EventArgs e) => { DelElement(); };
toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; }; toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; };
toolStripButtonRef.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; toolStripButtonRef.Click += (object sender, EventArgs e) => { LoadList(); };
toolStripButtonSelect.Click += async (object sender, EventArgs e) => { await SelectElement(); }; toolStripButtonSelect.Click += (object sender, EventArgs e) => { SelectElement(); };
toolStripButtonClose.Click += (object sender, EventArgs e) => toolStripButtonClose.Click += (object sender, EventArgs e) =>
{ {
CloseListEvent?.Invoke(ControlId); CloseListEvent?.Invoke(ControlId);
@ -301,10 +300,10 @@ namespace DesktopTools.Controls
Dispose(); Dispose();
}; };
buttonSearch.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); };
buttonCancelSearch.Click += async (object sender, EventArgs e) => { panelSearch.Visible = false; await LoadListAsync(); }; buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; LoadList(); };
dataGridViewList.KeyDown += async (object sender, KeyEventArgs e) => dataGridViewList.KeyDown += (object sender, KeyEventArgs e) =>
{ {
switch (e.KeyCode) switch (e.KeyCode)
{ {
@ -323,41 +322,41 @@ namespace DesktopTools.Controls
case Keys.Delete: case Keys.Delete:
if (toolStripButtonDel.Visible) if (toolStripButtonDel.Visible)
{ {
await DelElementAsync(); DelElement();
} }
break; break;
} }
}; };
dataGridViewList.CellDoubleClick += async (object sender, DataGridViewCellEventArgs e) => dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) =>
{ {
if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0) if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0)
{ {
await SelectElement(); SelectElement();
} }
UpdElement(); UpdElement();
}; };
toolStripButtonPrev.Click += async (object sender, EventArgs e) => toolStripButtonPrev.Click += (object sender, EventArgs e) =>
{ {
if (int.TryParse(toolStripTextBoxPage.Text, out int page)) if (int.TryParse(toolStripTextBoxPage.Text, out int page))
{ {
toolStripTextBoxPage.Text = (page - 1).ToString(); toolStripTextBoxPage.Text = (page - 1).ToString();
await LoadListAsync(); LoadList();
} }
}; };
toolStripButtonNext.Click += async (object sender, EventArgs e) => toolStripButtonNext.Click += (object sender, EventArgs e) =>
{ {
if (int.TryParse(toolStripTextBoxPage.Text, out int page)) if (int.TryParse(toolStripTextBoxPage.Text, out int page))
{ {
toolStripTextBoxPage.Text = (page + 1).ToString(); toolStripTextBoxPage.Text = (page + 1).ToString();
await LoadListAsync(); LoadList();
} }
}; };
toolStripTextBoxPage.KeyDown += async (object sender, KeyEventArgs e) => toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) =>
{ {
if (e.KeyData == Keys.Enter) if (e.KeyData == Keys.Enter)
{ {
await LoadListAsync(); LoadList();
} }
}; };
@ -369,12 +368,12 @@ namespace DesktopTools.Controls
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => await LoadListAsync(); private void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => LoadList();
/// <summary> /// <summary>
/// Вызов события загрузки данных на datagrid /// Вызов события загрузки данных на datagrid
/// </summary> /// </summary>
private async Task LoadListAsync() private void LoadList()
{ {
var cursor = Cursor.Current; var cursor = Cursor.Current;
@ -440,7 +439,7 @@ namespace DesktopTools.Controls
} }
} }
} }
data = await _businessLogic.GetListAsync(model); data = _businessLogic.GetList(model);
if (data == null && _businessLogic.Errors.Count > 0) if (data == null && _businessLogic.Errors.Count > 0)
{ {
DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных");
@ -463,14 +462,14 @@ namespace DesktopTools.Controls
{ {
Cursor.Current = cursor; Cursor.Current = cursor;
} }
FillDataOnGridAsync(data?.List, selectedGuids); FillDataOnGrid(data?.List, selectedGuids);
} }
/// <summary> /// <summary>
/// Заполнение таблицы /// Заполнение таблицы
/// </summary> /// </summary>
/// <param name="data"></param> /// <param name="data"></param>
private void FillDataOnGridAsync(List<E> data, List<Guid> selectedGuids) private void FillDataOnGrid(List<E> data, List<Guid> selectedGuids)
{ {
if (data == null) if (data == null)
{ {
@ -513,7 +512,7 @@ namespace DesktopTools.Controls
/// <summary> /// <summary>
/// Вызов события при удалении элемента /// Вызов события при удалении элемента
/// </summary> /// </summary>
private async Task DelElementAsync() private void DelElement()
{ {
if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
@ -523,7 +522,7 @@ namespace DesktopTools.Controls
Cursor.Current = Cursors.WaitCursor; Cursor.Current = Cursors.WaitCursor;
foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) foreach (DataGridViewRow selected in dataGridViewList.SelectedRows)
{ {
await _businessLogic.DeleteAsync(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) });
} }
} }
catch (Exception ex) catch (Exception ex)
@ -540,7 +539,7 @@ namespace DesktopTools.Controls
finally finally
{ {
Cursor.Current = cursor; Cursor.Current = cursor;
await LoadListAsync(); LoadList();
} }
} }
} }
@ -548,12 +547,12 @@ namespace DesktopTools.Controls
/// <summary> /// <summary>
/// Вызов события при выборе элемента /// Вызов события при выборе элемента
/// </summary> /// </summary>
private async Task SelectElement() private void SelectElement()
{ {
try try
{ {
SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString());
SelectedText = (await _businessLogic.GetElementAsync(new G { Id = SelectedId }))?.ToString(); SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString();
CloseSelectEvent?.Invoke(true); CloseSelectEvent?.Invoke(true);
Dispose(); Dispose();
} }
@ -581,7 +580,10 @@ namespace DesktopTools.Controls
{ {
if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key)
{ {
control.ParentId = new Guid(key.Key.ToString()); if (key.Key.GetType().Name == "Guid")
{
control.ParentId = new Guid(key.Key.ToString());
}
control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString(); control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString();
} }
} }
@ -596,9 +598,9 @@ namespace DesktopTools.Controls
{ {
OpenMode = ControlOpenMode.List, OpenMode = ControlOpenMode.List,
ElementId = id, ElementId = id,
CloseElement = async (Guid id) => CloseElement = (Guid id) =>
{ {
await LoadListAsync(); LoadList();
form.Close(); form.Close();
} }
}); });

View File

@ -3,18 +3,17 @@ using ModuleTools.Enums;
using ModuleTools.Interfaces; using ModuleTools.Interfaces;
using ModuleTools.ViewModels; using ModuleTools.ViewModels;
using System; using System;
using System.Threading.Tasks;
namespace ModuleTools.BusinessLogics namespace ModuleTools.BusinessLogics
{ {
/// <summary> /// <summary>
/// Базовый класс для логики сущности /// Базовый класс для логики сущности
/// </summary> /// </summary>
/// <typeparam name="G"></typeparam> /// <typeparam name="G"></typeparam>
/// <typeparam name="S"></typeparam> /// <typeparam name="S"></typeparam>
/// <typeparam name="L"></typeparam> /// <typeparam name="L"></typeparam>
/// <typeparam name="E"></typeparam> /// <typeparam name="E"></typeparam>
public class GenericBusinessLogic<G, S, L, E> : CoreBusinessLogic public class GenericBusinessLogic<G, S, L, E> : CoreBusinessLogic
where G : GetBindingModel where G : GetBindingModel
where S : SetBindingModel where S : SetBindingModel
where L : ListViewModel<E> where L : ListViewModel<E>
@ -42,7 +41,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public async Task<L> GetListAsync(G model) public L GetList(G model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -52,7 +51,7 @@ namespace ModuleTools.BusinessLogics
{ {
throw new MethodAccessException("Нет прав на получение списка"); throw new MethodAccessException("Нет прав на получение списка");
} }
var result = await Service.ReadAsync(model); var result = Service.Read(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);
@ -73,7 +72,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public async Task<E> GetElementAsync(G model) public E GetElement(G model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -83,7 +82,7 @@ namespace ModuleTools.BusinessLogics
{ {
throw new MethodAccessException("Нет прав на получение списка"); throw new MethodAccessException("Нет прав на получение списка");
} }
var result = await Service.ReadAsync(model); var result = Service.Read(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);
@ -103,7 +102,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<E> CreateAsync(S model) public virtual E Create(S model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -112,7 +111,7 @@ namespace ModuleTools.BusinessLogics
{ {
return null; return null;
} }
var result = await Service.CreateAsync(model); var result = Service.Create(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);
@ -133,7 +132,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<E> UpdateAsync(S model) public virtual E Update(S model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -142,7 +141,7 @@ namespace ModuleTools.BusinessLogics
{ {
return null; return null;
} }
var result = await Service.UpdateAsync(model); var result = Service.Update(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);
@ -163,7 +162,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<bool> DeleteAsync(G model) public virtual bool Delete(G model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -172,7 +171,7 @@ namespace ModuleTools.BusinessLogics
{ {
return false; return false;
} }
var result = await Service.DeleteAsync(model); var result = Service.Delete(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);
@ -193,7 +192,7 @@ namespace ModuleTools.BusinessLogics
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public virtual async Task<E> RestoreAsync(G model) public virtual E Restore(G model)
{ {
Errors.Clear(); Errors.Clear();
try try
@ -202,7 +201,7 @@ namespace ModuleTools.BusinessLogics
{ {
return null; return null;
} }
var result = await Service.RestoreAsync(model); var result = Service.Restore(model);
if (!result.IsSucceeded) if (!result.IsSucceeded)
{ {
Errors.AddRange(result.Errors); Errors.AddRange(result.Errors);

View File

@ -1,13 +1,12 @@
using ModuleTools.BindingModels; using ModuleTools.BindingModels;
using ModuleTools.Models; using ModuleTools.Models;
using System.Threading.Tasks;
namespace ModuleTools.Interfaces namespace ModuleTools.Interfaces
{ {
/// <summary> /// <summary>
/// Описание логики для хранилища сущности /// Описание логики для хранилища сущности
/// </summary> /// </summary>
public interface IGenerticEntityService<G, S> public interface IGenerticEntityService<G, S>
where G : GetBindingModel where G : GetBindingModel
where S : SetBindingModel where S : SetBindingModel
{ {
@ -16,34 +15,34 @@ namespace ModuleTools.Interfaces
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
Task<OperationResultModel> ReadAsync(G model); OperationResultModel Read(G model);
/// <summary> /// <summary>
/// Создание новой сущности /// Создание новой сущности
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
Task<OperationResultModel> CreateAsync(S model); OperationResultModel Create(S model);
/// <summary> /// <summary>
/// Изменение сущности /// Изменение сущности
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
Task<OperationResultModel> UpdateAsync(S model); OperationResultModel Update(S model);
/// <summary> /// <summary>
/// Удаление сущности /// Удаление сущности
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
Task<OperationResultModel> DeleteAsync(G model); OperationResultModel Delete(G model);
/// <summary> /// <summary>
/// Восстановление сущности /// Восстановление сущности
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
Task<OperationResultModel> RestoreAsync(G model); OperationResultModel Restore(G model);
} }
} }

View File

@ -6,25 +6,24 @@ using ModuleTools.BusinessLogics;
using ModuleTools.Enums; using ModuleTools.Enums;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.BusinessLogics; using SecurityBusinessLogic.BusinessLogics;
using System.Threading.Tasks;
namespace DepartmentBusinessLogic.BusinessLogics namespace DepartmentBusinessLogic.BusinessLogics
{ {
/// <summary> /// <summary>
/// Логика работы с записями приказов /// Логика работы с записями приказов
/// </summary> /// </summary>
public class OrderStudentRecordBusinessLogic : GenericBusinessLogic<OrderStudentRecordGetBindingModel, OrderStudentRecordSetBindingModel, OrderStudentRecordListViewModel, OrderStudentRecordViewModel> public class OrderStudentRecordBusinessLogic : GenericBusinessLogic<OrderStudentRecordGetBindingModel, OrderStudentRecordSetBindingModel, OrderStudentRecordListViewModel, OrderStudentRecordViewModel>
{ {
public OrderStudentRecordBusinessLogic(IOrderStudentRecordService service) : base(service, "Приказы", AccessOperation.Приказы) { } public OrderStudentRecordBusinessLogic(IOrderStudentRecordService service) : base(service, "Приказы", AccessOperation.Приказы) { }
public override async Task<OrderStudentRecordViewModel> CreateAsync(OrderStudentRecordSetBindingModel model) public override OrderStudentRecordViewModel Create(OrderStudentRecordSetBindingModel model)
{ {
var result = await base.CreateAsync(model); var result = base.Create(model);
if (result != null) if (result != null)
{ {
var studentLogic = DependencyManager.Instance.Resolve<StudentBusinessLogic>(); var studentLogic = DependencyManager.Instance.Resolve<StudentBusinessLogic>();
var userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var student = await studentLogic.GetElementAsync(new StudentGetBindingModel { Id = result.StudentId }); var student = studentLogic.GetElement(new StudentGetBindingModel { Id = result.StudentId });
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -37,7 +36,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (student.StudentGroupId != result.StudentGroupToId) if (student.StudentGroupId != result.StudentGroupToId)
{ {
st.StudentGroupId = result.StudentGroupToId; st.StudentGroupId = result.StudentGroupToId;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -49,7 +48,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (student.Description != model.Info) if (student.Description != model.Info)
{ {
st.Description = model.Info; st.Description = model.Info;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -65,7 +64,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
&& student.StudentState != StudentState.Учится) && student.StudentState != StudentState.Учится)
{ {
st.StudentState = StudentState.Учится; st.StudentState = StudentState.Учится;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -79,7 +78,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
&& student.StudentState != StudentState.Академ) && student.StudentState != StudentState.Академ)
{ {
st.StudentState = StudentState.Академ; st.StudentState = StudentState.Академ;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -91,7 +90,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (result.OrderStudentMoveType == OrderStudentMoveType.ВосстановитьИзАкадема && student.StudentState != StudentState.Учится) if (result.OrderStudentMoveType == OrderStudentMoveType.ВосстановитьИзАкадема && student.StudentState != StudentState.Учится)
{ {
st.StudentState = StudentState.Учится; st.StudentState = StudentState.Учится;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -108,21 +107,21 @@ namespace DepartmentBusinessLogic.BusinessLogics
student.StudentState != StudentState.Отчислен) student.StudentState != StudentState.Отчислен)
{ {
st.StudentState = result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению ? StudentState.Завершил : StudentState.Отчислен; st.StudentState = result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению ? StudentState.Завершил : StudentState.Отчислен;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}"));
return null; return null;
} }
var delete = await studentLogic.DeleteAsync(new StudentGetBindingModel { Id = student.Id }); var delete = studentLogic.Delete(new StudentGetBindingModel { Id = student.Id });
if (!delete) if (!delete)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
Errors.Add(("Ошибка удаления студента", $"Не удалось удалить студента {studentName}")); Errors.Add(("Ошибка удаления студента", $"Не удалось удалить студента {studentName}"));
return null; return null;
} }
delete = await userLogic.DeleteAsync(new UserGetBindingModel { Id = student.UserId }); delete = userLogic.Delete(new UserGetBindingModel { Id = student.UserId });
if (!delete) if (!delete)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -134,7 +133,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (result.OrderStudentMoveType == OrderStudentMoveType.Восстановить && student.StudentState != StudentState.Учится) if (result.OrderStudentMoveType == OrderStudentMoveType.Восстановить && student.StudentState != StudentState.Учится)
{ {
st.StudentState = StudentState.Учится; st.StudentState = StudentState.Учится;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);
@ -146,7 +145,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (result.OrderStudentMoveType == OrderStudentMoveType.УбратьПоПереводу && student.StudentState != StudentState.Ушел) if (result.OrderStudentMoveType == OrderStudentMoveType.УбратьПоПереводу && student.StudentState != StudentState.Ушел)
{ {
st.StudentState = StudentState.Ушел; st.StudentState = StudentState.Ушел;
student = await studentLogic.UpdateAsync(st); student = studentLogic.Update(st);
if (student == null) if (student == null)
{ {
Errors.AddRange(studentLogic.Errors); Errors.AddRange(studentLogic.Errors);

View File

@ -15,14 +15,13 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks;
namespace DepartmentBusinessLogic.BusinessLogics namespace DepartmentBusinessLogic.BusinessLogics
{ {
/// <summary> /// <summary>
/// Логика работы с историями синхронизации приказов /// Логика работы с историями синхронизации приказов
/// </summary> /// </summary>
public class OrderSyncHistoryBusinessLogic : GenericBusinessLogic<OrderSyncHistoryGetBindingModel, OrderSyncHistorySetBindingModel, OrderSyncHistoryListViewModel, OrderSyncHistoryViewModel> public class OrderSyncHistoryBusinessLogic : GenericBusinessLogic<OrderSyncHistoryGetBindingModel, OrderSyncHistorySetBindingModel, OrderSyncHistoryListViewModel, OrderSyncHistoryViewModel>
{ {
private OrderSyncHistoryRecordBusinessLogic _recordLogic; private OrderSyncHistoryRecordBusinessLogic _recordLogic;
@ -40,9 +39,9 @@ namespace DepartmentBusinessLogic.BusinessLogics
public OrderSyncHistoryBusinessLogic(IOrderSyncHistoryService service) : base(service, "Синхронизация Приказов", AccessOperation.СинхронизацияПриказов) { } public OrderSyncHistoryBusinessLogic(IOrderSyncHistoryService service) : base(service, "Синхронизация Приказов", AccessOperation.СинхронизацияПриказов) { }
public async Task<bool> SyncOrders() public bool SyncOrders()
{ {
var history = await CreateAsync(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); var history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now });
if (history == null) if (history == null)
{ {
Errors.Add(("Ошибка создание истории", "Не удалось создать историю")); Errors.Add(("Ошибка создание истории", "Не удалось создать историю"));
@ -57,12 +56,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
_orderStudentRecordLogic = DependencyManager.Instance.Resolve<OrderStudentRecordBusinessLogic>(); _orderStudentRecordLogic = DependencyManager.Instance.Resolve<OrderStudentRecordBusinessLogic>();
_userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); _userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var address = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" }))?.List?.FirstOrDefault(); var address = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" })?.List?.FirstOrDefault();
if (address == null || address.Value.IsEmpty()) if (address == null || address.Value.IsEmpty())
{ {
Errors = _enviromentSettingLogic.Errors; Errors = _enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить адрес серверая для получения приказов по студентам")); Errors.Add(("Ошибка получения данных", "Не удалось получить адрес серверая для получения приказов по студентам"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -70,12 +69,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
return false; return false;
} }
var username = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" }))?.List?.FirstOrDefault(); var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault();
if (username == null || username.Value.IsEmpty()) if (username == null || username.Value.IsEmpty())
{ {
Errors = _enviromentSettingLogic.Errors; Errors = _enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам")); Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -83,12 +82,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
return false; return false;
} }
var password = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" }))?.List?.FirstOrDefault(); var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault();
if (password == null || password.Value.IsEmpty()) if (password == null || password.Value.IsEmpty())
{ {
Errors = _enviromentSettingLogic.Errors; Errors = _enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам")); Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -107,11 +106,11 @@ namespace DepartmentBusinessLogic.BusinessLogics
// авторизация // авторизация
// получение списка студентов // получение списка студентов
HttpResponseMessage response = await client.GetAsync($"{address.Value}/univer/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment"); HttpResponseMessage response = client.GetAsync($"{address.Value}/univer/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment").Result;
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
{ {
Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с сервера")); Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с сервера"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -121,7 +120,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
var studentFromServer = JsonSerializer.Deserialize<StudentListSyncModel>(response.Content.ReadAsStringAsync().Result); var studentFromServer = JsonSerializer.Deserialize<StudentListSyncModel>(response.Content.ReadAsStringAsync().Result);
if (studentFromServer.CurrentStudentsList.Count == 0) if (studentFromServer.CurrentStudentsList.Count == 0)
{ {
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = "Полученный список студентов пустой" Information = "Полученный список студентов пустой"
@ -129,12 +128,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
return true; return true;
} }
var groups = await _groupsLogic.GetListAsync(new StudentGroupGetBindingModel()); var groups = _groupsLogic.GetList(new StudentGroupGetBindingModel());
if (groups == null || groups.List == null) if (groups == null || groups.List == null)
{ {
Errors = _groupsLogic.Errors; Errors = _groupsLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить список групп")); Errors.Add(("Ошибка получения данных", "Не удалось получить список групп"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -142,12 +141,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
return false; return false;
} }
var students = await _studentLogic.GetListAsync(new StudentGetBindingModel()); var students = _studentLogic.GetList(new StudentGetBindingModel());
if (students == null || students.List == null) if (students == null || students.List == null)
{ {
Errors = _studentLogic.Errors; Errors = _studentLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов")); Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -161,12 +160,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
// студент не найден, значит он ушел с кафедры, выясняем почему // студент не найден, значит он ушел с кафедры, выясняем почему
if (studentSync == null) if (studentSync == null)
{ {
await SyncStudentOrders(history, student, groups.List, client, address.Value); SyncStudentOrders(history, student, groups.List, client, address.Value);
} }
// не совпадение групп // не совпадение групп
else if (student.StudentGroupName != studentSync.groupName) else if (student.StudentGroupName != studentSync.groupName)
{ {
await SyncStudentOrders(history, student, groups.List, client, address.Value); SyncStudentOrders(history, student, groups.List, client, address.Value);
} }
studentFromServer.CurrentStudentsList.Remove(studentSync); studentFromServer.CurrentStudentsList.Remove(studentSync);
@ -174,39 +173,39 @@ namespace DepartmentBusinessLogic.BusinessLogics
// новые студенты и восстановленцы // новые студенты и восстановленцы
foreach (var student in studentFromServer.CurrentStudentsList) foreach (var student in studentFromServer.CurrentStudentsList)
{ {
var deletedStudent = await _studentLogic.GetElementAsync(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); var deletedStudent = _studentLogic.GetElement(new StudentGetBindingModel { NumberOfBook = student.recordBookName });
if (deletedStudent == null && _studentLogic.Errors.FirstOrDefault(x => x.Message == "Элемент удален") != default) if (deletedStudent == null && _studentLogic.Errors.FirstOrDefault(x => x.Message == "Элемент удален") != default)
{ {
// восстановленец // восстановленец
deletedStudent = await _studentLogic.RestoreAsync(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); deletedStudent = _studentLogic.Restore(new StudentGetBindingModel { NumberOfBook = student.recordBookName });
if (deletedStudent == null) if (deletedStudent == null)
{ {
var errors = _studentLogic.Errors; var errors = _studentLogic.Errors;
errors.Add(("Ошибка при восстановлении студента", $"Не удалось восстановить студента {student.lastName} {student.firstName} {student.patronymicName}")); errors.Add(("Ошибка при восстановлении студента", $"Не удалось восстановить студента {student.lastName} {student.firstName} {student.patronymicName}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
}); });
continue; continue;
} }
var deletedUser = await _userLogic.RestoreAsync(new UserGetBindingModel { Id = deletedStudent.UserId }); var deletedUser = _userLogic.Restore(new UserGetBindingModel { Id = deletedStudent.UserId });
if (deletedUser == null) if (deletedUser == null)
{ {
var errors = _userLogic.Errors; var errors = _userLogic.Errors;
errors.Add(("Ошибка при восстановлении пользователя студента", $"Не удалось восстановить пользователя студента {student.lastName} {student.firstName} {student.patronymicName}")); errors.Add(("Ошибка при восстановлении пользователя студента", $"Не удалось восстановить пользователя студента {student.lastName} {student.firstName} {student.patronymicName}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
}); });
continue; continue;
} }
await SyncStudentOrders(history, deletedStudent, groups.List, client, address.Value); SyncStudentOrders(history, deletedStudent, groups.List, client, address.Value);
continue; continue;
} }
var user = await _userLogic.GetElementAsync(new UserGetBindingModel var user = _userLogic.GetElement(new UserGetBindingModel
{ {
Login = student.recordBookName Login = student.recordBookName
}); });
@ -216,7 +215,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
var errors = _userLogic.Errors; var errors = _userLogic.Errors;
errors.Add(("Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); errors.Add(("Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
@ -225,7 +224,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}";
user = await _userLogic.CreateAsync(new UserSetBindingModel user = _userLogic.Create(new UserSetBindingModel
{ {
Login = student.recordBookName, Login = student.recordBookName,
Password = userName Password = userName
@ -235,7 +234,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
var errors = _userLogic.Errors; var errors = _userLogic.Errors;
errors.Add(("Ошибка создания пользователя под студента", $"Не удалось создать пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); errors.Add(("Ошибка создания пользователя под студента", $"Не удалось создать пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
@ -244,7 +243,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
} }
var newStudent = await _studentLogic.CreateAsync(new StudentSetBindingModel var newStudent = _studentLogic.Create(new StudentSetBindingModel
{ {
Iduniv = student.iduniv, Iduniv = student.iduniv,
NumberOfBook = student.recordBookName, NumberOfBook = student.recordBookName,
@ -260,7 +259,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
var errors = _studentLogic.Errors; var errors = _studentLogic.Errors;
errors.Add(("Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}")); errors.Add(("Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
@ -268,13 +267,13 @@ namespace DepartmentBusinessLogic.BusinessLogics
continue; continue;
} }
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Добавлен студент {newStudent}" Information = $"Добавлен студент {newStudent}"
}); });
await SyncStudentOrders(history, newStudent, groups.List, client, address.Value); SyncStudentOrders(history, newStudent, groups.List, client, address.Value);
} }
return true; return true;
} }
@ -288,13 +287,13 @@ namespace DepartmentBusinessLogic.BusinessLogics
/// <param name="client"></param> /// <param name="client"></param>
/// <param name="address"></param> /// <param name="address"></param>
/// <returns></returns> /// <returns></returns>
private async Task SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, List<StudentGroupViewModel> groups, HttpClient client, string address) private void SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, List<StudentGroupViewModel> groups, HttpClient client, string address)
{ {
HttpResponseMessage response = await client.GetAsync($"{address}/univer/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={student.Iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd"); HttpResponseMessage response = client.GetAsync($"{address}/univer/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={student.Iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd").Result;
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
{ {
Errors.Add(("Ошибка получения данных", "Не удалось получить список приказов по студенту")); Errors.Add(("Ошибка получения данных", "Не удалось получить список приказов по студенту"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
@ -306,7 +305,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
if (syncOrder.markOfApprove.ToLower() != "true") if (syncOrder.markOfApprove.ToLower() != "true")
{ {
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Приказ {syncOrder.clericNumber} от {syncOrder.clericDate} ({syncOrder.orderTypeName}) по студенту {student} не утврежден " Information = $"Приказ {syncOrder.clericNumber} от {syncOrder.clericDate} ({syncOrder.orderTypeName}) по студенту {student} не утврежден "
@ -315,7 +314,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
if (syncOrder.clericNumber.IsEmpty()) if (syncOrder.clericNumber.IsEmpty())
{ {
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Приказ без номера от {syncOrder.clericDate} ({student})" Information = $"Приказ без номера от {syncOrder.clericDate} ({student})"
@ -324,7 +323,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
if (syncOrder.clericDate.IsEmpty()) if (syncOrder.clericDate.IsEmpty())
{ {
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Приказ {syncOrder.clericNumber} - неизвестная дата ({student})" Information = $"Приказ {syncOrder.clericNumber} - неизвестная дата ({student})"
@ -339,7 +338,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (syncOrder.orderTypeName != "Корректировка" && syncOrder.orderTypeName != "Назначение стипендии" && if (syncOrder.orderTypeName != "Корректировка" && syncOrder.orderTypeName != "Назначение стипендии" &&
syncOrder.orderTypeName != "Утверждение тем курсовых работ" && syncOrder.orderTypeName != "Утверждение тем работ" syncOrder.orderTypeName != "Утверждение тем курсовых работ" && syncOrder.orderTypeName != "Утверждение тем работ"
&& syncOrder.orderTypeName != "Смена ФИО") && syncOrder.orderTypeName != "Смена ФИО")
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Приказ {syncOrder.clericNumber} неопределенного типа {syncOrder.orderTypeName}" Information = $"Приказ {syncOrder.clericNumber} неопределенного типа {syncOrder.orderTypeName}"
@ -348,14 +347,14 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
// пытаемся найти приказ // пытаемся найти приказ
var order = await _orderLogic.GetElementAsync(new OrderGetBindingModel var order = _orderLogic.GetElement(new OrderGetBindingModel
{ {
OrderNumber = syncOrder.clericNumber OrderNumber = syncOrder.clericNumber
}); });
if (order == null) if (order == null)
{ {
// если не нашли - пытаемся создать // если не нашли - пытаемся создать
order = await _orderLogic.CreateAsync(new OrderSetBindingModel order = _orderLogic.Create(new OrderSetBindingModel
{ {
OrderNumber = syncOrder.clericNumber, OrderNumber = syncOrder.clericNumber,
OrderDate = Convert.ToDateTime(syncOrder.clericDate), OrderDate = Convert.ToDateTime(syncOrder.clericDate),
@ -365,7 +364,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
var errors = _orderLogic.Errors; var errors = _orderLogic.Errors;
errors.Add(("Ошибка добавления приказа", $"Не удалось добавить приказ {syncOrder.clericNumber} {syncOrder.clericDate}")); errors.Add(("Ошибка добавления приказа", $"Не удалось добавить приказ {syncOrder.clericNumber} {syncOrder.clericDate}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
@ -478,7 +477,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
if (orderStudentMoveType == OrderStudentMoveType.Неопределено) if (orderStudentMoveType == OrderStudentMoveType.Неопределено)
{ {
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Неизветсный приказ {syncOrder.orderTypeName} ({syncOrder.reason}) по студенту {student}" Information = $"Неизветсный приказ {syncOrder.orderTypeName} ({syncOrder.reason}) по студенту {student}"
@ -487,7 +486,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
// ищем в приказе запись по студенту // ищем в приказе запись по студенту
var studentOrder = await _orderStudentRecordLogic.GetElementAsync(new OrderStudentRecordGetBindingModel var studentOrder = _orderStudentRecordLogic.GetElement(new OrderStudentRecordGetBindingModel
{ {
OrderId = order.Id, OrderId = order.Id,
StudentId = student.Id, StudentId = student.Id,
@ -501,7 +500,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
} }
// создаем, если не нашли // создаем, если не нашли
studentOrder = await _orderStudentRecordLogic.CreateAsync(new OrderStudentRecordSetBindingModel studentOrder = _orderStudentRecordLogic.Create(new OrderStudentRecordSetBindingModel
{ {
OrderId = order.Id, OrderId = order.Id,
StudentId = student.Id, StudentId = student.Id,
@ -514,7 +513,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
{ {
var errors = _orderStudentRecordLogic.Errors; var errors = _orderStudentRecordLogic.Errors;
errors.Add(("Ошибка добавления записи приказа по студенту", $"Не удалось добавить запись приказа {syncOrder.orderSubTypeName} по студенту {student}")); errors.Add(("Ошибка добавления записи приказа по студенту", $"Не удалось добавить запись приказа {syncOrder.orderSubTypeName} по студенту {student}"));
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
@ -522,7 +521,7 @@ namespace DepartmentBusinessLogic.BusinessLogics
continue; continue;
} }
await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel
{ {
OrderSyncHistoryId = history.Id, OrderSyncHistoryId = history.Id,
Information = $"Добавили запись к приказу {order.OrderNumber} по студенту {student} с формулировкой {info}" Information = $"Добавили запись к приказу {order.OrderNumber} по студенту {student} с формулировкой {info}"

View File

@ -9,26 +9,25 @@ using ModuleTools.Enums;
using ModuleTools.Models; using ModuleTools.Models;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace DepartmentDatabaseImplementation.Implementations namespace DepartmentDatabaseImplementation.Implementations
{ {
/// <summary> /// <summary>
/// Реализация IOrderSyncHistoryRecordService /// Реализация IOrderSyncHistoryRecordService
/// </summary> /// </summary>
public class OrderSyncHistoryRecordService : IOrderSyncHistoryRecordService public class OrderSyncHistoryRecordService : IOrderSyncHistoryRecordService
{ {
public async Task<OperationResultModel> CreateAsync(OrderSyncHistoryRecordSetBindingModel model) public OperationResultModel Create(OrderSyncHistoryRecordSetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
var entity = Mapper.MapToClass<OrderSyncHistoryRecordSetBindingModel, OrderSyncHistoryRecord>(model, true); var entity = Mapper.MapToClass<OrderSyncHistoryRecordSetBindingModel, OrderSyncHistoryRecord>(model, true);
await context.OrderSyncHistoryRecords.AddAsync(entity); context.OrderSyncHistoryRecords.Add(entity);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(entity, true));
} }
public async Task<OperationResultModel> DeleteAsync(OrderSyncHistoryRecordGetBindingModel model) public OperationResultModel Delete(OrderSyncHistoryRecordGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
var entity = context.OrderSyncHistoryRecords.FirstOrDefault(x => x.Id == model.Id); var entity = context.OrderSyncHistoryRecords.FirstOrDefault(x => x.Id == model.Id);
@ -37,12 +36,12 @@ namespace DepartmentDatabaseImplementation.Implementations
return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound);
} }
context.OrderSyncHistoryRecords.Remove(entity); context.OrderSyncHistoryRecords.Remove(entity);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(true); return OperationResultModel.Success(true);
} }
public async Task<OperationResultModel> ReadAsync(OrderSyncHistoryRecordGetBindingModel model) public OperationResultModel Read(OrderSyncHistoryRecordGetBindingModel model)
{ {
int countPages = 0; int countPages = 0;
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -69,31 +68,28 @@ namespace DepartmentDatabaseImplementation.Implementations
query = query.Include(x => x.OrderSyncHistory); query = query.Include(x => x.OrderSyncHistory);
return await Task.Run(() => if (model.PageNumber.HasValue && model.PageSize.HasValue)
{ {
if (model.PageNumber.HasValue && model.PageSize.HasValue) countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
{ query = query
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); .Skip(model.PageSize.Value * model.PageNumber.Value)
query = query .Take(model.PageSize.Value);
.Skip(model.PageSize.Value * model.PageNumber.Value) }
.Take(model.PageSize.Value); var result = new OrderSyncHistoryRecordListViewModel
} {
var result = new OrderSyncHistoryRecordListViewModel MaxCount = countPages,
{ List = query.Select(x => Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(x, model.HaveRight)).ToList()
MaxCount = countPages, };
List = query.Select(x => Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result); return OperationResultModel.Success(result);
});
} }
public Task<OperationResultModel> RestoreAsync(OrderSyncHistoryRecordGetBindingModel model) public OperationResultModel Restore(OrderSyncHistoryRecordGetBindingModel model)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public async Task<OperationResultModel> UpdateAsync(OrderSyncHistoryRecordSetBindingModel model) public OperationResultModel Update(OrderSyncHistoryRecordSetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -104,7 +100,7 @@ namespace DepartmentDatabaseImplementation.Implementations
} }
entity = Mapper.MapToClass(model, entity, true); entity = Mapper.MapToClass(model, entity, true);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistoryRecord, OrderSyncHistoryRecordViewModel>(entity, true));
} }

View File

@ -8,26 +8,25 @@ using ModuleTools.Enums;
using ModuleTools.Models; using ModuleTools.Models;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace DepartmentDatabaseImplementation.Implementations namespace DepartmentDatabaseImplementation.Implementations
{ {
/// <summary> /// <summary>
/// Реализация IOrderSyncHistoryService /// Реализация IOrderSyncHistoryService
/// </summary> /// </summary>
public class OrderSyncHistoryService : IOrderSyncHistoryService public class OrderSyncHistoryService : IOrderSyncHistoryService
{ {
public async Task<OperationResultModel> CreateAsync(OrderSyncHistorySetBindingModel model) public OperationResultModel Create(OrderSyncHistorySetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
var entity = Mapper.MapToClass<OrderSyncHistorySetBindingModel, OrderSyncHistory>(model, true); var entity = Mapper.MapToClass<OrderSyncHistorySetBindingModel, OrderSyncHistory>(model, true);
await context.OrderSyncHistories.AddAsync(entity); context.OrderSyncHistories.Add(entity);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(entity, true));
} }
public async Task<OperationResultModel> DeleteAsync(OrderSyncHistoryGetBindingModel model) public OperationResultModel Delete(OrderSyncHistoryGetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
using var transaction = context.Database.BeginTransaction(); using var transaction = context.Database.BeginTransaction();
@ -40,24 +39,24 @@ namespace DepartmentDatabaseImplementation.Implementations
} }
context.OrderSyncHistories.Remove(entity); context.OrderSyncHistories.Remove(entity);
await context.SaveChangesAsync(); context.SaveChanges();
var records = context.OrderSyncHistoryRecords.Where(x => x.OrderSyncHistoryId == model.Id); var records = context.OrderSyncHistoryRecords.Where(x => x.OrderSyncHistoryId == model.Id);
context.OrderSyncHistoryRecords.RemoveRange(records); context.OrderSyncHistoryRecords.RemoveRange(records);
await context.SaveChangesAsync(); context.SaveChanges();
await transaction.CommitAsync(); transaction.Commit();
} }
catch (Exception) catch (Exception)
{ {
await transaction.RollbackAsync(); transaction.Rollback();
throw; throw;
} }
return OperationResultModel.Success(true); return OperationResultModel.Success(true);
} }
public async Task<OperationResultModel> ReadAsync(OrderSyncHistoryGetBindingModel model) public OperationResultModel Read(OrderSyncHistoryGetBindingModel model)
{ {
int countPages = 0; int countPages = 0;
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -77,31 +76,28 @@ namespace DepartmentDatabaseImplementation.Implementations
query = query.OrderByDescending(x => x.SyncDate); query = query.OrderByDescending(x => x.SyncDate);
return await Task.Run(() => if (model.PageNumber.HasValue && model.PageSize.HasValue)
{ {
if (model.PageNumber.HasValue && model.PageSize.HasValue) countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value);
{ query = query
countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); .Skip(model.PageSize.Value * model.PageNumber.Value)
query = query .Take(model.PageSize.Value);
.Skip(model.PageSize.Value * model.PageNumber.Value) }
.Take(model.PageSize.Value); var result = new OrderSyncHistoryListViewModel
} {
var result = new OrderSyncHistoryListViewModel MaxCount = countPages,
{ List = query.Select(x => Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(x, model.HaveRight)).ToList()
MaxCount = countPages, };
List = query.Select(x => Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(x, model.HaveRight)).ToList()
};
return OperationResultModel.Success(result); return OperationResultModel.Success(result);
});
} }
public Task<OperationResultModel> RestoreAsync(OrderSyncHistoryGetBindingModel model) public OperationResultModel Restore(OrderSyncHistoryGetBindingModel model)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public async Task<OperationResultModel> UpdateAsync(OrderSyncHistorySetBindingModel model) public OperationResultModel Update(OrderSyncHistorySetBindingModel model)
{ {
using var context = DatabaseManager.GetContext; using var context = DatabaseManager.GetContext;
@ -112,7 +108,7 @@ namespace DepartmentDatabaseImplementation.Implementations
} }
entity = Mapper.MapToClass(model, entity, true); entity = Mapper.MapToClass(model, entity, true);
await context.SaveChangesAsync(); context.SaveChanges();
return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(entity, true)); return OperationResultModel.Success(Mapper.MapToClass<OrderSyncHistory, OrderSyncHistoryViewModel>(entity, true));
} }

View File

@ -12,52 +12,55 @@ using System.Linq;
namespace DepartmentWindowsDesktop.EntityControls namespace DepartmentWindowsDesktop.EntityControls
{ {
/// <summary> /// <summary>
/// Реализация контрола для списка дисциплин /// Реализация контрола для списка дисциплин
/// </summary> /// </summary>
public partial class ControlDisciplineList : public partial class ControlDisciplineList :
GenericControlEntityList<DisciplineGetBindingModel, DisciplineSetBindingModel, DisciplineListViewModel, DisciplineViewModel, DisciplineBusinessLogic>, GenericControlEntityList<DisciplineGetBindingModel, DisciplineSetBindingModel, DisciplineListViewModel, DisciplineViewModel, DisciplineBusinessLogic>,
IGenericControlEntityList IGenericControlEntityList
{ {
private readonly DisciplineBlockBusinessLogic _disciplineBlockBusinessLogic; private readonly DisciplineBlockBusinessLogic _disciplineBlockBusinessLogic;
public ControlDisciplineList() public ControlDisciplineList()
{ {
InitializeComponent(); InitializeComponent();
_disciplineBlockBusinessLogic = DependencyManager.Instance.Resolve<DisciplineBlockBusinessLogic>(); _disciplineBlockBusinessLogic = DependencyManager.Instance.Resolve<DisciplineBlockBusinessLogic>();
Title = "Дисциплины"; Title = "Дисциплины";
ControlId = new Guid("1731f50b-b20b-44c4-aa56-b335764fae7a"); ControlId = new Guid("1731f50b-b20b-44c4-aa56-b335764fae7a");
AccessOperation = AccessOperation.Дисциплины; AccessOperation = AccessOperation.Дисциплины;
ControlViewEntityElement = new ControlDisciplineElement(); ControlViewEntityElement = new ControlDisciplineElement();
_genericControlViewEntityList = this; _genericControlViewEntityList = this;
FillSearchPanel(); FillSearchPanel();
} }
public IControl GetInstanceGenericControl() => new ControlDisciplineList() { ControlId = Guid.NewGuid() }; public IControl GetInstanceGenericControl() => new ControlDisciplineList() { ControlId = Guid.NewGuid() };
public ControlViewEntityListConfiguration GetConfigControl() => new() public ControlViewEntityListConfiguration GetConfigControl()
{ {
PaginationOn = true, return new ControlViewEntityListConfiguration()
PageNamesForPagination = _disciplineBlockBusinessLogic.GetListAsync(new DisciplineBlockGetBindingModel()).Result?.List?.Select(x => {
new PageNamesForPaginationModel PaginationOn = true,
{ PageNamesForPagination = _disciplineBlockBusinessLogic.GetList(new DisciplineBlockGetBindingModel())?.List?.Select(x =>
Key = x.Id, new PageNamesForPaginationModel
Value = x.Title {
})?.ToList(), Key = x.Id,
ParentPropertyName = "DisciplineBlockId" Value = x.Title
}; })?.ToList(),
ParentPropertyName = "DisciplineBlockId"
};
}
private void FillSearchPanel() private void FillSearchPanel()
{ {
var control = new BaseControlString("DisciplineNameForSearch", false, false, 0) var control = new BaseControlString("DisciplineNameForSearch", false, false, 0)
{ {
Location = new System.Drawing.Point(10, 10), Location = new System.Drawing.Point(10, 10),
Size = new System.Drawing.Size(400, 23), Size = new System.Drawing.Size(400, 23),
Name = "SearchDisciplineName", Name = "SearchDisciplineName",
TabIndex = 0 TabIndex = 0
}; };
control.SetTitleWidth(control.SetTitle("Название:")); control.SetTitleWidth(control.SetTitle("Название:"));
panelSearchControls.Controls.Add(control); panelSearchControls.Controls.Add(control);
} }
} }
} }

View File

@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace DepartmentWindowsDesktop.EntityControls namespace DepartmentWindowsDesktop.EntityControls
{ {
/// <summary> /// <summary>
/// Реализация контрола для сотрудника /// Реализация контрола для сотрудника
/// </summary> /// </summary>
public partial class ControlEmployeeElement : public partial class ControlEmployeeElement :
GenericControlEntityElement<EmployeeGetBindingModel, EmployeeSetBindingModel, EmployeeListViewModel, EmployeeViewModel, EmployeeBusinessLogic>, GenericControlEntityElement<EmployeeGetBindingModel, EmployeeSetBindingModel, EmployeeListViewModel, EmployeeViewModel, EmployeeBusinessLogic>,
IGenericControlEntityElement IGenericControlEntityElement
{ {
@ -38,22 +37,22 @@ namespace DepartmentWindowsDesktop.EntityControls
{ {
ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)> ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)>
{ {
{ "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsync(); }) }, { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) },
{ "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) }
} }
}; };
/// <summary> /// <summary>
/// Поиск пользователя под учетку, либо добавление нового, если не найдено /// Поиск пользователя под учетку, либо добавление нового, если не найдено
/// </summary> /// </summary>
private async Task AddUserAsync() private void AddUser()
{ {
var model = new EmployeeSetBindingModel(); var model = new EmployeeSetBindingModel();
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}";
var result = await logic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); var result = logic.GetList(new UserGetBindingModel { UserNameForSearch = userName });
if (result != null) if (result != null)
{ {
if (result.List.Count > 1) if (result.List.Count > 1)
@ -67,7 +66,7 @@ namespace DepartmentWindowsDesktop.EntityControls
} }
else else
{ {
var newuser = await logic.CreateAsync(new UserSetBindingModel var newuser = logic.Create(new UserSetBindingModel
{ {
Login = userName, Login = userName,
Password = model.DateBirth.ToShortDateString(), Password = model.DateBirth.ToShortDateString(),
@ -92,7 +91,7 @@ namespace DepartmentWindowsDesktop.EntityControls
/// <summary> /// <summary>
/// Сброс пароля пользователя /// Сброс пароля пользователя
/// </summary> /// </summary>
private async Task PasswordResetAsync() private void PasswordReset()
{ {
if (_element == null) if (_element == null)
{ {
@ -102,14 +101,14 @@ namespace DepartmentWindowsDesktop.EntityControls
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId });
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");
return; return;
} }
user.Password = model.DateBirth.ToShortDateString(); user.Password = model.DateBirth.ToShortDateString();
user = await logic.UpdateAsync(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true)); user = logic.Update(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true));
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");

View File

@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace DepartmentWindowsDesktop.EntityControls namespace DepartmentWindowsDesktop.EntityControls
{ {
/// <summary> /// <summary>
/// Реализация контрола для преподавателя /// Реализация контрола для преподавателя
/// </summary> /// </summary>
public partial class ControlLecturerElement : public partial class ControlLecturerElement :
GenericControlEntityElement<LecturerGetBindingModel, LecturerSetBindingModel, LecturerListViewModel, LecturerViewModel, LecturerBusinessLogic>, GenericControlEntityElement<LecturerGetBindingModel, LecturerSetBindingModel, LecturerListViewModel, LecturerViewModel, LecturerBusinessLogic>,
IGenericControlEntityElement IGenericControlEntityElement
{ {
@ -38,22 +37,22 @@ namespace DepartmentWindowsDesktop.EntityControls
{ {
ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)> ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)>
{ {
{ "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsunc(); }) }, { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) },
{ "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) }
} }
}; };
/// <summary> /// <summary>
/// Поиск пользователя под учетку, либо добавление нового, если не найдено /// Поиск пользователя под учетку, либо добавление нового, если не найдено
/// </summary> /// </summary>
private async Task AddUserAsunc() private void AddUser()
{ {
var model = new LecturerSetBindingModel(); var model = new LecturerSetBindingModel();
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}";
var result = await logic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); var result = logic.GetList(new UserGetBindingModel { UserNameForSearch = userName });
if (result != null) if (result != null)
{ {
if (result.List.Count > 1) if (result.List.Count > 1)
@ -67,7 +66,7 @@ namespace DepartmentWindowsDesktop.EntityControls
} }
else else
{ {
var newuser = await logic.CreateAsync(new UserSetBindingModel var newuser = logic.Create(new UserSetBindingModel
{ {
Login = userName, Login = userName,
Password = model.DateBirth.ToShortDateString(), Password = model.DateBirth.ToShortDateString(),
@ -92,7 +91,7 @@ namespace DepartmentWindowsDesktop.EntityControls
/// <summary> /// <summary>
/// Сброс пароля пользователя /// Сброс пароля пользователя
/// </summary> /// </summary>
private async Task PasswordResetAsync() private void PasswordReset()
{ {
if (_element == null) if (_element == null)
{ {
@ -102,14 +101,14 @@ namespace DepartmentWindowsDesktop.EntityControls
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId });
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");
return; return;
} }
user.Password = model.DateBirth.ToShortDateString(); user.Password = model.DateBirth.ToShortDateString();
user = await logic.UpdateAsync(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true)); user = logic.Update(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true));
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");

View File

@ -9,14 +9,13 @@ using DesktopTools.Models;
using ModuleTools.Enums; using ModuleTools.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace DepartmentWindowsDesktop.EntityControls namespace DepartmentWindowsDesktop.EntityControls
{ {
/// <summary> /// <summary>
/// Реализация контрола для списка историй синхронизации приказов /// Реализация контрола для списка историй синхронизации приказов
/// </summary> /// </summary>
public partial class ControlOrderSyncHistoryList : public partial class ControlOrderSyncHistoryList :
GenericControlEntityList<OrderSyncHistoryGetBindingModel, OrderSyncHistorySetBindingModel, OrderSyncHistoryListViewModel, OrderSyncHistoryViewModel, OrderSyncHistoryBusinessLogic>, GenericControlEntityList<OrderSyncHistoryGetBindingModel, OrderSyncHistorySetBindingModel, OrderSyncHistoryListViewModel, OrderSyncHistoryViewModel, OrderSyncHistoryBusinessLogic>,
IGenericControlEntityList IGenericControlEntityList
{ {
@ -44,7 +43,7 @@ namespace DepartmentWindowsDesktop.EntityControls
}, },
ControlOnMoveElem = new() ControlOnMoveElem = new()
{ {
{ "ToolStripMenuItemSyncOrders", ("Синхронизировать студентов", async (object sender, EventArgs e) => { await SyncOrders(); }) } { "ToolStripMenuItemSyncOrders", ("Синхронизировать студентов", (object sender, EventArgs e) => { SyncOrders(); }) }
} }
}; };
@ -52,9 +51,9 @@ namespace DepartmentWindowsDesktop.EntityControls
/// Синхронизация приказов /// Синхронизация приказов
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
private async Task SyncOrders() private void SyncOrders()
{ {
var flag = await _businessLogic.SyncOrders(); var flag = _businessLogic.SyncOrders();
if (!flag) if (!flag)
{ {
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при синхронизации"); DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при синхронизации");

View File

@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics;
using SecurityBusinessLogic.ViewModels; using SecurityBusinessLogic.ViewModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace DepartmentWindowsDesktop.EntityControls namespace DepartmentWindowsDesktop.EntityControls
{ {
/// <summary> /// <summary>
/// Реализация контрола для студента /// Реализация контрола для студента
/// </summary> /// </summary>
public partial class ControlStudentElement : public partial class ControlStudentElement :
GenericControlEntityElement<StudentGetBindingModel, StudentSetBindingModel, StudentListViewModel, StudentViewModel, StudentBusinessLogic>, GenericControlEntityElement<StudentGetBindingModel, StudentSetBindingModel, StudentListViewModel, StudentViewModel, StudentBusinessLogic>,
IGenericControlEntityElement IGenericControlEntityElement
{ {
@ -38,22 +37,22 @@ namespace DepartmentWindowsDesktop.EntityControls
{ {
ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)> ControlOnMoveElem = new Dictionary<string, (string Title, EventHandler Event)>
{ {
{ "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsync(); }) }, { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) },
{ "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) }
} }
}; };
/// <summary> /// <summary>
/// Поиск пользователя под учетку, либо добавление нового, если не найдено /// Поиск пользователя под учетку, либо добавление нового, если не найдено
/// </summary> /// </summary>
private async Task AddUserAsync() private void AddUser()
{ {
var model = new StudentSetBindingModel(); var model = new StudentSetBindingModel();
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}";
var user = await logic.GetElementAsync(new UserGetBindingModel { Login = model.NumberOfBook }); var user = logic.GetElement(new UserGetBindingModel { Login = model.NumberOfBook });
if (user == null) if (user == null)
{ {
if (logic.Errors.Count > 0) if (logic.Errors.Count > 0)
@ -61,7 +60,7 @@ namespace DepartmentWindowsDesktop.EntityControls
DialogHelper.MessageException(logic.Errors, "Ошибка при создании пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при создании пользователя");
return; return;
} }
user = await logic.CreateAsync(new UserSetBindingModel user = logic.Create(new UserSetBindingModel
{ {
Login = model.NumberOfBook, Login = model.NumberOfBook,
Password = userName, Password = userName,
@ -85,7 +84,7 @@ namespace DepartmentWindowsDesktop.EntityControls
/// <summary> /// <summary>
/// Сброс пароля пользователя /// Сброс пароля пользователя
/// </summary> /// </summary>
private async Task PasswordResetAsync() private void PasswordReset()
{ {
if (_element == null) if (_element == null)
{ {
@ -95,14 +94,14 @@ namespace DepartmentWindowsDesktop.EntityControls
if (FillModel(model)) if (FillModel(model))
{ {
var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>(); var logic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId });
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");
return; return;
} }
user.Password = model.NumberOfBook; user.Password = model.NumberOfBook;
user = await logic.UpdateAsync(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true)); user = logic.Update(Mapper.MapToClass<UserViewModel, UserSetBindingModel>(user, true));
if (user == null) if (user == null)
{ {
DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя");

View File

@ -39,7 +39,7 @@ namespace SecurityWindowsDesktop.EntityControls
public ControlViewEntityListConfiguration GetConfigControl() => new() public ControlViewEntityListConfiguration GetConfigControl() => new()
{ {
PaginationOn = true, PaginationOn = true,
PageNamesForPagination = _roleBusinessLogic.GetListAsync(new RoleGetBindingModel()).Result?.List?.Select(x => PageNamesForPagination = _roleBusinessLogic.GetList(new RoleGetBindingModel())?.List?.Select(x =>
new PageNamesForPaginationModel new PageNamesForPaginationModel
{ {
Key = x.Id, Key = x.Id,