синхронизация пользовтаелей

This commit is contained in:
kotcheshir73 2021-04-02 20:46:41 +04:00
parent 356c8a6d02
commit ba47e48eeb
14 changed files with 395 additions and 49 deletions

View File

@ -0,0 +1,31 @@
using ModuleTools.Interfaces;
using System.Collections.Generic;
namespace ModuleTools.BusinessLogics
{
/// <summary>
/// Основа всех бизнес-логик
/// </summary>
public class CoreBusinessLogic
{
/// <summary>
/// Менеджер безопасности
/// </summary>
protected readonly ISecurityManager _security;
/// <summary>
/// Перечень ошибок при выполнении операции
/// </summary>
public List<(string Title, string Message)> Errors { get; protected set; }
/// <summary>
/// Основа всех бизнес-логик
/// </summary>
/// <param name="service"></param>
public CoreBusinessLogic()
{
_security = DependencyManager.Instance.Resolve<ISecurityManager>();
Errors = new();
}
}
}

View File

@ -4,7 +4,6 @@ using ModuleTools.Interfaces;
using ModuleTools.Models; using ModuleTools.Models;
using ModuleTools.ViewModels; using ModuleTools.ViewModels;
using System; using System;
using System.Collections.Generic;
namespace ModuleTools.BusinessLogics namespace ModuleTools.BusinessLogics
{ {
@ -15,27 +14,17 @@ namespace ModuleTools.BusinessLogics
/// <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> 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>
where E : ElementViewModel where E : ElementViewModel
{ {
/// <summary>
/// Перечень ошибок при выполнении операции
/// </summary>
public List<(string Title, string Message)> Errors { get; protected set; }
/// <summary> /// <summary>
/// Сервис с хранилищем данных /// Сервис с хранилищем данных
/// </summary> /// </summary>
protected IGenerticEntityService<G, S> Service { get; set; } protected IGenerticEntityService<G, S> Service { get; set; }
/// <summary>
/// Менеджер безопасности
/// </summary>
protected ISecurityManager Security { get; set; }
/// <summary> /// <summary>
/// Тип операции, скоторым работает логика /// Тип операции, скоторым работает логика
/// </summary> /// </summary>
@ -54,8 +43,6 @@ namespace ModuleTools.BusinessLogics
public GenericBusinessLogic(IGenerticEntityService<G, S> service, string entity, AccessOperation serviceOperation) public GenericBusinessLogic(IGenerticEntityService<G, S> service, string entity, AccessOperation serviceOperation)
{ {
Service = service; Service = service;
Errors = new List<(string Title, string Message)>();
Security = DependencyManager.Instance.Resolve<ISecurityManager>();
_entity = entity; _entity = entity;
_serviceOperation = serviceOperation; _serviceOperation = serviceOperation;
} }
@ -68,11 +55,11 @@ namespace ModuleTools.BusinessLogics
/// <returns></returns> /// <returns></returns>
protected bool NoAccess(AccessBindingModel model, AccessType type) protected bool NoAccess(AccessBindingModel model, AccessType type)
{ {
if (Security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity))) if (_security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity)))
{ {
return false; return false;
} }
Errors.Add(("Ошибка безопасности", Security.ErrorMessage)); Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true; return true;
} }

View File

@ -19,6 +19,8 @@
ПользователиРоли = 5, ПользователиРоли = 5,
РаботасБекапом = 10, РаботасБекапом = 10,
Синхронизация = 11,
#endregion #endregion
#region База #region База

View File

@ -1,12 +1,10 @@
using ModuleTools.BusinessLogics; using ModuleTools.BusinessLogics;
using ModuleTools.Enums; using ModuleTools.Enums;
using ModuleTools.Extensions; using ModuleTools.Extensions;
using ModuleTools.Interfaces;
using ModuleTools.Models; using ModuleTools.Models;
using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.Interfaces;
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
namespace SecurityBusinessLogic.BusinessLogics namespace SecurityBusinessLogic.BusinessLogics
@ -14,33 +12,18 @@ namespace SecurityBusinessLogic.BusinessLogics
/// <summary> /// <summary>
/// Логика работы с бекапом /// Логика работы с бекапом
/// </summary> /// </summary>
public class BackupBusinessLogic public class BackupBusinessLogic : CoreBusinessLogic
{ {
/// <summary> /// <summary>
/// Серивс для работы с бекапом /// Серивс для работы с бекапом
/// </summary> /// </summary>
private readonly IBackupService _service; private readonly IBackupService _service;
/// <summary>
/// Менеджер безопасности
/// </summary>
private readonly ISecurityManager _security;
/// <summary>
/// Перечень ошибок при выполнении операции
/// </summary>
public List<(string Title, string Message)> Errors { get; protected set; }
/// <summary> /// <summary>
/// Логика работы с бекапом /// Логика работы с бекапом
/// </summary> /// </summary>
/// <param name="service"></param> /// <param name="service"></param>
public BackupBusinessLogic(IBackupService service) public BackupBusinessLogic(IBackupService service) => _service = service;
{
_service = service;
_security = DependencyManager.Instance.Resolve<ISecurityManager>();
Errors = new();
}
/// <summary> /// <summary>
/// Создание бекапа с данными /// Создание бекапа с данными

View File

@ -0,0 +1,67 @@
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Models;
using SecurityBusinessLogic.Interfaces;
using System;
namespace SecurityBusinessLogic.BusinessLogics
{
/// <summary>
/// Логика синхронизации пользователей
/// </summary>
public class SynchronizationBusinessLogic : CoreBusinessLogic
{
/// <summary>
/// Серивс для работы с бекапом
/// </summary>
private readonly ISynchronizationService _service;
/// <summary>
/// Логика работы с бекапом
/// </summary>
/// <param name="service"></param>
public SynchronizationBusinessLogic(ISynchronizationService service) => _service = service;
/// <summary>
/// Запуск синхронизации
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool RunSynchronization()
{
try
{
if (NoAccess())
{
return false;
}
var result = _service.RunSynchronization();
if (!result.IsSucceeded)
{
Errors.AddRange(result.Errors);
return false;
}
return true;
}
catch (Exception ex)
{
Errors.Add(("Ошибка", ex.Message));
return false;
}
}
/// <summary>
/// Проверка доступности операции для пользователя
/// </summary>
/// <returns></returns>
private bool NoAccess()
{
if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.Синхронизация, AccessType.Delete, "Синхронизация")))
{
return false;
}
Errors.Add(("Ошибка безопасности", _security.ErrorMessage));
return true;
}
}
}

View File

@ -0,0 +1,17 @@
using ModuleTools.Models;
namespace SecurityBusinessLogic.Interfaces
{
/// <summary>
/// Синхронизация пользователей (преподаватели, сотрудники, студенты)
/// </summary>
public interface ISynchronizationService
{
/// <summary>
/// Синхронизация
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OperationResultModel RunSynchronization();
}
}

View File

@ -0,0 +1,17 @@
using ModuleTools.Models;
using SecurityBusinessLogic.Interfaces;
namespace SecurityDatabaseImplementation.Implementations
{
/// <summary>
/// Реализация ISynchronizationService
/// </summary>
public class SynchronizationService : ISynchronizationService
{
public OperationResultModel RunSynchronization()
{
// пока нечего синхронизировать
return OperationResultModel.Success(null);
}
}
}

View File

@ -16,6 +16,7 @@ namespace SecurityDatabaseImplementation
DependencyManager.Instance.RegisterType<IUserRoleService, UserRoleService>(); DependencyManager.Instance.RegisterType<IUserRoleService, UserRoleService>();
DependencyManager.Instance.RegisterType<IBackupService, BackupJsonContractService>(); DependencyManager.Instance.RegisterType<IBackupService, BackupJsonContractService>();
DependencyManager.Instance.RegisterType<ISynchronizationService, SynchronizationService>();
} }
} }
} }

View File

@ -76,7 +76,8 @@ namespace SecurityWindowsDesktop
}; };
List<IControl> _controls = new() List<IControl> _controls = new()
{ {
new BackupControl() new BackupControl(),
new SynchronizationControl()
}; };
foreach (var cntrl in _controls) foreach (var cntrl in _controls)

View File

@ -131,7 +131,6 @@ namespace SecurityWindowsDesktop.SpecialControls
this.toolStripHeader.Size = new System.Drawing.Size(708, 25); this.toolStripHeader.Size = new System.Drawing.Size(708, 25);
this.toolStripHeader.TabIndex = 1; this.toolStripHeader.TabIndex = 1;
this.toolStripHeader.Text = "toolStrip1"; this.toolStripHeader.Text = "toolStrip1";
this.toolStripHeader.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.ToolStripHeader_ItemClicked);
// //
// toolStripButtonClose // toolStripButtonClose
// //

View File

@ -17,7 +17,7 @@ namespace SecurityWindowsDesktop.SpecialControls
public partial class BackupControl : UserControl, IControl public partial class BackupControl : UserControl, IControl
{ {
/// <summary> /// <summary>
/// Класс с бизнес-лоникой работы с бекапом /// Класс с бизнес-логикой работы с бекапом
/// </summary> /// </summary>
private readonly BackupBusinessLogic _businessLogic; private readonly BackupBusinessLogic _businessLogic;
@ -36,6 +36,11 @@ namespace SecurityWindowsDesktop.SpecialControls
Title = "Работа с бекапом"; Title = "Работа с бекапом";
ControlId = new Guid("cc9844e6-5d92-4c89-b817-4c17ec382bc1"); ControlId = new Guid("cc9844e6-5d92-4c89-b817-4c17ec382bc1");
AccessOperation = AccessOperation.РаботасБекапом; AccessOperation = AccessOperation.РаботасБекапом;
toolStripButtonClose.Click += (object sender, EventArgs e) =>
{
CloseEvent?.Invoke(ControlId);
Dispose();
};
} }
#region IControl #region IControl
@ -71,17 +76,6 @@ namespace SecurityWindowsDesktop.SpecialControls
} }
#endregion #endregion
/// <summary>
/// Закрытие контрола
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolStripHeader_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
CloseEvent?.Invoke(ControlId);
Dispose();
}
/// <summary> /// <summary>
/// Выбор пути для папки сохранения бекапа /// Выбор пути для папки сохранения бекапа
/// </summary> /// </summary>

View File

@ -0,0 +1,89 @@

namespace SecurityWindowsDesktop.SpecialControls
{
partial class SynchronizationControl
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.toolStripHeader = new System.Windows.Forms.ToolStrip();
this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton();
this.buttonRunSynchronization = new System.Windows.Forms.Button();
this.toolStripHeader.SuspendLayout();
this.SuspendLayout();
//
// toolStripHeader
//
this.toolStripHeader.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonClose});
this.toolStripHeader.Location = new System.Drawing.Point(0, 0);
this.toolStripHeader.Name = "toolStripHeader";
this.toolStripHeader.Size = new System.Drawing.Size(647, 25);
this.toolStripHeader.TabIndex = 0;
this.toolStripHeader.Text = "toolStrip1";
//
// toolStripButtonClose
//
this.toolStripButtonClose.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripButtonClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButtonClose.Image = global::SecurityWindowsDesktop.Properties.Resources.Close;
this.toolStripButtonClose.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButtonClose.Name = "toolStripButtonClose";
this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22);
this.toolStripButtonClose.Text = "Закрыть";
//
// buttonRunSynchronization
//
this.buttonRunSynchronization.Location = new System.Drawing.Point(124, 59);
this.buttonRunSynchronization.Name = "buttonRunSynchronization";
this.buttonRunSynchronization.Size = new System.Drawing.Size(375, 151);
this.buttonRunSynchronization.TabIndex = 1;
this.buttonRunSynchronization.Text = "Сделай за**ись";
this.buttonRunSynchronization.UseVisualStyleBackColor = true;
this.buttonRunSynchronization.Click += new System.EventHandler(this.ButtonRunSynchronization_Click);
//
// SynchronizationControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.buttonRunSynchronization);
this.Controls.Add(this.toolStripHeader);
this.Name = "SynchronizationControl";
this.Size = new System.Drawing.Size(647, 508);
this.toolStripHeader.ResumeLayout(false);
this.toolStripHeader.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStripHeader;
private System.Windows.Forms.ToolStripButton toolStripButtonClose;
private System.Windows.Forms.Button buttonRunSynchronization;
}
}

View File

@ -0,0 +1,98 @@
using DesktopTools.Helpers;
using DesktopTools.Interfaces;
using DesktopTools.Models;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using SecurityBusinessLogic.BusinessLogics;
using System;
using System.Windows.Forms;
using System.Xml.Linq;
namespace SecurityWindowsDesktop.SpecialControls
{
/// <summary>
/// Контрол для работы с синхронизацией
/// </summary>
public partial class SynchronizationControl : UserControl, IControl
{
/// <summary>
/// Класс с бизнес-логикой работы с синхронизацией
/// </summary>
private readonly SynchronizationBusinessLogic _businessLogic;
/// <summary>
/// Событие, вызываемое при закрытии контрола
/// </summary>
private event Action<Guid> CloseEvent;
/// <summary>
/// Контрол для работы с синхронизацией
/// </summary>
public SynchronizationControl()
{
InitializeComponent();
_businessLogic = DependencyManager.Instance.Resolve<SynchronizationBusinessLogic>();
Title = "Синхронизация";
ControlId = new Guid("c392818b-9036-4c4b-8a57-8ff935115e6a");
AccessOperation = AccessOperation.Синхронизация;
toolStripButtonClose.Click += (object sender, EventArgs e) =>
{
CloseEvent?.Invoke(ControlId);
Dispose();
};
}
#region IControl
public Guid ControlId { get; private set; }
public string Title { get; private set; }
public AccessOperation AccessOperation { get; private set; }
public IControl GetInstance() => new SynchronizationControl() { ControlId = Guid.NewGuid() };
public void Open(ControlOpenModel model)
{
if (model.CloseList != null)
{
CloseEvent += model.CloseList;
}
Dock = DockStyle.Fill;
}
public string SaveToXml() => new XElement("Control",
new XAttribute("Type", GetType().FullName),
new XAttribute("ControlId", ControlId),
new XAttribute("Title", Title),
new XAttribute("AccessOperation", AccessOperation)).ToString();
public void LoadFromXml(string xml)
{
var control = XElement.Parse(xml);
ControlId = new Guid(control.Attribute("ControlId").Value.ToString());
Title = control.Attribute("Title").Value.ToString();
AccessOperation = (AccessOperation)Enum.Parse(typeof(AccessOperation), control.Attribute("AccessOperation").Value.ToString());
}
#endregion
/// <summary>
/// Запуск синхронизации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRunSynchronization_Click(object sender, EventArgs e)
{
var cursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
if (_businessLogic.RunSynchronization())
{
DialogHelper.MessageInformation("Синхронизация прошла успешно", "Результат");
}
else
{
DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при синхронизации");
}
Cursor.Current = cursor;
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>