diff --git a/DepartmentPortal/Common/DatabaseCore/DatabaseContext.cs b/DepartmentPortal/Common/DatabaseCore/DatabaseContext.cs index 76a69fd..d3501f5 100644 --- a/DepartmentPortal/Common/DatabaseCore/DatabaseContext.cs +++ b/DepartmentPortal/Common/DatabaseCore/DatabaseContext.cs @@ -23,6 +23,11 @@ namespace DatabaseCore base.OnConfiguring(optionsBuilder); } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasIndex(s => s.Key).IsUnique(); + } + public virtual DbSet Accesses { set; get; } public virtual DbSet EnviromentSettings { set; get; } diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.Designer.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.Designer.cs new file mode 100644 index 0000000..8c0d54c --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.Designer.cs @@ -0,0 +1,216 @@ +// +using System; +using DatabaseCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace DatabaseCore.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20210401105731_UpdateSecurityModels")] + partial class UpdateSecurityModels + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.4") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("DatabaseCore.Models.Security.Access", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AccessOperation") + .HasColumnType("int"); + + b.Property("AccessType") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("Accesses"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.EnviromentSetting", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Key") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("EnviromentSettings"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Role", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleName") + .HasColumnType("nvarchar(max)"); + + b.Property("RolePriority") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.User", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Avatar") + .HasColumnType("varbinary(max)"); + + b.Property("CountAttempt") + .HasColumnType("int"); + + b.Property("DateBanned") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("DateLastVisit") + .HasColumnType("datetime2"); + + b.Property("IsBanned") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Access", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("Access") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Role", b => + { + b.Navigation("Access"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.User", b => + { + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.cs new file mode 100644 index 0000000..08ca627 --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210401105731_UpdateSecurityModels.cs @@ -0,0 +1,90 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DatabaseCore.Migrations +{ + public partial class UpdateSecurityModels : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "EmployeeId", + table: "Users"); + + migrationBuilder.DropColumn( + name: "LecturerId", + table: "Users"); + + migrationBuilder.DropColumn( + name: "StudentId", + table: "Users"); + + migrationBuilder.AlterColumn( + name: "Value", + table: "EnviromentSettings", + type: "nvarchar(max)", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "Key", + table: "EnviromentSettings", + type: "nvarchar(450)", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + + migrationBuilder.CreateIndex( + name: "IX_EnviromentSettings_Key", + table: "EnviromentSettings", + column: "Key", + unique: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_EnviromentSettings_Key", + table: "EnviromentSettings"); + + migrationBuilder.AddColumn( + name: "EmployeeId", + table: "Users", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.AddColumn( + name: "LecturerId", + table: "Users", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.AddColumn( + name: "StudentId", + table: "Users", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.AlterColumn( + name: "Value", + table: "EnviromentSettings", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Key", + table: "EnviromentSettings", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(450)"); + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs index a6a0f4f..fa00fee 100644 --- a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs @@ -58,13 +58,18 @@ namespace DatabaseCore.Migrations .HasColumnType("nvarchar(max)"); b.Property("Key") - .HasColumnType("nvarchar(max)"); + .IsRequired() + .HasColumnType("nvarchar(450)"); b.Property("Value") + .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); + b.HasIndex("Key") + .IsUnique(); + b.ToTable("EnviromentSettings"); }); @@ -116,24 +121,15 @@ namespace DatabaseCore.Migrations b.Property("DateLastVisit") .HasColumnType("datetime2"); - b.Property("EmployeeId") - .HasColumnType("uniqueidentifier"); - b.Property("IsBanned") .HasColumnType("bit"); b.Property("IsDeleted") .HasColumnType("bit"); - b.Property("LecturerId") - .HasColumnType("uniqueidentifier"); - b.Property("PasswordHash") .HasColumnType("nvarchar(max)"); - b.Property("StudentId") - .HasColumnType("uniqueidentifier"); - b.Property("UserName") .HasColumnType("nvarchar(max)"); diff --git a/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs b/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs index 0e5ac39..2eaa615 100644 --- a/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs +++ b/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs @@ -1,4 +1,5 @@ using ModuleTools.Attributes; +using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; namespace DatabaseCore.Models.Security @@ -12,10 +13,12 @@ namespace DatabaseCore.Models.Security { [DataMember] [MapConfiguration("Key")] + [Required] public string Key { get; set; } [DataMember] [MapConfiguration("Value")] + [Required] public string Value { get; set; } [DataMember] diff --git a/DepartmentPortal/Common/DatabaseCore/Models/Security/UserRole.cs b/DepartmentPortal/Common/DatabaseCore/Models/Security/UserRole.cs index 7d0b2fc..f182630 100644 --- a/DepartmentPortal/Common/DatabaseCore/Models/Security/UserRole.cs +++ b/DepartmentPortal/Common/DatabaseCore/Models/Security/UserRole.cs @@ -14,9 +14,11 @@ namespace DatabaseCore.Models.Security public class UserRole : BaseEntity { [DataMember] + [MapConfiguration("RoleId")] public Guid RoleId { get; set; } [DataMember] + [MapConfiguration("UserId")] public Guid UserId { get; set; } //------------------------------------------------------------------------- diff --git a/DepartmentPortal/Common/DatabaseCore/SecurityManager.cs b/DepartmentPortal/Common/DatabaseCore/SecurityManager.cs index 9dc916d..a47e9dc 100644 --- a/DepartmentPortal/Common/DatabaseCore/SecurityManager.cs +++ b/DepartmentPortal/Common/DatabaseCore/SecurityManager.cs @@ -32,12 +32,12 @@ namespace DatabaseCore if (model.Model != null) { // если не указан идентификатор пользователя, то смотрим, может он авторизован - if (!model.Model.UserId.HasValue && User.HasValue) + if (!model.Model.UserIdForAccess.HasValue && User.HasValue) { - model.Model.UserId = User.Value; + model.Model.UserIdForAccess = User.Value; } - var roles = context.UserRoles.Where(x => x.UserId == model.Model.UserId && !x.IsDeleted).Select(x => x.Role).OrderByDescending(x => x.RolePriority).ToList(); + var roles = context.UserRoles.Where(x => x.UserId == model.Model.UserIdForAccess && !x.IsDeleted).Select(x => x.Role).OrderByDescending(x => x.RolePriority).ToList(); if (roles == null) { ErrorMessage = $"Не верный пользователь"; @@ -125,6 +125,29 @@ namespace DatabaseCore context.SaveChanges(); } + List enviromentKeys = new() + { + "Практика", + "Учебный год", + "Даты семестра", + "Дисциплины (модули)", + "Кафедра", + "ГИА" + }; + foreach(var key in enviromentKeys) + { + var es = context.EnviromentSettings.FirstOrDefault(x => x.Key == key); + if(es == null) + { + context.EnviromentSettings.Add(new EnviromentSetting + { + Key = key, + Value = "Прописать значение!" + }); + } + } + context.SaveChanges(); + transaction.Commit(); } diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs index 6875fb0..bb511c1 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs @@ -1,4 +1,5 @@ -using ModuleTools.Extensions; +using DesktopTools.Interfaces; +using ModuleTools.Extensions; using System; using System.Windows.Forms; @@ -7,8 +8,13 @@ namespace DesktopTools.BaseControls /// /// Описание контрола для работы со значением свойства класса /// - public abstract partial class AbstractBaseControl : UserControl + public partial class AbstractBaseControl : UserControl { + /// + /// Фнукции для основного контрола + /// + protected IBaseControl _baseControl; + /// /// Оригинальное значение (требуется при откате изменений) /// @@ -53,14 +59,9 @@ namespace DesktopTools.BaseControls _propertyName = propertyName; _mustFilling = mustFilling; panelControl.Enabled = !readOnly; - SetDefaultValue(); + _baseControl?.SetDefaultValue(); } - /// - /// Установка _originalValue в значение по умолчанию - /// - protected abstract void SetDefaultValue(); - #region Работа с заголовком /// /// Установка заголовка @@ -98,33 +99,21 @@ namespace DesktopTools.BaseControls if (property != null) { _originalValue = property.GetValue(obj); - SetValueToControl(_originalValue); + _baseControl?.SetValueToControl(_originalValue); } } } - /// - /// Установка значения в контрол - /// - /// - protected abstract void SetValueToControl(object value); - /// /// Сброс значения /// - public abstract void DropValue(); + public void DropValue() => _baseControl?.DropValueForControl(); /// /// Проверка на заполненность /// /// - public abstract bool CheckValue(); - - /// - /// Получение значение с контрола - /// - /// - protected abstract object GetValueFromControl(); + public bool CheckValue() => _baseControl?.CheckValueForControl() ?? false; /// /// Заполнение свойства объекта значением из контрола @@ -137,7 +126,7 @@ namespace DesktopTools.BaseControls var property = obj.GetType().GetProperty(_propertyName); if (property != null) { - property.SetValue(obj, GetValueFromControl()); + property.SetValue(obj, _baseControl?.GetValueFromControl()); } } } diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlBool.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlBool.cs index 39bcb72..ed3bee8 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlBool.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlBool.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Interfaces; +using System; using System.Windows.Forms; namespace DesktopTools.BaseControls @@ -6,7 +7,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с bool-полем /// - public partial class BaseControlBool : AbstractBaseControl + public partial class BaseControlBool : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -17,6 +18,7 @@ namespace DesktopTools.BaseControls public BaseControlBool(string propertyName, bool mustFilling, bool readOnly) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; if (!_mustFilling) { @@ -32,9 +34,9 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(checkBox); } - protected override void SetDefaultValue() => _originalValue = _mustFilling ? false : null; + public void SetDefaultValue() => _originalValue = _mustFilling ? false : null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -46,7 +48,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -58,8 +60,10 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() => true; + public bool CheckValueForControl() => true; - protected override object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : checkBox.Checked; + public object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : checkBox.Checked; + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDateTime.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDateTime.cs index 3ee7eb0..243fff0 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDateTime.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDateTime.cs @@ -1,4 +1,5 @@ -using ModuleTools.Extensions; +using DesktopTools.Interfaces; +using ModuleTools.Extensions; using System; using System.Windows.Forms; @@ -7,7 +8,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с датой /// - public partial class BaseControlDateTime : AbstractBaseControl + public partial class BaseControlDateTime : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -21,6 +22,7 @@ namespace DesktopTools.BaseControls public BaseControlDateTime(string propertyName, bool mustFilling, bool readOnly, DateTime? minDate, DateTime? maxDate, string customDateFormat) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; if (!_mustFilling) { @@ -48,9 +50,9 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(dateTimePicker); } - protected override void SetDefaultValue() => _originalValue = _mustFilling ? DateTime.Now : null; + public void SetDefaultValue() => _originalValue = _mustFilling ? DateTime.Now : null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -62,7 +64,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -74,8 +76,10 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() => true; + public bool CheckValueForControl() => true; - protected override object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToDateTime(dateTimePicker.Value); + public object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToDateTime(dateTimePicker.Value); + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDecimal.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDecimal.cs index bd475f3..b052ccb 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDecimal.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlDecimal.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Interfaces; +using System; using System.Windows.Forms; namespace DesktopTools.BaseControls @@ -6,7 +7,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с вещественным полем /// - public partial class BaseControlDecimal : AbstractBaseControl + public partial class BaseControlDecimal : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -20,6 +21,7 @@ namespace DesktopTools.BaseControls public BaseControlDecimal(string propertyName, bool mustFilling, bool readOnly, decimal? minValue, decimal? maxValue, int? decimalPlaces) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; if (!_mustFilling) { @@ -47,9 +49,9 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(numericUpDown); } - protected override void SetDefaultValue() => _originalValue = _mustFilling ? 0 : null; + public void SetDefaultValue() => _originalValue = _mustFilling ? 0 : null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -61,7 +63,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -73,8 +75,10 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() => true; + public bool CheckValueForControl() => true; - protected override object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToDouble(numericUpDown.Value); + public object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToDouble(numericUpDown.Value); + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlEnum.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlEnum.cs index 8994dbe..57f9896 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlEnum.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlEnum.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Interfaces; +using System; using System.Drawing; using System.Windows.Forms; @@ -7,7 +8,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с перечислениями /// - public partial class BaseControlEnum : AbstractBaseControl + public partial class BaseControlEnum : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -19,6 +20,8 @@ namespace DesktopTools.BaseControls public BaseControlEnum(string propertyName, bool mustFilling, bool readOnly, Type enumType) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; + if (!_mustFilling) { checkBoxNullable.CheckedChanged += (object sender, EventArgs e) => @@ -38,9 +41,9 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(comboBox); } - protected override void SetDefaultValue() => _originalValue = null; + public void SetDefaultValue() => _originalValue = null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -52,7 +55,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -64,7 +67,7 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() + public bool CheckValueForControl() { if (_mustFilling && comboBox.SelectedIndex == -1) { @@ -74,7 +77,7 @@ namespace DesktopTools.BaseControls return true; } - protected override object GetValueFromControl() + public object GetValueFromControl() { if (_mustFilling && comboBox.SelectedIndex == -1) { @@ -82,5 +85,7 @@ namespace DesktopTools.BaseControls } return checkBoxNullable.Checked ? null : comboBox.SelectedItem; } + + public string GetPropertyName() => _propertyName; } } diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlGuid.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlGuid.cs index fdbbe4d..945f03f 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlGuid.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlGuid.cs @@ -1,22 +1,32 @@ -using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; using System; using System.Drawing; using System.Windows.Forms; namespace DesktopTools.BaseControls { - public partial class BaseControlGuid : AbstractBaseControl + public partial class BaseControlGuid : AbstractBaseControl, IBaseControl { - private AbstractControlViewEntityList _control; + private readonly IControlEntitySelectable _control; - public BaseControlGuid(string propertyName, bool mustFilling, bool readOnly, AbstractControlViewEntityList controlType) : base(propertyName, mustFilling, readOnly) + public BaseControlGuid(string propertyName, bool mustFilling, bool readOnly, IControlEntitySelectable controlType, Guid? parentId) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; _control = controlType; panelControl.Controls.Add(textBox); + if (parentId.HasValue) + { + textBox.Tag = parentId.Value; + textBox.Text = _control?.GetTitleFromId(parentId.Value); + panelControl.Enabled = false; + } + if (!_mustFilling) { buttonClear.Click += (object sender, EventArgs e) => @@ -32,30 +42,36 @@ namespace DesktopTools.BaseControls { var form = new Form { - Height = controlType.Height, - Width = controlType.Width, + Height = (controlType as UserControl).Height, + Width = (controlType as UserControl).Width, Text = $"{controlType.Title}. Выбор", StartPosition = FormStartPosition.CenterParent, ControlBox = false }; - var clone = controlType.Clone(); - form.Controls.Add(clone); - clone.Dock = DockStyle.Fill; - clone.FormForSelected = form; - clone.Open(); - if (form.ShowDialog() == DialogResult.OK) + var clone = controlType.GetInstance() as IControlEntitySelectable; + clone.Open(new ControlOpenModel { - textBox.Tag = clone.SelectedId; - textBox.Text = clone.SelectedText; - CallOnValueChangeEvent(); - } + OpenMode = ControlOpenMode.Select, + CloseSelect = (bool flag) => + { + if (flag) + { + textBox.Tag = clone.SelectedId; + textBox.Text = clone.SelectedText; + CallOnValueChangeEvent(); + } + form.Close(); + } + }); + form.Controls.Add(clone as UserControl); + form.ShowDialog(); }; panelControl.Controls.Add(buttonSelect); } - protected override void SetDefaultValue() => _originalValue = null; + public void SetDefaultValue() => _originalValue = null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -69,7 +85,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -84,7 +100,7 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() + public bool CheckValueForControl() { if (_mustFilling && textBox.Tag == null) { @@ -94,7 +110,7 @@ namespace DesktopTools.BaseControls return true; } - protected override object GetValueFromControl() + public object GetValueFromControl() { if (_mustFilling && textBox.Tag == null) { @@ -102,5 +118,7 @@ namespace DesktopTools.BaseControls } return textBox.Tag == null ? null : new Guid(textBox.Tag.ToString()); } + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.Designer.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.Designer.cs index ac7856d..0272eb5 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.Designer.cs @@ -1,4 +1,6 @@  +using System.Windows.Forms; + namespace DesktopTools.BaseControls { partial class BaseControlImage @@ -48,6 +50,7 @@ namespace DesktopTools.BaseControls this.pictureBox.Size = new System.Drawing.Size(100, 50); this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; + this.pictureBox.SizeMode = PictureBoxSizeMode.Zoom; ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); } diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.cs index 8fcc399..86403c4 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlImage.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Interfaces; +using System; using System.Drawing; using System.IO; using System.Windows.Forms; @@ -8,7 +9,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с изображением /// - public partial class BaseControlImage : AbstractBaseControl + public partial class BaseControlImage : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -21,6 +22,8 @@ namespace DesktopTools.BaseControls public BaseControlImage(string propertyName, bool mustFilling, bool readOnly, int? width, int? height) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; + if (width.HasValue) { Width = width.Value; @@ -48,11 +51,12 @@ namespace DesktopTools.BaseControls } }; panelControl.Controls.Add(pictureBox); + panelControl.Controls.Add(buttonLoad); } - protected override void SetDefaultValue() => _originalValue = null; + public void SetDefaultValue() => _originalValue = null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -65,7 +69,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -78,7 +82,7 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() + public bool CheckValueForControl() { if (_mustFilling && pictureBox.Image == null) { @@ -88,7 +92,7 @@ namespace DesktopTools.BaseControls return true; } - protected override object GetValueFromControl() + public object GetValueFromControl() { if (_mustFilling && pictureBox.Image == null) { @@ -97,5 +101,7 @@ namespace DesktopTools.BaseControls var converter = new ImageConverter(); return (byte[])converter.ConvertTo(pictureBox.Image, typeof(byte[])); } + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs index 6849f9c..398daf0 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Interfaces; +using System; using System.Windows.Forms; namespace DesktopTools.BaseControls @@ -6,7 +7,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с целочисленным полем /// - public partial class BaseControlInt : AbstractBaseControl + public partial class BaseControlInt : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -19,6 +20,7 @@ namespace DesktopTools.BaseControls public BaseControlInt(string propertyName, bool mustFilling, bool readOnly, decimal? minValue, decimal? maxValue) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; if (!_mustFilling) { @@ -42,9 +44,9 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(numericUpDown); } - protected override void SetDefaultValue() => _originalValue = _mustFilling ? 0 : null; + public void SetDefaultValue() => _originalValue = _mustFilling ? 0 : null; - protected override void SetValueToControl(object value) + public void SetValueToControl(object value) { if (value != null) { @@ -56,7 +58,7 @@ namespace DesktopTools.BaseControls } } - public override void DropValue() + public void DropValueForControl() { if (_originalValue != null) { @@ -68,8 +70,10 @@ namespace DesktopTools.BaseControls } } - public override bool CheckValue() => true; + public bool CheckValueForControl() => true; - protected override object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToInt32(numericUpDown.Value); + public object GetValueFromControl() => !_mustFilling && checkBoxNullable.Checked ? null : Convert.ToInt32(numericUpDown.Value); + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlString.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlString.cs index 93d0f06..8854e62 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlString.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlString.cs @@ -1,4 +1,5 @@ -using ModuleTools.Extensions; +using DesktopTools.Interfaces; +using ModuleTools.Extensions; using System; using System.Drawing; @@ -7,7 +8,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с однострочным текстовым полем /// - public partial class BaseControlString : AbstractBaseControl + public partial class BaseControlString : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -19,6 +20,8 @@ namespace DesktopTools.BaseControls public BaseControlString(string propertyName, bool mustFilling, bool readOnly, int? maxLength) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; + if (maxLength.HasValue) { textBox.MaxLength = maxLength.Value; @@ -27,13 +30,13 @@ namespace DesktopTools.BaseControls panelControl.Controls.Add(textBox); } - protected override void SetDefaultValue() => _originalValue = string.Empty; + public void SetDefaultValue() => _originalValue = string.Empty; - protected override void SetValueToControl(object value) => textBox.Text = value?.ToString(); + public void SetValueToControl(object value) => textBox.Text = value?.ToString(); - public override void DropValue() => textBox.Text = _originalValue?.ToString(); + public void DropValueForControl() => textBox.Text = _originalValue?.ToString(); - public override bool CheckValue() + public bool CheckValueForControl() { if (_mustFilling && textBox.Text.IsEmpty()) { @@ -43,7 +46,7 @@ namespace DesktopTools.BaseControls return true; } - protected override object GetValueFromControl() + public object GetValueFromControl() { if (_mustFilling && textBox.Text.IsEmpty()) { @@ -51,5 +54,7 @@ namespace DesktopTools.BaseControls } return textBox.Text; } + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs index cae8f04..1f90d71 100644 --- a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs @@ -1,4 +1,5 @@ -using ModuleTools.Extensions; +using DesktopTools.Interfaces; +using ModuleTools.Extensions; using System; using System.Drawing; @@ -7,7 +8,7 @@ namespace DesktopTools.BaseControls /// /// Контрол, предоставляющий работу с текстовым полем на несколько строк /// - public partial class BaseControlText : AbstractBaseControl + public partial class BaseControlText : AbstractBaseControl, IBaseControl { /// /// Конструктор @@ -20,6 +21,8 @@ namespace DesktopTools.BaseControls public BaseControlText(string propertyName, bool mustFilling, bool readOnly, int? maxLength, int? height) : base(propertyName, mustFilling, readOnly) { InitializeComponent(); + _baseControl = this; + if (maxLength.HasValue) { textBox.MaxLength = maxLength.Value; @@ -27,18 +30,19 @@ namespace DesktopTools.BaseControls if (height.HasValue) { textBox.Height = height.Value; + Height = height.Value; } textBox.TextChanged += (object sender, EventArgs e) => { CallOnValueChangeEvent(); }; panelControl.Controls.Add(textBox); } - protected override void SetDefaultValue() => _originalValue = string.Empty; + public void SetDefaultValue() => _originalValue = string.Empty; - protected override void SetValueToControl(object value) => textBox.Text = value?.ToString(); + public void SetValueToControl(object value) => textBox.Text = value?.ToString(); - public override void DropValue() => textBox.Text = _originalValue?.ToString(); + public void DropValueForControl() => textBox.Text = _originalValue?.ToString(); - public override bool CheckValue() + public bool CheckValueForControl() { if(_mustFilling && textBox.Text.IsEmpty()) { @@ -48,7 +52,7 @@ namespace DesktopTools.BaseControls return true; } - protected override object GetValueFromControl() + public object GetValueFromControl() { if (_mustFilling && textBox.Text.IsEmpty()) { @@ -56,5 +60,7 @@ namespace DesktopTools.BaseControls } return textBox.Text; } + + public string GetPropertyName() => _propertyName; } } \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.cs deleted file mode 100644 index 9c302a5..0000000 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.cs +++ /dev/null @@ -1,98 +0,0 @@ -using DesktopTools.Helpers; -using ModuleTools.Enums; -using System; -using System.Windows.Forms; - -namespace DesktopTools.Controls -{ - public abstract partial class AbstractControlViewEntityElement : UserControl - { - /// - /// Признак налиичия изменений - /// - protected bool _haveChages = false; - - /// - /// Событие, вызываемое при закрытии контрола - /// - protected event Action CloseEvent; - - /// - /// Событие, вызываемое при закрытии контрола - /// - public event Action CloseEventAdd { add { CloseEvent += value; } remove { CloseEvent -= value; } } - - /// - /// Открытие формы - /// - public abstract void Open(Guid? id); - - /// - /// Закрытие формы - /// - public void Close() - { - if(_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == - DialogResult.Yes) - { - if (!Save()) - { - return; - } - } - CloseEvent?.Invoke(ControlId); - Form?.Close(); - Dispose(); - } - - protected abstract bool Save(); - - /// - /// Установка флага, что есть изменения - /// - protected void ValueChange() => _haveChages = true; - - /// - /// Идентификатор контрола - /// - public Guid ControlId { get; protected set; } - - /// - /// Идентификатор элемента с которым идет раота при редактировании - /// - public Guid? ElementId { get; protected set; } - - /// - /// Идентификатор родителського элемента - /// - public Guid? ParentEleemtId { get; protected set; } - - /// - /// Заголовок контрола - /// - public string Title { get; protected set; } - - /// - /// Порядок контрола в меню - /// - public int Order { get; protected set; } - - /// - /// Операция в системе - /// - public AccessOperation AccessOperation { get; protected set; } - - /// - /// Форма в которой открыт контрол - /// - public Form Form { get; set; } - - /// - /// Констркутор - /// - public AbstractControlViewEntityElement() - { - InitializeComponent(); - } - } -} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.cs b/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.cs deleted file mode 100644 index 27f710e..0000000 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.cs +++ /dev/null @@ -1,93 +0,0 @@ -using ModuleTools.Enums; -using System; -using System.Windows.Forms; - -namespace DesktopTools.Controls -{ - public abstract partial class AbstractControlViewEntityList : UserControl - { - /// - /// Событие, вызываемое при закрытии контрола - /// - protected event Action CloseEvent; - - /// - /// Событие, вызываемое при закрытии контрола - /// - public event Action CloseEventAdd { add { CloseEvent += value; } remove { CloseEvent -= value; } } - - /// - /// Открытие формы - /// - public abstract void Open(); - - /// - /// Закрытие формы - /// - public void Close() - { - CloseEvent?.Invoke(ControlId); - if (FormForSelected != null) - { - FormForSelected.DialogResult = DialogResult.Cancel; - FormForSelected.Close(); - } - Dispose(); - } - - /// - /// Дубликат контрола - /// - /// - public abstract AbstractControlViewEntityList Clone(); - - /// - /// Идентификатор контрола - /// - public Guid ControlId { get; protected set; } - - /// - /// Заголовок контрола - /// - public string Title { get; protected set; } - - /// - /// Порядок контрола в меню - /// - public int Order { get; protected set; } - - /// - /// Операция в системе - /// - public AccessOperation AccessOperation { get; protected set; } - - /// - /// Идентификатор выбранной записи - /// - public Guid? SelectedId { get; set; } - - /// - /// Название выбранной записи - /// - public string SelectedText { get; set; } - - /// - /// Ссылка на форму, в который открыевается контрол для выбора значения - /// - public Form FormForSelected { get; set; } - - /// - /// Получение названиия объекта по его идентификатору - /// - /// - public abstract string GetTitleFromId(Guid id); - - /// - /// Констркутор - /// - public AbstractControlViewEntityList() - { - InitializeComponent(); - } - } -} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.cs deleted file mode 100644 index c6dceba..0000000 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.cs +++ /dev/null @@ -1,382 +0,0 @@ -using DesktopTools.Models; -using ModuleTools.Attributes; -using ModuleTools.BindingModels; -using ModuleTools.BusinessLogics; -using ModuleTools.Extensions; -using ModuleTools.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace DesktopTools.Controls -{ - public abstract partial class AbstractGenericControlEntityList : AbstractControlViewEntityList - where G : GetBindingModel, new() - where S : SetBindingModel, new() - where L : ListViewModel - where E : ElementViewModel - where BL : GenericBusinessLogic - { - /// - /// Объект бизнес-логики для получения данных - /// - protected BL _businessLogic; - - /// - /// Констркутор - /// - public AbstractGenericControlEntityList() - { - InitializeComponent(); - InitEvents(); - _businessLogic = DependencyManager.Instance.Resolve(); - } - - public override async void Open() - { - if (dataGridViewList.Columns.Count == 0) - { - Configurate(GetConfig()); - } - await LoadListAsync(); - } - - public override string GetTitleFromId(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString(); - - /// - /// Конфигуратор контрола - /// - /// Настройки - private void Configurate(ControlViewEntityListConfiguration config) - { - if (config == null) - { - return; - } - // формирование таблицы на основе модели - dataGridViewList.Columns.Clear(); - var properties = typeof(E).GetProperties(); - foreach (var property in properties) - { - var attr = property.GetCustomAttribute(); - if (attr != null) - { - var colIndex = attr.DisplayName == "Идентификатор" ? 0 : dataGridViewList.Columns.Count; - dataGridViewList.Columns.Insert(colIndex, new DataGridViewTextBoxColumn - { - HeaderText = attr.DisplayName, - Name = string.Format("Column{0}", property.Name), - ReadOnly = true, - Visible = !attr.IsHide, - Width = attr.ColumnWidth ?? 0, - AutoSizeMode = attr.ColumnWidth.HasValue ? DataGridViewAutoSizeColumnMode.None : DataGridViewAutoSizeColumnMode.Fill - }); - } - } - // настройка отображения основных кнопок - if (config.ShowToolStripButton != null) - { - foreach (ToolStripItem button in toolStripMenu.Items) - { - if (config.ShowToolStripButton.Contains(button.Name)) - { - button.Visible = false; - switch (button.Name) - { - case "toolStripButtonUpd": - toolStripSeparator1.Visible = false; - break; - case "toolStripButtonDel": - toolStripSeparator2.Visible = false; - break; - case "toolStripButtonRef": - toolStripSeparator3.Visible = false; - break; - case "toolStripButtonSearch": - toolStripSeparator4.Visible = false; - break; - } - } - } - } - // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" - if (config.ControlOnMoveElem != null) - { - foreach (var elem in config.ControlOnMoveElem) - { - ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key }; - item.Click += elem.Value.Event; - toolStripSplitButtonActions.DropDownItems.Add(item); - contextMenuStripDataGrid.Items.Add(item); - } - } - // либо скрытие пункта, если не предусмотренно подпунктов - else - { - toolStripSplitButtonActions.Visible = false; - toolStripSeparator3.Visible = false; - } - - // Пагинация - if (config.PaginationOn) - { - if (config.CountElementsOnPage.HasValue) - { - toolStripTextBoxPage.Tag = config.CountElementsOnPage.Value; - } - // пагинация по названиям - if (config.PageNamesForPagination != null) - { - toolStripButtonPrev.Visible = toolStripLabelPage.Visible = toolStripTextBoxPage.Visible = toolStripLabelCountPages.Visible = - toolStripButtonNext.Visible = false; - toolStripComboBoxPageNames.Items.AddRange(config.PageNamesForPagination.ToArray()); - toolStripComboBoxPageNames.SelectedIndex = 0; - } - // пагинация по страницам - else - { - toolStripLabelPageName.Visible = toolStripComboBoxPageNames.Visible = false; - } - } - // нет пагинации - else - { - toolStripFooter.Visible = false; - } - - // при вызове контрола для выбора элемента, делаем возможность выбора только одной записи - dataGridViewList.MultiSelect = FormForSelected == null; - } - - /// - /// Инициализация событий к контролам - /// - private void InitEvents() - { - toolStripButtonAdd.Click += (object sender, EventArgs e) => { CallAddElementEvent(); }; - toolStripButtonUpd.Click += (object sender, EventArgs e) => { CallUpdElementEvent(); }; - toolStripButtonDel.Click += (object sender, EventArgs e) => { CallDelElementEvent(); }; - toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; }; - toolStripButtonRef.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; - toolStripButtonClose.Click += (object sender, EventArgs e) => { Close(); }; - - buttonSearch.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; - buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; }; - - dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => - { - switch (e.KeyCode) - { - case Keys.Insert: - CallAddElementEvent(); - break; - case Keys.Enter: - CallUpdElementEvent(); - break; - case Keys.Delete: - CallDelElementEvent(); - break; - } - }; - dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) => - { - if (FormForSelected != null && dataGridViewList.SelectedRows.Count > 0) - { - SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); - SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString(); - FormForSelected.DialogResult = DialogResult.OK; - FormForSelected.Close(); - return; - } - CallUpdElementEvent(); - }; - - toolStripButtonPrev.Click += async (object sender, EventArgs e) => - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page)) - { - toolStripTextBoxPage.Text = (page - 1).ToString(); - await LoadListAsync(); - } - }; - toolStripButtonNext.Click += async (object sender, EventArgs e) => - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page)) - { - toolStripTextBoxPage.Text = (page + 1).ToString(); - await LoadListAsync(); - } - }; - toolStripTextBoxPage.KeyDown += async (object sender, KeyEventArgs e) => - { - if (e.KeyData == Keys.Enter) - { - await LoadListAsync(); - } - }; - - toolStripComboBoxPageNames.SelectedIndexChanged += async (object sender, EventArgs e) => { await LoadListAsync(); }; - } - - /// - /// Вызов события загрузки данных на datagrid - /// - private async Task LoadListAsync() - { - var cursor = Cursor.Current; - L data = null; - try - { - Cursor.Current = Cursors.WaitCursor; - // если включена пагинация - if (toolStripFooter.Visible) - { - // постраничная - if (toolStripTextBoxPage.Visible) - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxPage.Tag.ToString(), out int count)) - { - await Task.Run(() => data = GetDataWithPageNumber(page, count)); - } - } - // поименная - else if (toolStripComboBoxPageNames.Visible) - { - var key = toolStripComboBoxPageNames.Text; - if (key.IsNotEmpty()) - { - await Task.Run(() => data = GetDataWithPageName(key)); - } - } - } - else - { - await Task.Run(() => data = GetData()); - } - - if (data == null) - { - // TODO вывод сообщения об ощибок - return; - } - - toolStripLabelCountPages.Text = $"из {data.MaxCount}"; - FillDataOnGridAsync(data.List); - } - finally - { - Cursor.Current = cursor; - } - } - - /// - /// Заполнение таблицы - /// - /// - private void FillDataOnGridAsync(List data) - { - if (data == null) - { - return; - } - dataGridViewList.Rows.Clear(); - foreach (var elem in data) - { - var mas = new List(); - foreach (DataGridViewColumn column in dataGridViewList.Columns) - { - mas.Add(elem.GetType().GetProperty(column.Name["Column".Length..])?.GetValue(elem)); - } - - dataGridViewList.Rows.Add(mas.ToArray()); - } - } - - /// - /// Вызов события при добавлении элемента - /// - private void CallAddElementEvent() => LaunchControl(null); - - /// - /// Вызов события при изменении элемента - /// - private void CallUpdElementEvent() - { - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) - { - LaunchControl(new Guid(selected.Cells[0].Value.ToString())); - } - } - - /// - /// Вызов события при удалении элемента - /// - private void CallDelElementEvent() - { - if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - var cursor = Cursor.Current; - try - { - Cursor.Current = Cursors.WaitCursor; - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) - { - _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); - } - } - catch (Exception ex) - { - if (_businessLogic.Errors.Count != 0) - { - MessageBox.Show(_businessLogic.Errors.LastOrDefault().Message ?? ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - finally - { - Cursor.Current = cursor; - } - } - } - - /// - /// Создание формы с контролом для работы с элементом - /// - /// - private void LaunchControl(Guid? id) - { - try - { - var control = new GenericControlEntityElement(); - control.Open(id); - var form = new Form - { - Height = control.Height, - Width = control.Width, - Text = $"{Title}. Добавление", - StartPosition = FormStartPosition.CenterParent, - ControlBox = false - }; - form.Controls.Add(control); - control.Dock = DockStyle.Fill; - control.Form = form; - form.Show(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - protected abstract ControlViewEntityListConfiguration GetConfig(); - - protected abstract L GetData(); - - protected abstract L GetDataWithPageName(string key); - - protected abstract L GetDataWithPageNumber(int page, int count); - } -} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs deleted file mode 100644 index eae7a9d..0000000 --- a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs +++ /dev/null @@ -1,176 +0,0 @@ -using DesktopTools.BaseControls; -using ModuleTools.Attributes; -using ModuleTools.BindingModels; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using ModuleTools.Extensions; -using ModuleTools.ViewModels; -using System; -using System.Linq; -using System.Reflection; -using System.Windows.Forms; - -namespace DesktopTools.Controls -{ - public partial class GenericControlEntityElement : AbstractControlViewEntityElement - where G : GetBindingModel, new() - where S : SetBindingModel, new() - where L : ListViewModel - where E : ElementViewModel - where BL : GenericBusinessLogic - { - /// - /// Объект бизнес-логики для получения данных - /// - private readonly BL _businessLogic; - - private event Action SetTitleWidth; - - private event Action SetValues; - - private event Action DropValues; - - private event Func CheckValues; - - private event Action GetValues; - - private E _element = null; - private E Element { get { return _element; } set { _element = value; SetValues?.Invoke(_element); _haveChages = false; } } - - public GenericControlEntityElement() - { - InitializeComponent(); - InitEvents(); - _businessLogic = DependencyManager.Instance.Resolve(); - } - - public override void Open(Guid? id) - { - if (panelContainer.Controls.Count == 0) - { - Configurate(); - } - Element = _businessLogic.GetElement(new G { Id = id }); - } - - private void InitEvents() - { - toolStripButtonSave.Click += (object sender, EventArgs e) => { Save(); }; - toolStripButtonReload.Click += (object sender, EventArgs e) => { DropValues?.Invoke(); }; - toolStripButtonClose.Click += (object sender, EventArgs e) => { Close(); }; - } - - private void Configurate() - { - int positionY = 5; - int positionX = 5; - int interval = 15; - - int titleWidth = 0; - - foreach (var property in typeof(E).GetProperties()) - { - var attribute = property.GetCustomAttribute(); - if (attribute != null) - { - AbstractBaseControl control = null; - switch (attribute.ControlType) - { - case ControlType.ControlString: - control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength); - break; - case ControlType.ControlText: - control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height); - break; - case ControlType.ControlInt: - control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue); - break; - case ControlType.ControlDecimal: - control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, - attribute.MaxValue, attribute.DecimalPlaces); - break; - case ControlType.ControlBool: - control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly); - break; - case ControlType.ControlDateTime: - control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate, - attribute.MaxDate, attribute.CustomDateFormat); - break; - case ControlType.ControlImage: - control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height); - break; - case ControlType.ControlEnum: - control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType); - break; - case ControlType.ControlGuid: - if (attribute.ControlTypeObject.IsNotEmpty()) - { - control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly, - DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as AbstractControlViewEntityList); - } - break; - } - if (control == null) - { - continue; - } - - var widthTitle = control.SetTitle(attribute.DisplayName); - if (widthTitle > titleWidth) - { - titleWidth = widthTitle; - } - - control.OnValueChangeEvent += ValueChange; - SetValues += control.SetValue; - DropValues += control.DropValue; - CheckValues += control.CheckValue; - SetTitleWidth += control.SetTitleWidth; - GetValues += control.GetValue; - - control.Location = new System.Drawing.Point(positionX, positionY); - control.Width = Width - positionX * 2; - control.Anchor = AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Left; - positionY += control.Height + interval; - - panelContainer.Controls.Add(control); - } - } - - SetTitleWidth(titleWidth); - } - - protected override bool Save() - { - if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) - { - return false; - } - var model = Element == null ? new S() : Mapper.MapToClass(Element, true); - GetValues(model); - - if (model != null) - { - if (Element == null) - { - Element = _businessLogic.Create(model); - } - else - { - Element = _businessLogic.Update(model); - } - - if (Element == null) - { - throw new Exception($"Ошибка при сохранении: {_businessLogic.Errors.LastOrDefault().Message}"); - } - - _haveChages = false; - MessageBox.Show("Сохранение прошло успешно", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - return true; - } - - return false; - } - } -} diff --git a/DepartmentPortal/Common/DesktopTools/Enums/ControlOpenMode.cs b/DepartmentPortal/Common/DesktopTools/Enums/ControlOpenMode.cs new file mode 100644 index 0000000..34664b4 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Enums/ControlOpenMode.cs @@ -0,0 +1,23 @@ +namespace DesktopTools.Enums +{ + /// + /// С какой целью открыт контрол + /// + public enum ControlOpenMode + { + /// + /// Вывод списка на основной форме + /// + List = 0, + + /// + /// Для выбора элемента + /// + Select = 1, + + /// + /// Для вложенного списка + /// + Child = 2 + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Enums/ToolStripButtonListNames.cs b/DepartmentPortal/Common/DesktopTools/Enums/ToolStripButtonListNames.cs new file mode 100644 index 0000000..8765709 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Enums/ToolStripButtonListNames.cs @@ -0,0 +1,18 @@ +namespace DesktopTools.Enums +{ + /// + /// Имена кнопок на основной панеле контрола для работы со списком сущности + /// + public enum ToolStripButtonListNames + { + toolStripButtonAdd, + + toolStripButtonUpd, + + toolStripButtonDel, + + toolStripButtonSearch, + + toolStripButtonRef + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs b/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs index 7cd0172..dba1273 100644 --- a/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs +++ b/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs @@ -1,15 +1,34 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace DesktopTools.Helpers { public static class DialogHelper { + public static DialogResult MessageInformation(string message, string title) => + MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Information); + public static DialogResult MessageQuestion(string message, string title) => MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question); + public static DialogResult MessageQuestion(string message) => + MessageBox.Show(message, "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + + public static DialogResult MessageException(string message) => + MessageBox.Show(message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + public static DialogResult MessageException(string message, string title) => + MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error); + public static DialogResult MessageException(List<(string Title, string Message)> messages, string title) + { + if (messages.Count == 1) + { + return MessageBox.Show(messages.First().Message, messages.First().Title, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + else + { + return MessageBox.Show(string.Join(Environment.NewLine, messages.Select(x=> $"{x.Title}:{x.Message}")), title, MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IBaseControl.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IBaseControl.cs new file mode 100644 index 0000000..7aa968f --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IBaseControl.cs @@ -0,0 +1,42 @@ +namespace DesktopTools.Interfaces +{ + /// + /// Работа с контролами вывода свойства элемента + /// + public interface IBaseControl + { + /// + /// Установка _originalValue в значение по умолчанию + /// + void SetDefaultValue(); + + /// + /// Установка значения в контрол + /// + /// + void SetValueToControl(object value); + + /// + /// Сброс значения + /// + void DropValueForControl(); + + /// + /// Проверка на заполненность + /// + /// + bool CheckValueForControl(); + + /// + /// Получение значение с контрола + /// + /// + object GetValueFromControl(); + + /// + /// Получение имени свойства + /// + /// + string GetPropertyName(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControl.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControl.cs new file mode 100644 index 0000000..8488cf7 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControl.cs @@ -0,0 +1,39 @@ +using DesktopTools.Models; +using ModuleTools.Enums; +using System; + +namespace DesktopTools.Interfaces +{ + /// + /// Основные параметры для контрола + /// + public interface IControl + { + /// + /// Идентификатор контрола + /// + public Guid ControlId { get; } + + /// + /// Заголовок контрола + /// + string Title { get; } + + /// + /// Операция в системе + /// + public AccessOperation AccessOperation { get; } + + /// + /// Создание дубликата + /// + /// + IControl GetInstance(); + + /// + /// Открытие контрола + /// + /// + void Open(ControlOpenModel model); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControlChildEntity.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlChildEntity.cs new file mode 100644 index 0000000..40d4af9 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlChildEntity.cs @@ -0,0 +1,25 @@ +using System; + +namespace DesktopTools.Interfaces +{ + /// + /// параметры для контрола-налсденика + /// + public interface IControlChildEntity : IControl + { + /// + /// Название свойства в дочернем классе, по которму идет связь с родительским классом + /// + public string ParentPropertyName { get; set; } + + /// + /// Идентификатор родительской записи + /// + public object ParentObject { get; set; } + + /// + /// Идентификатор родительского элемента + /// + public Guid? ParentId { get; set; } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntityList.cs new file mode 100644 index 0000000..ff295ad --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntityList.cs @@ -0,0 +1,13 @@ +namespace DesktopTools.Interfaces +{ + /// + /// параметры для контрола-списка + /// + public interface IControlEntityList : IControl + { + /// + /// Ссылка на контро для элемента + /// + IControlChildEntity ControlViewEntityElement { get; } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntitySelectable.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntitySelectable.cs new file mode 100644 index 0000000..fcb464b --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlEntitySelectable.cs @@ -0,0 +1,27 @@ +using System; + +namespace DesktopTools.Interfaces +{ + /// + /// Методы для работы с контролом при выборе элемента из списка + /// + public interface IControlEntitySelectable : IControl + { + /// + /// Идентификатор выбранной записи + /// + Guid? SelectedId { get; } + + /// + /// Название выбранной записи + /// + string SelectedText { get; } + + /// + /// Получение имене элемента по иденификатору + /// + /// + /// + string GetTitleFromId(Guid id); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityElement.cs new file mode 100644 index 0000000..7aaecfd --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityElement.cs @@ -0,0 +1,22 @@ +using DesktopTools.Models; + +namespace DesktopTools.Interfaces +{ + /// + /// Работа с контролом элемента + /// + public interface IControlViewEntityElement + { + /// + /// Открытие формы + /// + /// + void OpenControl(ControlOpenModel model); + + /// + /// Новый экземпляр контрола + /// + /// + IControl GetInstanceControl(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityList.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityList.cs new file mode 100644 index 0000000..0720e52 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IControlViewEntityList.cs @@ -0,0 +1,29 @@ +using DesktopTools.Models; +using System; + +namespace DesktopTools.Interfaces +{ + /// + /// Работа с контролом списка + /// + public interface IControlViewEntityList : IControl + { + /// + /// Открытие формы + /// + /// + void OpenControl(ControlOpenModel model); + + /// + /// Новый экземпляр контрола + /// + /// + IControl GetInstanceControl(); + + /// + /// Получение названиия объекта по его идентификатору + /// + /// + string GetTitleFromIdControl(Guid id); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityElement.cs new file mode 100644 index 0000000..4f92374 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityElement.cs @@ -0,0 +1,14 @@ +namespace DesktopTools.Interfaces +{ + /// + /// Работа с generic-контролом элемента + /// + public interface IGenericControlEntityElement + { + /// + /// Новый экземпляр контрола + /// + /// + IControl GetInstanceGenericControl(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityList.cs new file mode 100644 index 0000000..179e103 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Interfaces/IGenericControlEntityList.cs @@ -0,0 +1,54 @@ +using DesktopTools.Models; +using ModuleTools.ViewModels; +using System; + +namespace DesktopTools.Interfaces +{ + /// + /// Работа с generic-контролом списка + /// + public interface IGenericControlEntityList + where L : ListViewModel + where E : ElementViewModel + { + /// + /// Новый экземпляр контрола + /// + /// + IControl GetInstanceGenericControl(); + + /// + /// Получение настроек + /// + /// + ControlViewEntityListConfiguration GetConfigControl(); + + /// + /// Получение полного списка + /// + /// + L GetDataForControl(); + + /// + /// Получение списка с пагинацией по названиям + /// + /// + /// + L GetDataWithPageNameForControl(string key); + + /// + /// Получение списка с пагинацией по страницам + /// + /// + /// + /// + L GetDataWithPageNumberForControl(int page, int count); + + /// + /// Получение списка от родителя + /// + /// + /// + L GetDataFromParentForControl(Guid id); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.Designer.cs similarity index 80% rename from DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs rename to DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.Designer.cs index 5a5ec29..e41a38b 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.Designer.cs @@ -29,6 +29,9 @@ namespace DesktopTools.Controls this.toolStripButtonReload = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton(); this.panelContainer = new System.Windows.Forms.Panel(); + this.tabControl = new System.Windows.Forms.TabControl(); + this.tabPageMain = new System.Windows.Forms.TabPage(); + this.tabControl.SuspendLayout(); this.toolStripActions.SuspendLayout(); this.SuspendLayout(); // @@ -81,16 +84,38 @@ namespace DesktopTools.Controls this.panelContainer.Size = new System.Drawing.Size(594, 485); this.panelContainer.TabIndex = 1; // + // tabControl + // + this.tabControl.Controls.Add(this.tabPageMain); + this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill; + this.tabControl.Location = new System.Drawing.Point(218, 141); + this.tabControl.Name = "tabControl"; + this.tabControl.SelectedIndex = 0; + this.tabControl.Size = new System.Drawing.Size(130, 127); + this.tabControl.TabIndex = 0; + // + // tabPageMain + // + this.tabPageMain.Location = new System.Drawing.Point(4, 24); + this.tabPageMain.Name = "tabPageMain"; + this.tabPageMain.Padding = new System.Windows.Forms.Padding(3); + this.tabPageMain.Size = new System.Drawing.Size(122, 99); + this.tabPageMain.TabIndex = 0; + this.tabPageMain.Text = "Свойства элемента"; + this.tabPageMain.UseVisualStyleBackColor = true; + // // GenericControlEntityElement // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.tabControl); this.Controls.Add(this.panelContainer); this.Controls.Add(this.toolStripActions); this.Name = "GenericControlEntityElement"; this.Size = new System.Drawing.Size(594, 510); this.toolStripActions.ResumeLayout(false); this.toolStripActions.PerformLayout(); + this.tabControl.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); @@ -103,5 +128,7 @@ namespace DesktopTools.Controls private System.Windows.Forms.ToolStripButton toolStripButtonReload; private System.Windows.Forms.ToolStripButton toolStripButtonClose; private System.Windows.Forms.Panel panelContainer; + private System.Windows.Forms.TabControl tabControl; + private System.Windows.Forms.TabPage tabPageMain; } } diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs new file mode 100644 index 0000000..ac5534d --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs @@ -0,0 +1,340 @@ +using DesktopTools.BaseControls; +using DesktopTools.Enums; +using DesktopTools.Helpers; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; +using ModuleTools.BusinessLogics; +using ModuleTools.Enums; +using ModuleTools.Extensions; +using ModuleTools.ViewModels; +using System; +using System.Linq; +using System.Reflection; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class GenericControlEntityElement : MainControlViewEntityElement, IControlViewEntityElement + where G : GetBindingModel, new() + where S : SetBindingModel, new() + where L : ListViewModel + where E : ElementViewModel + where BL : GenericBusinessLogic + { + /// + /// Объект бизнес-логики для получения данных + /// + private readonly BL _businessLogic; + + /// + /// Методы для реализации в generic-контроле + /// + protected IGenericControlEntityElement _genericControlViewEntityElement; + + /// + /// Признак налиичия изменений + /// + private bool _haveChages = false; + + /// + /// Ширина контрола по умолчанию + /// + private readonly int _defaultControlWidth = 350; + + private E _element = null; + + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseElementEvent; + + private event Action SetTitleWidth; + + private event Action SetValues; + + private event Action DropValues; + + private event Func CheckValues; + + private event Action GetValues; + + private E Element + { + get { return _element; } + set + { + try + { + _element = value; + SetValues?.Invoke(_element); + if (tabControl.Visible) + { + foreach (TabPage page in tabControl.TabPages) + { + if (page.Name == tabPageMain.Name) + { + continue; + } + if (page.Controls[0] is IControlChildEntity cntrl) + { + cntrl.ParentObject = _element; + cntrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.Child }); + } + } + } + _haveChages = false; + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при установки значений"); + } + } + } + + public GenericControlEntityElement() + { + InitializeComponent(); + InitEvents(); + _businessLogic = DependencyManager.Instance.Resolve(); + _controlViewEntityElement = this; + } + + public void OpenControl(ControlOpenModel model) + { + if (model.CloseElement != null) + { + CloseElementEvent += model.CloseElement; + } + if (panelContainer.Controls.Count == 0) + { + try + { + Configurate(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при конфигурации"); + } + } + if (model.ElementId.HasValue) + { + Element = _businessLogic.GetElement(new G { Id = model.ElementId }); + if (Element == null) + { + DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при получении элемента"); + } + } + Dock = DockStyle.Fill; + } + + private void InitEvents() + { + toolStripButtonSave.Click += (object sender, EventArgs e) => { Save(); }; + toolStripButtonReload.Click += (object sender, EventArgs e) => + { + if (DialogHelper.MessageQuestion("Отменить все внесенные изменения?") == DialogResult.Yes) + { + try + { + DropValues?.Invoke(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при сбросе значений"); + } + } + }; + toolStripButtonClose.Click += (object sender, EventArgs e) => { + if (_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == DialogResult.Yes) + { + if (Save()) + { + return; + } + } + CloseElementEvent?.Invoke(ControlId); + Dispose(); + }; + } + + private void Configurate() + { + var attributeClass = typeof(E).GetCustomAttribute(); + if (attributeClass == null) + { + return; + } + tabControl.Visible = attributeClass.HaveDependenceEntities; + panelContainer.Visible = !attributeClass.HaveDependenceEntities; + Width = attributeClass.Width != 0 ? attributeClass.Width : _defaultControlWidth; + + int positionY = 5; + int positionX = 5; + int interval = 15; + + int titleWidth = 0; + + foreach (var property in typeof(E).GetProperties()) + { + var attribute = property.GetCustomAttribute(); + if (attribute != null) + { + AbstractBaseControl control = null; + switch (attribute.ControlType) + { + case ControlType.ControlString: + control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength); + break; + case ControlType.ControlText: + control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height); + break; + case ControlType.ControlInt: + control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue); + break; + case ControlType.ControlDecimal: + control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, + attribute.MaxValue, attribute.DecimalPlaces); + break; + case ControlType.ControlBool: + control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly); + break; + case ControlType.ControlDateTime: + control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate, + attribute.MaxDate, attribute.CustomDateFormat); + break; + case ControlType.ControlImage: + control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height); + break; + case ControlType.ControlEnum: + control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType); + break; + case ControlType.ControlGuid: + if (attribute.ControlTypeObject.IsNotEmpty()) + { + control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly, + DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as IControlEntitySelectable, + property.Name == ParentPropertyName ? ParentId : null); + } + break; + } + if (control == null) + { + continue; + } + + var widthTitle = control.SetTitle(attribute.DisplayName); + if (widthTitle > titleWidth) + { + titleWidth = widthTitle; + } + + control.OnValueChangeEvent += () => { _haveChages = true; }; + SetValues += control.SetValue; + DropValues += control.DropValue; + CheckValues += control.CheckValue; + SetTitleWidth += control.SetTitleWidth; + GetValues += control.GetValue; + + control.Location = new System.Drawing.Point(positionX, positionY); + control.Width = Width - positionX * 2 - (tabControl.Visible ? 10 : 0); + control.Anchor = AnchorStyles.Top | AnchorStyles.Left; + if (panelContainer.Visible) + { + control.Anchor |= AnchorStyles.Right; + } + positionY += control.Height + interval; + + if (panelContainer.Visible) + { + panelContainer.Controls.Add(control); + } + if (tabControl.Visible) + { + tabPageMain.Controls.Add(control); + } + } + } + + SetTitleWidth(titleWidth); + Height = attributeClass.Height != 0 ? attributeClass.Height : positionY; + + if (attributeClass.HaveDependenceEntities) + { + var attrDependences = typeof(E).GetCustomAttributes(); + if (attrDependences != null) + { + foreach (var attr in attrDependences) + { + if (DependencyManager.Instance.Resolve(Type.GetType(attr.ControlTypeObject)) is IControlChildEntity control) + { + var cntrl = control.GetInstance() as IControlChildEntity; + cntrl.ParentPropertyName = attr.ParentPropertyName; + //cntrl.Open(null); + var tabPage = new TabPage + { + Location = new System.Drawing.Point(4, 24), + Name = "tabPage", + Padding = new Padding(3), + Size = new System.Drawing.Size(122, 99), + TabIndex = 0, + Text = attr.Title, + UseVisualStyleBackColor = true + }; + tabPage.Controls.Add(cntrl as UserControl); + + tabControl.TabPages.Add(tabPage); + if (attr.IsActive) + { + tabPage.Select(); + } + } + } + } + } + } + + public bool Save() + { + if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) + { + return false; + } + var model = Element == null ? new S() : Mapper.MapToClass(Element, true); + try + { + GetValues(model); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); + } + + if (model != null) + { + if (Element == null) + { + Element = _businessLogic.Create(model); + } + else + { + Element = _businessLogic.Update(model); + } + + if (Element == null) + { + DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении элемента"); + } + + _haveChages = false; + DialogHelper.MessageInformation("Сохранение прошло успешно", "Сообщение"); + return true; + } + + return false; + } + + public IControl GetInstanceControl() => _genericControlViewEntityElement?.GetInstanceGenericControl(); + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.resx b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.resx similarity index 100% rename from DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.resx rename to DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.resx diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.Designer.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.Designer.cs similarity index 67% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.Designer.cs rename to DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.Designer.cs index 324f614..71998d3 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.Designer.cs @@ -1,6 +1,6 @@ namespace DesktopTools.Controls { - partial class AbstractGenericControlEntityList + partial class GenericControlEntityList { /// /// Освободить все используемые ресурсы. @@ -23,7 +23,6 @@ /// private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); this.toolStripMenu = new System.Windows.Forms.ToolStrip(); this.toolStripButtonAdd = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); @@ -37,21 +36,30 @@ this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSplitButtonActions = new System.Windows.Forms.ToolStripSplitButton(); this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton(); + this.labelTitle = new System.Windows.Forms.Label(); + this.panelHeader = new System.Windows.Forms.Panel(); this.panelSearch = new System.Windows.Forms.Panel(); - this.buttonCancelSearch = new System.Windows.Forms.Button(); + this.panelSearchControls = new System.Windows.Forms.Panel(); + this.panelSearchActions = new System.Windows.Forms.Panel(); this.buttonSearch = new System.Windows.Forms.Button(); + this.buttonCancelSearch = new System.Windows.Forms.Button(); this.toolStripFooter = new System.Windows.Forms.ToolStrip(); this.toolStripButtonPrev = new System.Windows.Forms.ToolStripButton(); this.toolStripLabelPage = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBoxPage = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabelCountPages = new System.Windows.Forms.ToolStripLabel(); + this.toolStripLabelCountRecords = new System.Windows.Forms.ToolStripLabel(); + this.toolStripTextBoxCountRecords = new System.Windows.Forms.ToolStripTextBox(); this.toolStripButtonNext = new System.Windows.Forms.ToolStripButton(); this.toolStripLabelPageName = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBoxPageNames = new System.Windows.Forms.ToolStripComboBox(); - this.contextMenuStripDataGrid = new System.Windows.Forms.ContextMenuStrip(this.components); this.dataGridViewList = new System.Windows.Forms.DataGridView(); + this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); + this.toolStripButtonSelect = new System.Windows.Forms.ToolStripButton(); this.toolStripMenu.SuspendLayout(); + this.panelHeader.SuspendLayout(); this.panelSearch.SuspendLayout(); + this.panelSearchActions.SuspendLayout(); this.toolStripFooter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewList)).BeginInit(); this.SuspendLayout(); @@ -70,8 +78,10 @@ this.toolStripButtonRef, this.toolStripSeparator5, this.toolStripSplitButtonActions, + this.toolStripSeparator6, + this.toolStripButtonSelect, this.toolStripButtonClose}); - this.toolStripMenu.Location = new System.Drawing.Point(0, 0); + this.toolStripMenu.Location = new System.Drawing.Point(0, 30); this.toolStripMenu.Name = "toolStripMenu"; this.toolStripMenu.Size = new System.Drawing.Size(1000, 25); this.toolStripMenu.TabIndex = 0; @@ -160,35 +170,73 @@ this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22); this.toolStripButtonClose.Text = "Закрть"; // + // labelTitle + // + this.labelTitle.Dock = System.Windows.Forms.DockStyle.Fill; + this.labelTitle.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); + this.labelTitle.Location = new System.Drawing.Point(0, 0); + this.labelTitle.Name = "labelTitle"; + this.labelTitle.Size = new System.Drawing.Size(1000, 30); + this.labelTitle.TabIndex = 0; + this.labelTitle.Text = "Сущность"; + this.labelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // panelHeader + // + this.panelHeader.Controls.Add(this.labelTitle); + this.panelHeader.Dock = System.Windows.Forms.DockStyle.Top; + this.panelHeader.Location = new System.Drawing.Point(0, 0); + this.panelHeader.Name = "panelHeader"; + this.panelHeader.Size = new System.Drawing.Size(1000, 30); + this.panelHeader.TabIndex = 1; + // // panelSearch // - this.panelSearch.Controls.Add(this.buttonCancelSearch); - this.panelSearch.Controls.Add(this.buttonSearch); + this.panelSearch.Controls.Add(this.panelSearchControls); + this.panelSearch.Controls.Add(this.panelSearchActions); this.panelSearch.Dock = System.Windows.Forms.DockStyle.Top; - this.panelSearch.Location = new System.Drawing.Point(0, 25); + this.panelSearch.Location = new System.Drawing.Point(0, 55); this.panelSearch.Name = "panelSearch"; this.panelSearch.Size = new System.Drawing.Size(1000, 87); this.panelSearch.TabIndex = 1; this.panelSearch.Visible = false; // - // buttonCancelSearch + // panelSearchControls // - this.buttonCancelSearch.Location = new System.Drawing.Point(11, 47); - this.buttonCancelSearch.Name = "buttonCancelSearch"; - this.buttonCancelSearch.Size = new System.Drawing.Size(89, 24); - this.buttonCancelSearch.TabIndex = 1; - this.buttonCancelSearch.Text = "Скрыть"; - this.buttonCancelSearch.UseVisualStyleBackColor = true; + this.panelSearchControls.Dock = System.Windows.Forms.DockStyle.Fill; + this.panelSearchControls.Location = new System.Drawing.Point(118, 0); + this.panelSearchControls.Name = "panelSearchControls"; + this.panelSearchControls.Size = new System.Drawing.Size(882, 87); + this.panelSearchControls.TabIndex = 1; + // + // panelSearchActions + // + this.panelSearchActions.Controls.Add(this.buttonSearch); + this.panelSearchActions.Controls.Add(this.buttonCancelSearch); + this.panelSearchActions.Dock = System.Windows.Forms.DockStyle.Left; + this.panelSearchActions.Location = new System.Drawing.Point(0, 0); + this.panelSearchActions.Name = "panelSearchActions"; + this.panelSearchActions.Size = new System.Drawing.Size(118, 87); + this.panelSearchActions.TabIndex = 0; // // buttonSearch // - this.buttonSearch.Location = new System.Drawing.Point(11, 13); + this.buttonSearch.Location = new System.Drawing.Point(13, 14); this.buttonSearch.Name = "buttonSearch"; this.buttonSearch.Size = new System.Drawing.Size(89, 24); this.buttonSearch.TabIndex = 0; this.buttonSearch.Text = "Запуск"; this.buttonSearch.UseVisualStyleBackColor = true; // + // buttonCancelSearch + // + this.buttonCancelSearch.Location = new System.Drawing.Point(13, 48); + this.buttonCancelSearch.Name = "buttonCancelSearch"; + this.buttonCancelSearch.Size = new System.Drawing.Size(89, 24); + this.buttonCancelSearch.TabIndex = 1; + this.buttonCancelSearch.Text = "Скрыть"; + this.buttonCancelSearch.UseVisualStyleBackColor = true; + // // toolStripFooter // this.toolStripFooter.Dock = System.Windows.Forms.DockStyle.Bottom; @@ -197,6 +245,8 @@ this.toolStripLabelPage, this.toolStripTextBoxPage, this.toolStripLabelCountPages, + this.toolStripLabelCountRecords, + this.toolStripTextBoxCountRecords, this.toolStripButtonNext, this.toolStripLabelPageName, this.toolStripComboBoxPageNames}); @@ -233,6 +283,18 @@ this.toolStripLabelCountPages.Size = new System.Drawing.Size(28, 22); this.toolStripLabelCountPages.Text = "из 0"; // + // toolStripLabelCountRecords + // + this.toolStripLabelCountRecords.Name = "toolStripLabelCountRecords"; + this.toolStripLabelCountRecords.Size = new System.Drawing.Size(21, 22); + this.toolStripLabelCountRecords.Text = "по"; + // + // toolStripTextBoxCountRecords + // + this.toolStripTextBoxCountRecords.Name = "toolStripTextBoxCountRecords"; + this.toolStripTextBoxCountRecords.Size = new System.Drawing.Size(30, 25); + this.toolStripTextBoxCountRecords.Text = "1"; + // // toolStripButtonNext // this.toolStripButtonNext.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; @@ -250,14 +312,9 @@ // // toolStripComboBoxPageNames // + this.toolStripComboBoxPageNames.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBoxPageNames.Name = "toolStripComboBoxPageNames"; this.toolStripComboBoxPageNames.Size = new System.Drawing.Size(200, 25); - this.toolStripComboBoxPageNames.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - // - // contextMenuStripDataGrid - // - this.contextMenuStripDataGrid.Name = "contextMenuStripDataGrid"; - this.contextMenuStripDataGrid.Size = new System.Drawing.Size(61, 4); // // dataGridViewList // @@ -266,18 +323,32 @@ this.dataGridViewList.AllowUserToResizeRows = false; this.dataGridViewList.BackgroundColor = System.Drawing.SystemColors.ControlLightLight; this.dataGridViewList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridViewList.ContextMenuStrip = this.contextMenuStripDataGrid; this.dataGridViewList.Dock = System.Windows.Forms.DockStyle.Fill; - this.dataGridViewList.Location = new System.Drawing.Point(0, 112); + this.dataGridViewList.Location = new System.Drawing.Point(0, 142); this.dataGridViewList.Name = "dataGridViewList"; this.dataGridViewList.ReadOnly = true; this.dataGridViewList.RowHeadersVisible = false; this.dataGridViewList.RowTemplate.Height = 25; this.dataGridViewList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.dataGridViewList.Size = new System.Drawing.Size(1000, 663); + this.dataGridViewList.Size = new System.Drawing.Size(1000, 633); this.dataGridViewList.TabIndex = 3; // - // AbstractControlEntityList + // toolStripSeparator6 + // + this.toolStripSeparator6.Name = "toolStripSeparator6"; + this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); + this.toolStripSeparator6.Visible = false; + // + // toolStripButtonSelect + // + this.toolStripButtonSelect.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + this.toolStripButtonSelect.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButtonSelect.Name = "toolStripButtonSelect"; + this.toolStripButtonSelect.Size = new System.Drawing.Size(58, 22); + this.toolStripButtonSelect.Text = "Выбрать"; + this.toolStripButtonSelect.Visible = false; + // + // GenericControlEntityList // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; @@ -285,11 +356,14 @@ this.Controls.Add(this.toolStripFooter); this.Controls.Add(this.panelSearch); this.Controls.Add(this.toolStripMenu); - this.Name = "AbstractControlEntityList"; + this.Controls.Add(this.panelHeader); + this.Name = "GenericControlEntityList"; this.Size = new System.Drawing.Size(1000, 800); this.toolStripMenu.ResumeLayout(false); this.toolStripMenu.PerformLayout(); + this.panelHeader.ResumeLayout(false); this.panelSearch.ResumeLayout(false); + this.panelSearchActions.ResumeLayout(false); this.toolStripFooter.ResumeLayout(false); this.toolStripFooter.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewList)).EndInit(); @@ -300,31 +374,39 @@ #endregion - private System.Windows.Forms.ToolStrip toolStripMenu; - private System.Windows.Forms.ToolStripButton toolStripButtonAdd; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; - private System.Windows.Forms.ToolStripButton toolStripButtonUpd; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; - private System.Windows.Forms.ToolStripButton toolStripButtonDel; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; - private System.Windows.Forms.ToolStripButton toolStripButtonSearch; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; - private System.Windows.Forms.ToolStripButton toolStripButtonRef; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; - private System.Windows.Forms.ToolStripSplitButton toolStripSplitButtonActions; - private System.Windows.Forms.ToolStripButton toolStripButtonClose; + protected System.Windows.Forms.ToolStrip toolStripMenu; + protected System.Windows.Forms.ToolStripButton toolStripButtonAdd; + protected System.Windows.Forms.ToolStripSeparator toolStripSeparator1; + protected System.Windows.Forms.ToolStripButton toolStripButtonUpd; + protected System.Windows.Forms.ToolStripSeparator toolStripSeparator2; + protected System.Windows.Forms.ToolStripButton toolStripButtonDel; + protected System.Windows.Forms.ToolStripSeparator toolStripSeparator3; + protected System.Windows.Forms.ToolStripButton toolStripButtonSearch; + protected System.Windows.Forms.ToolStripSeparator toolStripSeparator4; + protected System.Windows.Forms.ToolStripButton toolStripButtonRef; + protected System.Windows.Forms.ToolStripSeparator toolStripSeparator5; + protected System.Windows.Forms.ToolStripSplitButton toolStripSplitButtonActions; + protected System.Windows.Forms.ToolStripButton toolStripButtonClose; + protected System.Windows.Forms.Label labelTitle; + protected System.Windows.Forms.Panel panelHeader; protected System.Windows.Forms.Panel panelSearch; - private System.Windows.Forms.Button buttonCancelSearch; - private System.Windows.Forms.Button buttonSearch; - private System.Windows.Forms.ToolStrip toolStripFooter; - private System.Windows.Forms.ToolStripButton toolStripButtonPrev; - private System.Windows.Forms.ToolStripLabel toolStripLabelPage; - private System.Windows.Forms.ToolStripTextBox toolStripTextBoxPage; - private System.Windows.Forms.ToolStripLabel toolStripLabelCountPages; - private System.Windows.Forms.ToolStripButton toolStripButtonNext; - private System.Windows.Forms.ToolStripLabel toolStripLabelPageName; - private System.Windows.Forms.ToolStripComboBox toolStripComboBoxPageNames; - private System.Windows.Forms.ContextMenuStrip contextMenuStripDataGrid; - private System.Windows.Forms.DataGridView dataGridViewList; + protected System.Windows.Forms.Button buttonCancelSearch; + protected System.Windows.Forms.Button buttonSearch; + protected System.Windows.Forms.ToolStrip toolStripFooter; + protected System.Windows.Forms.ToolStripButton toolStripButtonPrev; + protected System.Windows.Forms.ToolStripLabel toolStripLabelPage; + protected System.Windows.Forms.ToolStripTextBox toolStripTextBoxPage; + protected System.Windows.Forms.ToolStripLabel toolStripLabelCountPages; + protected System.Windows.Forms.ToolStripLabel toolStripLabelCountRecords; + protected System.Windows.Forms.ToolStripTextBox toolStripTextBoxCountRecords; + protected System.Windows.Forms.ToolStripButton toolStripButtonNext; + protected System.Windows.Forms.ToolStripLabel toolStripLabelPageName; + protected System.Windows.Forms.ToolStripComboBox toolStripComboBoxPageNames; + protected System.Windows.Forms.ContextMenuStrip contextMenuStripDataGrid; + protected System.Windows.Forms.DataGridView dataGridViewList; + private System.Windows.Forms.Panel panelSearchActions; + protected System.Windows.Forms.Panel panelSearchControls; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; + private System.Windows.Forms.ToolStripButton toolStripButtonSelect; } } diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs new file mode 100644 index 0000000..b0bf6c4 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs @@ -0,0 +1,550 @@ +using DesktopTools.Enums; +using DesktopTools.Helpers; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; +using ModuleTools.BusinessLogics; +using ModuleTools.Extensions; +using ModuleTools.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class GenericControlEntityList : MainControlViewEntityList, IControlViewEntityList + where G : GetBindingModel, new() + where S : SetBindingModel, new() + where L : ListViewModel + where E : ElementViewModel + where BL : GenericBusinessLogic + { + /// + /// Режим работы + /// + private ControlOpenMode _openMode; + + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseListEvent; + + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseSelectEvent; + + /// + /// Объект бизнес-логики для получения данных + /// + protected BL _businessLogic; + + /// + /// Методы для реализации в generic-контроле + /// + protected IGenericControlEntityList _genericControlViewEntityList; + + /// + /// Список значений с контролов с панели поиска + /// + protected List<(string Name, object Value)> _searchValues; + + /// + /// Констркутор + /// + public GenericControlEntityList() + { + InitializeComponent(); + InitEvents(); + _businessLogic = DependencyManager.Instance.Resolve(); + _controlViewEntityList = this; + } + + #region IControlViewEntityList + public async void OpenControl(ControlOpenModel model) + { + _openMode = model.OpenMode; + if (model.CloseList != null) + { + CloseListEvent += model.CloseList; + } + if (model.CloseSelect != null) + { + CloseSelectEvent += model.CloseSelect; + } + + if (dataGridViewList.Columns.Count == 0) + { + try + { + Configurate(GetConfig()); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при конфигурации"); + } + } + await LoadListAsync(); + } + + public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl(); + + public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString(); + #endregion + + /// + /// Конфигуратор контрола + /// + /// Настройки + private void Configurate(ControlViewEntityListConfiguration config) + { + if (config == null) + { + return; + } + + // формирование таблицы на основе модели + dataGridViewList.Columns.Clear(); + var properties = typeof(E).GetProperties(); + foreach (var property in properties) + { + var attr = property.GetCustomAttribute(); + if (attr != null) + { + var colIndex = attr.DisplayName == "Идентификатор" ? 0 : dataGridViewList.Columns.Count; + dataGridViewList.Columns.Insert(colIndex, new DataGridViewTextBoxColumn + { + HeaderText = attr.DisplayName, + Name = string.Format("Column{0}", property.Name), + ReadOnly = true, + Visible = !attr.IsHide, + Width = attr.ColumnWidth ?? 0, + AutoSizeMode = attr.ColumnWidth.HasValue ? DataGridViewAutoSizeColumnMode.None : DataGridViewAutoSizeColumnMode.Fill + }); + } + } + + labelTitle.Text = Title; + // настройка отображения основных кнопок + if (config.HideToolStripButton != null) + { + foreach (var elem in config.HideToolStripButton) + { + var ctrl = toolStripMenu.Items.Find(elem.ToString(), false); + if (ctrl != null && ctrl.Length > 0) + { + ctrl[0].Visible = false; + switch (elem) + { + case ToolStripButtonListNames.toolStripButtonAdd: + toolStripSeparator1.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonUpd: + toolStripSeparator2.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonDel: + toolStripSeparator3.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonSearch: + toolStripSeparator4.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonRef: + toolStripSeparator5.Visible = false; + break; + } + } + } + } + // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" + if (config.ControlOnMoveElem != null) + { + foreach (var elem in config.ControlOnMoveElem) + { + ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key }; + item.Click += elem.Value.Event; + toolStripSplitButtonActions.DropDownItems.Add(item); + contextMenuStripDataGrid.Items.Add(item); + } + } + // либо скрытие пункта, если не предусмотренно подпунктов + else + { + toolStripSplitButtonActions.Visible = false; + toolStripSeparator5.Visible = false; + } + + toolStripFooter.Visible = config.PaginationOn; + // Пагинация + if (config.PaginationOn) + { + // пагинация по страницам + if (config.CountElementsOnPage.HasValue) + { + toolStripTextBoxCountRecords.Text = config.CountElementsOnPage.Value.ToString(); + toolStripLabelPageName.Visible = toolStripComboBoxPageNames.Visible = false; + } + // пагинация по названиям + else if (config.PageNamesForPagination != null) + { + toolStripButtonPrev.Visible = toolStripLabelPage.Visible = toolStripTextBoxPage.Visible = toolStripLabelCountPages.Visible = + toolStripLabelCountRecords.Visible = toolStripTextBoxCountRecords.Visible = toolStripButtonNext.Visible = false; + + toolStripComboBoxPageNames.Items.AddRange(config.PageNamesForPagination.ToArray()); + toolStripComboBoxPageNames.SelectedIndex = 0; + toolStripComboBoxPageNames.Tag = config.ParentPropertyName; + } + } + + // при вызове контрола для выбора элемента, делаем возможность выбора только одной записи + dataGridViewList.MultiSelect = _openMode == ControlOpenMode.List; + + // Открытие через родительский элемент + if (_openMode == ControlOpenMode.Child) + { + panelHeader.Visible = false; + toolStripButtonClose.Visible = false; + toolStripFooter.Visible = false; + toolStripSeparator6.Visible = true; + toolStripButtonSelect.Visible = true; + } + + Dock = DockStyle.Fill; + } + + /// + /// Инициализация событий к контролам + /// + private void InitEvents() + { + toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); }; + toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); }; + toolStripButtonDel.Click += (object sender, EventArgs e) => { DelElement(); }; + toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; _searchValues?.Clear(); }; + toolStripButtonRef.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; + toolStripButtonSelect.Click += (object sender, EventArgs e) => { SelectElement(); }; + toolStripButtonClose.Click += (object sender, EventArgs e) => + { + CloseListEvent?.Invoke(ControlId); + CloseSelectEvent?.Invoke(false); + Dispose(); + }; + + buttonSearch.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; + buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; _searchValues?.Clear(); }; + + dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => + { + switch (e.KeyCode) + { + case Keys.Insert: + if (toolStripButtonAdd.Visible) + { + AddElement(); + } + break; + case Keys.Enter: + if (toolStripButtonUpd.Visible) + { + UpdElement(); + } + break; + case Keys.Delete: + if (toolStripButtonDel.Visible) + { + DelElement(); + } + break; + } + }; + dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) => + { + if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0) + { + SelectElement(); + } + UpdElement(); + }; + + toolStripButtonPrev.Click += async (object sender, EventArgs e) => + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page)) + { + toolStripTextBoxPage.Text = (page - 1).ToString(); + await LoadListAsync(); + } + }; + toolStripButtonNext.Click += async (object sender, EventArgs e) => + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page)) + { + toolStripTextBoxPage.Text = (page + 1).ToString(); + await LoadListAsync(); + } + }; + toolStripTextBoxPage.KeyDown += async (object sender, KeyEventArgs e) => + { + if (e.KeyData == Keys.Enter) + { + await LoadListAsync(); + } + }; + + toolStripComboBoxPageNames.SelectedIndexChanged += async (object sender, EventArgs e) => { await LoadListAsync(); }; + } + + /// + /// Вызов события загрузки данных на datagrid + /// + private async Task LoadListAsync() + { + var cursor = Cursor.Current; + + var selectedGuids = new List(); + foreach (DataGridViewRow row in dataGridViewList.SelectedRows) + { + selectedGuids.Add(new Guid(row.Cells[0].Value.ToString())); + } + + L data = null; + try + { + Cursor.Current = Cursors.WaitCursor; + if (panelSearch.Visible) + { + var controls = panelSearchControls.Controls.Cast(); + if (_searchValues == null) + { + _searchValues = new(); + } + _searchValues.Clear(); + + foreach (var cntrl in controls) + { + _searchValues.Add((cntrl.GetPropertyName(), cntrl.GetValueFromControl())); + } + } + + if (ParentPropertyName.IsNotEmpty()) + { + if (ParentObject != null) + { + var property = ParentObject.GetType().GetProperty("Id"); + if (property != null) + { + await Task.Run(() => data = GetDataFromParent(new Guid(property.GetValue(ParentObject).ToString()))); + } + Visible = true; + } + else + { + Visible = false; + } + } + // если включена пагинация + else if (toolStripFooter.Visible) + { + // постраничная + if (toolStripTextBoxPage.Visible) + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxCountRecords.Text.ToString(), out int count)) + { + await Task.Run(() => data = GetDataWithPageNumber(page - 1, count)); + } + } + // поименная + else if (toolStripComboBoxPageNames.Visible) + { + if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) + { + await Task.Run(() => data = GetDataWithPageName(key.Key)); + } + } + } + else + { + await Task.Run(() => data = GetData()); + } + + toolStripLabelCountPages.Text = $"из {data?.MaxCount}"; + } + catch (Exception ex) + { + if (_businessLogic.Errors.Count > 0) + { + DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при получении данных"); + } + else + { + DialogHelper.MessageException(ex.Message, "Ошибка при получении данных"); + } + } + finally + { + Cursor.Current = cursor; + } + FillDataOnGridAsync(data?.List, selectedGuids); + } + + /// + /// Заполнение таблицы + /// + /// + private void FillDataOnGridAsync(List data, List selectedGuids) + { + if (data == null) + { + return; + } + dataGridViewList.Rows.Clear(); + foreach (var elem in data) + { + var mas = new List(); + foreach (DataGridViewColumn column in dataGridViewList.Columns) + { + mas.Add(elem.GetType().GetProperty(column.Name["Column".Length..])?.GetValue(elem)); + } + + dataGridViewList.Rows.Add(mas.ToArray()); + dataGridViewList.Rows[^1].Selected = selectedGuids.Contains(new Guid(mas[0].ToString())); + } + if (selectedGuids.Count == 0 && dataGridViewList.Rows.Count > 0) + { + dataGridViewList.Rows[0].Selected = true; + } + } + + /// + /// Вызов события при добавлении элемента + /// + private void AddElement() => LaunchControl(null); + + /// + /// Вызов события при изменении элемента + /// + private void UpdElement() + { + foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + { + LaunchControl(new Guid(selected.Cells[0].Value.ToString())); + } + } + + /// + /// Вызов события при удалении элемента + /// + private async void DelElement() + { + if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + var cursor = Cursor.Current; + try + { + Cursor.Current = Cursors.WaitCursor; + foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + { + _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); + } + } + catch (Exception ex) + { + if (_businessLogic.Errors.Count != 0) + { + DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при удалении"); + } + else + { + DialogHelper.MessageException(ex.Message, "Ошибки при удалении"); + } + } + finally + { + Cursor.Current = cursor; + await LoadListAsync(); + } + } + } + + /// + /// Вызов события при выборе элемента + /// + private void SelectElement() + { + try + { + SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); + SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString(); + CloseSelectEvent?.Invoke(true); + Dispose(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при получении выбранного значения"); + } + } + + /// + /// Создание формы с контролом для работы с элементом + /// + /// + private void LaunchControl(Guid? id) + { + try + { + var control = ControlViewEntityElement.GetInstance() as IControlChildEntity; + var property = ParentObject?.GetType()?.GetProperty("Id"); + if (property != null) + { + control.ParentId = new Guid(property.GetValue(ParentObject).ToString()); + control.ParentPropertyName = ParentPropertyName; + } + if (toolStripFooter.Visible && toolStripComboBoxPageNames.Visible) + { + if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) + { + control.ParentId = new Guid(key.Key); + control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString(); + } + } + + var form = new Form + { + Text = (id.HasValue ? $"{Title}. Редактирование" : $"{Title}. Добавление"), + StartPosition = FormStartPosition.CenterScreen, + ControlBox = false + }; + control.Open( new ControlOpenModel + { + OpenMode = ControlOpenMode.List, + ElementId = id, + CloseElement = async (Guid id) => + { + await LoadListAsync(); + form.Close(); + } + }); + form.Height = (control as UserControl).Height + 55; + form.Width = (control as UserControl).Width + 20; + form.Controls.Add(control as UserControl); + form.Show(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибки при открытии элемента"); + } + } + + private ControlViewEntityListConfiguration GetConfig() => _genericControlViewEntityList?.GetConfigControl(); + + private L GetData() => _genericControlViewEntityList?.GetDataForControl(); + + private L GetDataWithPageName(string key) => _genericControlViewEntityList?.GetDataWithPageNameForControl(key); + + private L GetDataWithPageNumber(int page, int count) => _genericControlViewEntityList?.GetDataWithPageNumberForControl(page, count); + + private L GetDataFromParent(Guid id) => _genericControlViewEntityList?.GetDataFromParentForControl(id); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.resx b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.resx similarity index 79% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.resx rename to DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.resx index f298a7b..48f4a54 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenericControlEntityList.resx +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.resx @@ -57,4 +57,14 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACRSURBVDhPY/j27dt/SjDYACcnJ7IwigEf3n8kCZNswPNb + J/+f6DYF0yA+yQac6Db5f6hWCmwIiE+mC0wIu2DS2Vf/F1x6DefjwlgNyNr34r/0wkdgTMgQDAOQNRNj + CIoBOg0rMTTDMLIhIHbriZeYBmDTiIxBGkEYxge5liQDsGGQqykyAISpZwAlmIEywMAAAAc1/Jwvt6sN + AAAAAElFTkSuQmCC + + \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.Designer.cs b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.Designer.cs similarity index 90% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.Designer.cs rename to DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.Designer.cs index ceb0f5b..32571a7 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.Designer.cs @@ -1,7 +1,7 @@  namespace DesktopTools.Controls { - partial class AbstractControlViewEntityElement + partial class MainControlViewEntityElement { /// /// Обязательная переменная конструктора. @@ -31,11 +31,11 @@ namespace DesktopTools.Controls { this.SuspendLayout(); // - // BaseControlViewEntityElement + // AbstractControlViewEntityElement // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Name = "BaseControlViewEntityElement"; + this.Name = "AbstractControlViewEntityElement"; this.Size = new System.Drawing.Size(695, 578); this.ResumeLayout(false); diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.cs b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.cs new file mode 100644 index 0000000..d571721 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.cs @@ -0,0 +1,42 @@ +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using System; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class MainControlViewEntityElement : UserControl, IControl, IControlChildEntity + { + /// + /// Методы для реализации в generic-контроле + /// + protected IControlViewEntityElement _controlViewEntityElement; + + #region IControlEntity + public Guid ControlId { get; protected set; } + + public string Title { get; protected set; } + + public AccessOperation AccessOperation { get; protected set; } + + public void Open(ControlOpenModel model) => _controlViewEntityElement?.OpenControl(model); + + public IControl GetInstance() => _controlViewEntityElement?.GetInstanceControl(); + + #endregion + + #region IControlChildEntity + public string ParentPropertyName { get; set; } + + public Guid? ParentId { get; set; } + + public object ParentObject { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + #endregion + + /// + /// Констркутор + /// + public MainControlViewEntityElement() => InitializeComponent(); + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.resx b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.resx similarity index 100% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityElement.resx rename to DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityElement.resx diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.Designer.cs b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.Designer.cs similarity index 96% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.Designer.cs rename to DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.Designer.cs index 220865b..fafb1d7 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.Designer.cs @@ -1,7 +1,7 @@  namespace DesktopTools.Controls { - partial class AbstractControlViewEntityList + partial class MainControlViewEntityList { /// /// Обязательная переменная конструктора. diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.cs b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.cs new file mode 100644 index 0000000..ebac13d --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.cs @@ -0,0 +1,53 @@ +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using System; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class MainControlViewEntityList : UserControl, IControl, IControlChildEntity, IControlEntityList, IControlEntitySelectable + { + /// + /// Методы для реализации в generic-контроле + /// + protected IControlViewEntityList _controlViewEntityList; + + #region IControlEntity + public Guid ControlId { get; protected set; } + + public string Title { get; protected set; } + + public AccessOperation AccessOperation { get; protected set; } + + public void Open(ControlOpenModel model) => _controlViewEntityList?.OpenControl(model); + + public IControl GetInstance() => _controlViewEntityList?.GetInstanceControl(); + #endregion + + #region IControlEntityList + public IControlChildEntity ControlViewEntityElement { get; protected set; } + #endregion + + #region IControlChildEntity + public string ParentPropertyName { get; set; } + + public object ParentObject { get; set; } + + public Guid? ParentId { get; set; } + #endregion + + #region ISelectableControlManager + public Guid? SelectedId { get; protected set; } + + public string SelectedText { get; protected set; } + + public string GetTitleFromId(Guid id) => _controlViewEntityList?.GetTitleFromIdControl(id); + #endregion + + /// + /// Констркутор + /// + public MainControlViewEntityList() => InitializeComponent(); + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.resx b/DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.resx similarity index 100% rename from DepartmentPortal/Common/DesktopTools/Controls/AbstractControlViewEntityList.resx rename to DepartmentPortal/Common/DesktopTools/MainControls/MainControlViewEntityList.resx diff --git a/DepartmentPortal/Common/DesktopTools/Models/ControlOpenModel.cs b/DepartmentPortal/Common/DesktopTools/Models/ControlOpenModel.cs new file mode 100644 index 0000000..810fe2f --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Models/ControlOpenModel.cs @@ -0,0 +1,36 @@ +using DesktopTools.Enums; +using System; + +namespace DesktopTools.Models +{ + /// + /// Данные, передаваемый при открытии контрола + /// + public class ControlOpenModel + { + /// + /// Варинат открытия контрола списка + /// + public ControlOpenMode OpenMode { get; set; } + + /// + /// Событипе на закрытие контрола списка, если открыт как список + /// + public Action CloseList { get; set; } + + /// + /// Событипе на закрытие контрола списка, если открыт на выбор + /// + public Action CloseSelect { get; set; } + + /// + /// Событипе на закрытие контрола Элемента + /// + public Action CloseElement { get; set; } + + /// + /// Идентификатор выбранной записи для контрола элемента + /// + public Guid? ElementId { get; set; } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Models/ControlViewEntityListConfiguration.cs b/DepartmentPortal/Common/DesktopTools/Models/ControlViewEntityListConfiguration.cs index 5d52330..e4632bb 100644 --- a/DepartmentPortal/Common/DesktopTools/Models/ControlViewEntityListConfiguration.cs +++ b/DepartmentPortal/Common/DesktopTools/Models/ControlViewEntityListConfiguration.cs @@ -1,4 +1,5 @@ -using System; +using DesktopTools.Enums; +using System; using System.Collections.Generic; namespace DesktopTools.Models @@ -16,7 +17,7 @@ namespace DesktopTools.Models /// /// Список названий кнопок, которые надо скрыть /// - public List ShowToolStripButton { get; set; } + public List HideToolStripButton { get; set; } /// /// Перечень действий для контектснго меню и выпадающего в верхнем меню пункта "Действия" @@ -31,7 +32,12 @@ namespace DesktopTools.Models /// /// Перечень значений для выбора при выводе пагинации по названиям /// - public List PageNamesForPagination { get; set; } = null; + public List PageNamesForPagination { get; set; } = null; + + /// + /// Название свойства в дочернем классе + /// + public string ParentPropertyName { get; set; } /// /// Количество записей на странице (для пагинации) diff --git a/DepartmentPortal/Common/DesktopTools/Models/PageNamesForPaginationModel.cs b/DepartmentPortal/Common/DesktopTools/Models/PageNamesForPaginationModel.cs new file mode 100644 index 0000000..000f521 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Models/PageNamesForPaginationModel.cs @@ -0,0 +1,15 @@ +namespace DesktopTools.Models +{ + /// + /// Модель для выпадабщего списка пагинации + /// + public class PageNamesForPaginationModel + { + public string Key { get; set; } + + public string Value { get; set; } + + public override string ToString() => Value; + + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Models/WindowDesktopExtensionControlModel.cs b/DepartmentPortal/Common/DesktopTools/Models/WindowDesktopExtensionControlModel.cs index 18c6d5a..c93ff23 100644 --- a/DepartmentPortal/Common/DesktopTools/Models/WindowDesktopExtensionControlModel.cs +++ b/DepartmentPortal/Common/DesktopTools/Models/WindowDesktopExtensionControlModel.cs @@ -1,4 +1,4 @@ -using DesktopTools.Controls; +using DesktopTools.Interfaces; using System; namespace DesktopTools.Models @@ -7,10 +7,8 @@ namespace DesktopTools.Models { public Guid Id { get; set; } - public int Order { get; set; } - public string Title { get; set; } - public AbstractControlViewEntityList Control { get; set; } + public IControl Control { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementClassAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementClassAttribute.cs new file mode 100644 index 0000000..7e8d872 --- /dev/null +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementClassAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace ModuleTools.Attributes +{ + /// + /// Настройка контрола отображения объекта класса (требуется для автоматизации вывода элемента, + /// применяется к классам ElementViewModel) + /// + [AttributeUsage(AttributeTargets.Class)] + public class ViewModelControlElementClassAttribute : Attribute + { + /// + /// Ширина контрола + /// + public int Width { get; set; } = 0; + + /// + /// Высота контрола + /// + public int Height { get; set; } = 0; + + /// + /// Имеются зависимые от него сущности, при выводе использовать tabControl + /// + public bool HaveDependenceEntities { get; set; } = false; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementDependenceEntityAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementDependenceEntityAttribute.cs new file mode 100644 index 0000000..9574677 --- /dev/null +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementDependenceEntityAttribute.cs @@ -0,0 +1,37 @@ +using System; + +namespace ModuleTools.Attributes +{ + /// + /// Настройка контрола отображения? указывающая на дочерний контрол (требуется для автоматизации вывода элемента, + /// применяется к классам ElementViewModel) + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public class ViewModelControlElementDependenceEntityAttribute : Attribute + { + /// + /// Заголовок вкладки + /// + public string Title { get; set; } + + /// + /// Порядок вкладки + /// + public int Order { get; set; } = 0; + + /// + /// При открытии элемента отображать с этой вкладки + /// + public bool IsActive { get; set; } = false; + + /// + /// Имя контрола (включая namespace) для вставки контрола во вкладку + /// + public string ControlTypeObject { get; set; } = string.Empty; + + /// + /// Название свойства в дочернем классе, по которму идет связь + /// + public string ParentPropertyName { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementPropertyAttribute.cs similarity index 86% rename from DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs rename to DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementPropertyAttribute.cs index 7a6a233..cd6bc18 100644 --- a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlElementPropertyAttribute.cs @@ -8,7 +8,7 @@ namespace ModuleTools.Attributes /// применяется к классам ElementViewModel) /// [AttributeUsage(AttributeTargets.Property)] - public class ViewModelOnElementPropertyAttribute : Attribute + public class ViewModelControlElementPropertyAttribute : Attribute { /// /// Название на форме @@ -80,17 +80,12 @@ namespace ModuleTools.Attributes /// public string ControlTypeObject { get; set; } = string.Empty; - /// - /// Имя свйоства, где лежит текстовое значение для ссылочного типа (опсанного через Id на другую сущность) - /// - public string PropertyNameForTitle { get; set; } - /// /// Конструктор /// /// Название на форме /// Через какой тип контрола отображать свойство - public ViewModelOnElementPropertyAttribute(string displayName, ControlType controlType) + public ViewModelControlElementPropertyAttribute(string displayName, ControlType controlType) { DisplayName = displayName; ControlType = controlType; @@ -103,7 +98,7 @@ namespace ModuleTools.Attributes /// Через какой тип контрола отображать свойство /// Ширина /// Высота - public ViewModelOnElementPropertyAttribute(string displayName, ControlType controlType, int width, int height) + public ViewModelControlElementPropertyAttribute(string displayName, ControlType controlType, int width, int height) { DisplayName = displayName; ControlType = controlType; diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlListPropertyAttribute.cs similarity index 86% rename from DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs rename to DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlListPropertyAttribute.cs index d7c3bbc..75df843 100644 --- a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelControlListPropertyAttribute.cs @@ -7,7 +7,7 @@ namespace ModuleTools.Attributes /// применяется к классам ElementViewModel) /// [AttributeUsage(AttributeTargets.Property)] - public class ViewModelOnListPropertyAttribute : Attribute + public class ViewModelControlListPropertyAttribute : Attribute { /// /// Название на форме @@ -28,7 +28,7 @@ namespace ModuleTools.Attributes /// Настройка отображения элемента в контролах /// /// Название на форме - public ViewModelOnListPropertyAttribute(string displayName) + public ViewModelControlListPropertyAttribute(string displayName) { DisplayName = displayName; } @@ -38,7 +38,7 @@ namespace ModuleTools.Attributes /// /// Название на форме /// Ширина колонки - public ViewModelOnListPropertyAttribute(string displayName, int columnWidth) + public ViewModelControlListPropertyAttribute(string displayName, int columnWidth) { DisplayName = displayName; ColumnWidth = columnWidth; diff --git a/DepartmentPortal/Common/ModuleTools/BindingModels/AccessBindingModel.cs b/DepartmentPortal/Common/ModuleTools/BindingModels/AccessBindingModel.cs index 08b62b5..aca56d5 100644 --- a/DepartmentPortal/Common/ModuleTools/BindingModels/AccessBindingModel.cs +++ b/DepartmentPortal/Common/ModuleTools/BindingModels/AccessBindingModel.cs @@ -10,6 +10,6 @@ namespace ModuleTools.BindingModels /// /// Идентификатор пользователя, который запрашивает выполнение операции /// - public Guid? UserId { get; set; } + public Guid? UserIdForAccess { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Enums/AccessOperation.cs b/DepartmentPortal/Common/ModuleTools/Enums/AccessOperation.cs index 99f2005..2a64c48 100644 --- a/DepartmentPortal/Common/ModuleTools/Enums/AccessOperation.cs +++ b/DepartmentPortal/Common/ModuleTools/Enums/AccessOperation.cs @@ -15,6 +15,8 @@ Пользователи = 3, НастройкиСреды = 4, + + ПользователиРоли = 5, #endregion #region База diff --git a/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs b/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs index dc1e826..76ca9b1 100644 --- a/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs +++ b/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs @@ -8,7 +8,7 @@ namespace ModuleTools.ViewModels /// public class ElementViewModel { - [ViewModelOnListProperty("Идентификатор", IsHide = true)] + [ViewModelControlListProperty("Идентификатор", IsHide = true)] [MapConfiguration("Id")] public Guid Id { get; set; } } diff --git a/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs b/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs index 1614ea6..6b46bf4 100644 --- a/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs +++ b/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs @@ -1,5 +1,8 @@ using DesktopTools.BusinessLogics; using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; using System; using System.Collections.Generic; using System.Linq; @@ -9,26 +12,26 @@ namespace DepartmentPortalDesctop { public partial class FormMain : Form { - private readonly Dictionary _baseControls; + private readonly Dictionary _baseControls; - private readonly Dictionary _controls; + private readonly Dictionary _controls; public FormMain() { InitializeComponent(); - _baseControls = new Dictionary(); - _controls = new Dictionary(); + _baseControls = new Dictionary(); + _controls = new Dictionary(); var extensions = DesktopLoader.GetWindowDesktopExtensions(); foreach (var extens in extensions) { - var list = extens?.GetListControlEntityList()?.OrderBy(x => x.Order).ToList(); + var list = extens?.GetListControlEntityList()?.ToList(); if (list != null && list.Count > 0) { var menu = new ToolStripMenuItem { Text = list[0].Title }; for (int i = 0; i < list.Count; i++) { - if (list[i].Control is AbstractControlViewEntityList control) + if (list[i].Control is IControl control) { if (_baseControls.ContainsKey(list[i].Id)) { @@ -65,16 +68,14 @@ namespace DepartmentPortalDesctop return; } - var ctrl = _baseControls[id].Clone(); + var ctrl = _baseControls[id].GetInstance(); if (!_controls.ContainsKey(ctrl.ControlId)) { - ctrl.CloseEventAdd += CloseControl; - ctrl.Dock = DockStyle.Fill; - ctrl.Open(); + ctrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.List, CloseList = CloseControl }); _controls.Add(ctrl.ControlId, ctrl); splitContainerMain.Panel1.Controls.Clear(); - splitContainerMain.Panel1.Controls.Add(ctrl); + splitContainerMain.Panel1.Controls.Add(ctrl as UserControl); dataGridViewControls.Rows.Add(new object[] { ctrl.ControlId, ctrl.Title }); dataGridViewControls.Rows[^1].Selected = true; } @@ -132,7 +133,7 @@ namespace DepartmentPortalDesctop return; } splitContainerMain.Panel1.Controls.Clear(); - splitContainerMain.Panel1.Controls.Add(ctrl); + splitContainerMain.Panel1.Controls.Add(ctrl as UserControl); } private void ButtonShowHideControlList_Click(object sender, EventArgs e) diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs index cacea99..282756b 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs @@ -10,6 +10,7 @@ namespace SecurityBusinessLogic.BindingModels /// public class UserGetBindingModel : GetBindingModel { + public string UserNameForSearch { get; set; } } /// diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserRoleBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserRoleBindingModels.cs new file mode 100644 index 0000000..d679a96 --- /dev/null +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserRoleBindingModels.cs @@ -0,0 +1,31 @@ +using ModuleTools.Attributes; +using ModuleTools.BindingModels; +using System; +using System.ComponentModel.DataAnnotations; + +namespace SecurityBusinessLogic.BindingModels +{ + /// + /// Получение связи пользователя с ролью + /// + public class UserRoleGetBindingModel : GetBindingModel + { + public Guid? UserId { get; set; } + + public Guid? RoleId { get; set; } + } + + /// + /// Сохранение связи пользователя с ролью + /// + public class UserRoleSetBindingModel : SetBindingModel + { + [Required(ErrorMessage = "required")] + [MapConfiguration("UserId")] + public Guid UserId { get; set; } + + [Required(ErrorMessage = "required")] + [MapConfiguration("RoleId")] + public Guid RoleId { get; set; } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/UserRoleBusinessLogic.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/UserRoleBusinessLogic.cs new file mode 100644 index 0000000..c97bcc7 --- /dev/null +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/UserRoleBusinessLogic.cs @@ -0,0 +1,16 @@ +using ModuleTools.BusinessLogics; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.Interfaces; +using SecurityBusinessLogic.ViewModels; + +namespace SecurityBusinessLogic.BusinessLogics +{ + /// + /// Логика работы со связями пользователями с ролями + /// + public class UserRoleBusinessLogic : GenericBusinessLogic + { + public UserRoleBusinessLogic(IUserRoleService service) : base(service, "Свзяь пользователей с ролями", AccessOperation.ПользователиРоли) { } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/Interfaces/IUserRoleService.cs b/DepartmentPortal/Security/SecurityBusinessLogic/Interfaces/IUserRoleService.cs new file mode 100644 index 0000000..ae8b1ee --- /dev/null +++ b/DepartmentPortal/Security/SecurityBusinessLogic/Interfaces/IUserRoleService.cs @@ -0,0 +1,10 @@ +using ModuleTools.Interfaces; +using SecurityBusinessLogic.BindingModels; + +namespace SecurityBusinessLogic.Interfaces +{ + /// + /// Хранение связей пользователей с ролями + /// + public interface IUserRoleService : IGenerticEntityService { } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs index 002a02e..ab77fbe 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs @@ -13,28 +13,29 @@ namespace SecurityBusinessLogic.ViewModels /// /// Элемент доступа /// + [ViewModelControlElementClass()] public class AccessViewModel : ElementViewModel { [MapConfiguration("RoleId", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Роль", ControlType.ControlGuid, MustHaveValue = true, ControlTypeObject = "SecurityWindowsDesktop.Controls.RolesControl, SecurityWindowsDesktop")] + [ViewModelControlElementProperty("Роль", ControlType.ControlGuid, MustHaveValue = true, ReadOnly = true, ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlRoleList, SecurityWindowsDesktop")] public Guid RoleId { get; set; } - [ViewModelOnListProperty("Роль", 100)] + [ViewModelControlListProperty("Роль", 100)] [MapConfiguration("Role.RoleName", IsDifficle = true, AllowCopyWithoutRigth = false)] public string RoleName { get; set; } [MapConfiguration("AccessOperation", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Операция", ControlType.ControlEnum, MustHaveValue = true)] + [ViewModelControlElementProperty("Операция", ControlType.ControlEnum, MustHaveValue = true)] public AccessOperation AccessOperation { get; set; } - [ViewModelOnListProperty("Операция")] + [ViewModelControlListProperty("Операция")] public string AccessOperationTitle => AccessOperation.ToString("G"); [MapConfiguration("AccessType", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Тип", ControlType.ControlEnum, MustHaveValue = true)] + [ViewModelControlElementProperty("Тип", ControlType.ControlEnum, MustHaveValue = true)] public AccessType AccessType { get; set; } - [ViewModelOnListProperty("Тип", 150)] + [ViewModelControlListProperty("Тип", 150)] public string AccessTypeTitle => AccessType switch { AccessType.Delete => "Полные права", diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs index 8bef541..19adcce 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs @@ -12,20 +12,21 @@ namespace SecurityBusinessLogic.ViewModels /// /// Элемент общих настроек системы /// + [ViewModelControlElementClass()] public class EnviromentSettingViewModel : ElementViewModel { - [ViewModelOnListProperty("Ключ")] - [ViewModelOnElementProperty("Ключ", ControlType.ControlString, MustHaveValue = true, ReadOnly = true)] + [ViewModelControlListProperty("Ключ")] + [ViewModelControlElementProperty("Ключ", ControlType.ControlString, MustHaveValue = true, ReadOnly = true)] [MapConfiguration("Key", AllowCopyWithoutRigth = false)] public string Key { get; set; } - [ViewModelOnListProperty("Значение")] - [ViewModelOnElementProperty("Значение", ControlType.ControlString, MustHaveValue = true)] + [ViewModelControlListProperty("Значение")] + [ViewModelControlElementProperty("Значение", ControlType.ControlString, MustHaveValue = true)] [MapConfiguration("Value", AllowCopyWithoutRigth = false)] public string Value { get; set; } - [ViewModelOnListProperty("Описание")] - [ViewModelOnElementProperty("Описание", ControlType.ControlText, 0, 200)] + [ViewModelControlListProperty("Описание")] + [ViewModelControlElementProperty("Описание", ControlType.ControlText, 0, 200)] [MapConfiguration("Description", AllowCopyWithoutRigth = false)] public string Description { get; set; } diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs index e1ee095..8a10d24 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs @@ -12,15 +12,20 @@ namespace SecurityBusinessLogic.ViewModels /// /// Элемент ролей /// + [ViewModelControlElementClass(HaveDependenceEntities = true, Width = 800, Height = 500)] + [ViewModelControlElementDependenceEntity(Title = "Доступы", Order = 1, ParentPropertyName = "RoleId", + ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlAccessList, SecurityWindowsDesktop")] + [ViewModelControlElementDependenceEntity(Title = "Пользователи", Order = 2, ParentPropertyName = "RoleId", + ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlRoleUserList, SecurityWindowsDesktop")] public class RoleViewModel : ElementViewModel { - [ViewModelOnListProperty("Название роли")] - [ViewModelOnElementProperty("Название роли", ControlType.ControlString, MustHaveValue = true)] + [ViewModelControlListProperty("Название роли")] + [ViewModelControlElementProperty("Название роли", ControlType.ControlString, MustHaveValue = true)] [MapConfiguration("RoleName")] public string RoleName { get; set; } - [ViewModelOnListProperty("Приоритет", 100)] - [ViewModelOnElementProperty("Приоритет", ControlType.ControlInt, MustHaveValue = true)] + [ViewModelControlListProperty("Приоритет", 100)] + [ViewModelControlElementProperty("Приоритет", ControlType.ControlInt, MustHaveValue = true)] [MapConfiguration("RolePriority")] public int RolePriority { get; set; } diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserRoleViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserRoleViewModels.cs new file mode 100644 index 0000000..dc7312d --- /dev/null +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserRoleViewModels.cs @@ -0,0 +1,37 @@ +using ModuleTools.Attributes; +using ModuleTools.Enums; +using ModuleTools.ViewModels; +using System; + +namespace SecurityBusinessLogic.ViewModels +{ + /// + /// Список пользователей + /// + public class UserRoleListViewModel : ListViewModel { } + + /// + /// Элемент пользователей + /// + [ViewModelControlElementClass()] + public class UserRoleViewModel : ElementViewModel + { + [MapConfiguration("UserId", AllowCopyWithoutRigth = false)] + [ViewModelControlElementProperty("Пользователь", ControlType.ControlGuid, MustHaveValue = true, ReadOnly = false, ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlUserList, SecurityWindowsDesktop")] + public Guid UserId { get; set; } + + [ViewModelControlListProperty("Пользователь")] + [MapConfiguration("User.UserName", IsDifficle = true, AllowCopyWithoutRigth = false)] + public string UserName { get; set; } + + [MapConfiguration("RoleId", AllowCopyWithoutRigth = false)] + [ViewModelControlElementProperty("Роль", ControlType.ControlGuid, MustHaveValue = true, ReadOnly = false, ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlRoleList, SecurityWindowsDesktop")] + public Guid RoleId { get; set; } + + [ViewModelControlListProperty("Роль")] + [MapConfiguration("Role.RoleName", IsDifficle = true, AllowCopyWithoutRigth = false)] + public string RoleName { get; set; } + + public override string ToString() => $"{RoleName}-{UserName}"; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs index cc1d479..3f7c3c7 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs @@ -13,10 +13,13 @@ namespace SecurityBusinessLogic.ViewModels /// /// Элемент пользователей /// + [ViewModelControlElementClass(HaveDependenceEntities = true, Width = 800, Height = 500)] + [ViewModelControlElementDependenceEntity(Title = "Роли", Order = 1, ParentPropertyName = "UserId", + ControlTypeObject = "SecurityWindowsDesktop.Controls.ControlUserRoleList, SecurityWindowsDesktop")] public class UserViewModel : ElementViewModel { - [ViewModelOnListProperty("Пользователь")] - [ViewModelOnElementProperty("Логин", ControlType.ControlString, MustHaveValue = true)] + [ViewModelControlListProperty("Пользователь")] + [ViewModelControlElementProperty("Логин", ControlType.ControlString, MustHaveValue = true)] [MapConfiguration("UserName")] public string Login { get; set; } @@ -24,29 +27,29 @@ namespace SecurityBusinessLogic.ViewModels public string Password { get; set; } [MapConfiguration("Avatar")] - [ViewModelOnElementProperty("Фото", ControlType.ControlImage, 200, 200)] + [ViewModelControlElementProperty("Фото", ControlType.ControlImage, 200, 200)] public byte[] Avatar { get; set; } - [ViewModelOnListProperty("Посл. визит", 100)] + [ViewModelControlListProperty("Посл. визит", 100)] [MapConfiguration("DateLastVisit")] public DateTime? DateLastVisit { get; set; } [MapConfiguration("IsBanned", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Заблокирован", ControlType.ControlBool, MustHaveValue = true)] + [ViewModelControlElementProperty("Заблокирован", ControlType.ControlBool, MustHaveValue = true)] public bool IsBanned { get; set; } - [ViewModelOnListProperty("Блокир.", 80)] + [ViewModelControlListProperty("Блокир.", 80)] public string Banned => IsBanned ? "Да" : "Нет"; [MapConfiguration("DateBanned", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Дата блокировки", ControlType.ControlDateTime, ReadOnly = true)] + [ViewModelControlElementProperty("Дата блокировки", ControlType.ControlDateTime, ReadOnly = true)] public DateTime? DateBanned { get; set; } - [ViewModelOnListProperty("Дата Б.", 100)] + [ViewModelControlListProperty("Дата Б.", 100)] public string DateBannedTitle => DateBanned.HasValue ? DateBanned.Value.ToShortDateString() : string.Empty; [MapConfiguration("CountAttempt", AllowCopyWithoutRigth = false)] - [ViewModelOnElementProperty("Попытки входа", ControlType.ControlInt , ReadOnly = true)] + [ViewModelControlElementProperty("Попытки входа", ControlType.ControlInt , ReadOnly = true)] public int CountAttempt { get; set; } public override string ToString() => Login; diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs index 5fa71cf..b32508b 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs @@ -11,7 +11,7 @@ using SecurityBusinessLogic.ViewModels; using System; using System.Linq; -namespace SecurityImplementation.SecurityDatabaseImplementation +namespace SecurityDatabaseImplementation.Implementations { /// /// Реализация IAccessService diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs index 440fea4..d0cbcb6 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs @@ -10,7 +10,7 @@ using SecurityBusinessLogic.ViewModels; using System; using System.Linq; -namespace SecurityImplementation.SecurityDatabaseImplementation +namespace SecurityDatabaseImplementation.Implementations { /// /// Реализация IEnviromentSettingService diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs index 51cb434..83f1976 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs @@ -9,7 +9,7 @@ using SecurityBusinessLogic.ViewModels; using System; using System.Linq; -namespace SecurityImplementation.SecurityDatabaseImplementation +namespace SecurityDatabaseImplementation.Implementations { /// /// Реализация IRoleService diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs new file mode 100644 index 0000000..a7a282b --- /dev/null +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs @@ -0,0 +1,135 @@ +using DatabaseCore; +using DatabaseCore.Models.Security; +using Microsoft.EntityFrameworkCore; +using ModuleTools.BusinessLogics; +using ModuleTools.Enums; +using ModuleTools.Models; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.Interfaces; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Linq; + +namespace SecurityDatabaseImplementation.Implementations +{ + /// + /// Реализация IUserRoleService + /// + public class UserRoleService : IUserRoleService + { + public OperationResultModel Create(UserRoleSetBindingModel model) + { + using var context = DatabaseManager.GetContext; + + var exsistEntity = context.UserRoles.FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId); + if (exsistEntity == null) + { + var entity = Mapper.MapToClass(model, true); + context.UserRoles.Add(entity); + context.SaveChanges(); + return OperationResultModel.Success(Mapper.MapToClass(entity, true)); + } + else + { + if (exsistEntity.IsDeleted) + { + exsistEntity.IsDeleted = false; + context.SaveChanges(); + return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); + } + else + { + return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); + } + } + } + + public OperationResultModel Delete(UserRoleGetBindingModel model) + { + using var context = DatabaseManager.GetContext; + + var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + else if (entity.IsDeleted) + { + return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); + } + entity.IsDeleted = true; + entity.DateDelete = DateTime.Now; + + context.SaveChanges(); + + return OperationResultModel.Success(true); + } + + public OperationResultModel Read(UserRoleGetBindingModel model) + { + int countPages = 0; + using var context = DatabaseManager.GetContext; + + // для одной записи + if (model.Id.HasValue) + { + var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id.Value); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); + } + + var query = context.UserRoles.Where(x => !x.IsDeleted).AsQueryable(); + if (model.RoleId.HasValue) + { + query = query.Where(x => x.RoleId == model.RoleId); + } + if (model.UserId.HasValue) + { + query = query.Where(x => x.UserId == model.UserId); + } + + query = query.OrderBy(x => x.User.UserName); + + 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); + } + + query = query.Include(x => x.Role).Include(x => x.User); + + var result = new UserRoleListViewModel + { + MaxCount = countPages, + List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() + }; + + return OperationResultModel.Success(result); + } + + public OperationResultModel Update(UserRoleSetBindingModel model) + { + using var context = DatabaseManager.GetContext; + + var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + else if (entity.IsDeleted) + { + return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); + } + entity = Mapper.MapToClass(model, entity, true); + + context.SaveChanges(); + + return OperationResultModel.Success(Mapper.MapToClass(entity, true)); + } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs index 4a0002d..7000a21 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs @@ -2,6 +2,7 @@ using DatabaseCore.Models.Security; using ModuleTools.BusinessLogics; using ModuleTools.Enums; +using ModuleTools.Extensions; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; @@ -9,7 +10,7 @@ using SecurityBusinessLogic.ViewModels; using System; using System.Linq; -namespace SecurityImplementation.SecurityDatabaseImplementation +namespace SecurityDatabaseImplementation.Implementations { /// /// Реализация IUserService @@ -100,6 +101,11 @@ namespace SecurityImplementation.SecurityDatabaseImplementation var query = context.Users.Where(x => !x.IsDeleted).AsQueryable(); + if(model.UserNameForSearch.IsNotEmpty()) + { + query = query.Where(x => x.UserName.Contains(model.UserNameForSearch)); + } + query = query.OrderBy(x => x.UserName); if (model.PageNumber.HasValue && model.PageSize.HasValue) diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/SecurityImplementationExtensions.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/SecurityImplementationExtensions.cs index 6ea45f7..bcf3a23 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/SecurityImplementationExtensions.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/SecurityImplementationExtensions.cs @@ -1,7 +1,7 @@ using ModuleTools.BusinessLogics; using ModuleTools.Interfaces; using SecurityBusinessLogic.Interfaces; -using SecurityImplementation.SecurityDatabaseImplementation; +using SecurityDatabaseImplementation.Implementations; namespace SecurityDatabaseImplementation { @@ -13,6 +13,7 @@ namespace SecurityDatabaseImplementation DependencyManager.Instance.RegisterType(); DependencyManager.Instance.RegisterType(); DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs deleted file mode 100644 index 6f29ef2..0000000 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs +++ /dev/null @@ -1,52 +0,0 @@ -using DesktopTools.Controls; -using DesktopTools.Models; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using SecurityBusinessLogic.BindingModels; -using SecurityBusinessLogic.BusinessLogics; -using SecurityBusinessLogic.ViewModels; -using System; -using System.Data; -using System.Linq; - -namespace SecurityWindowsDesktop.Controls -{ - public partial class AccessesControl : AbstractGenericControlEntityList - { - private readonly RoleBusinessLogic _roleBusinessLogic; - - public AccessesControl() - { - InitializeComponent(); - _roleBusinessLogic = DependencyManager.Instance.Resolve(); - Title = "Доступы"; - ControlId = new Guid("6eebc4c4-cb86-4368-93e0-33dbdbb7409a"); - Order = 1; - AccessOperation = AccessOperation.Доступы; - } - - public override AbstractControlViewEntityList Clone() => new AccessesControl() { ControlId = Guid.NewGuid() }; - - protected override ControlViewEntityListConfiguration GetConfig() => new() - { - PaginationOn = true, - PageNamesForPagination = _roleBusinessLogic.GetList(new RoleGetBindingModel())?.List?.Select(x => x.RoleName)?.ToList() - }; - - protected override AccessListViewModel GetData() - { - throw new NotImplementedException(); - } - - protected override AccessListViewModel GetDataWithPageName(string key) - { - var list = _businessLogic.GetList(new AccessGetBindingModel { RoleName = key }); - return list; - } - - protected override AccessListViewModel GetDataWithPageNumber(int page, int count) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.Designer.cs similarity index 96% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.Designer.cs rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.Designer.cs index 8027646..c70d2dc 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.Designer.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.Designer.cs @@ -1,7 +1,7 @@  namespace SecurityWindowsDesktop.Controls { - partial class EnviromentSettingControl + partial class ControlAccessElement { /// /// Освободить все используемые ресурсы. diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.cs new file mode 100644 index 0000000..9c14792 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.cs @@ -0,0 +1,24 @@ +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; + +namespace SecurityWindowsDesktop.Controls +{ + public partial class ControlAccessElement : + GenericControlEntityElement, + IGenericControlEntityElement + { + public ControlAccessElement() + { + InitializeComponent(); + Title = "Доступы"; + ControlId = new Guid("fbe22d1d-e7b3-49f9-b013-93950aa0281b"); + _genericControlViewEntityElement = this; + } + + public IControl GetInstanceGenericControl() => new ControlAccessElement() { ControlId = Guid.NewGuid() }; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.resx similarity index 100% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.resx rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessElement.resx diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.Designer.cs similarity index 96% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.Designer.cs rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.Designer.cs index cda88f6..d3d8631 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.Designer.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.Designer.cs @@ -1,7 +1,7 @@  namespace SecurityWindowsDesktop.Controls { - partial class UsersControl + partial class ControlAccessList { /// /// Освободить все используемые ресурсы. diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.cs new file mode 100644 index 0000000..1f97b75 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.cs @@ -0,0 +1,63 @@ +using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.BusinessLogics; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка доступов + /// + public partial class ControlAccessList : + GenericControlEntityList, + IGenericControlEntityList + { + private readonly RoleBusinessLogic _roleBusinessLogic; + + public ControlAccessList() + { + InitializeComponent(); + _roleBusinessLogic = DependencyManager.Instance.Resolve(); + Title = "Доступы"; + ControlId = new Guid("6eebc4c4-cb86-4368-93e0-33dbdbb7409a"); + AccessOperation = AccessOperation.Доступы; + ControlViewEntityElement = new ControlAccessElement(); + _genericControlViewEntityList = this; + } + + public IControl GetInstanceGenericControl() => new ControlAccessList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = true, + PageNamesForPagination = _roleBusinessLogic.GetList(new RoleGetBindingModel())?.List?.Select(x => + new PageNamesForPaginationModel + { + Key = x.Id.ToString(), + Value = x.RoleName + })?.ToList(), + ParentPropertyName = "RoleId", + HideToolStripButton = new List + { + ToolStripButtonListNames.toolStripButtonSearch + } + }; + + public AccessListViewModel GetDataForControl() => throw new NotImplementedException(); + + public AccessListViewModel GetDataFromParentForControl(Guid id) => _businessLogic.GetList(new AccessGetBindingModel { RoleId = id }); + + public AccessListViewModel GetDataWithPageNameForControl(string key) => _businessLogic.GetList(new AccessGetBindingModel { RoleId = new Guid(key) }); + + public AccessListViewModel GetDataWithPageNumberForControl(int page, int count) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.resx similarity index 100% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.resx rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlAccessList.resx diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.Designer.cs new file mode 100644 index 0000000..9b2780b --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlEnviromentSettingElement + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.cs new file mode 100644 index 0000000..caa1df6 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.cs @@ -0,0 +1,24 @@ +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; + +namespace SecurityWindowsDesktop.Controls +{ + public partial class ControlEnviromentSettingElement : + GenericControlEntityElement, + IGenericControlEntityElement + { + public ControlEnviromentSettingElement() + { + InitializeComponent(); + Title = "Настройки Среды"; + ControlId = new Guid("9888d5c5-14d4-4528-a544-f0ede22aaad3"); + _genericControlViewEntityElement = this; + } + + public IControl GetInstanceGenericControl() => new ControlEnviromentSettingElement() { ControlId = Guid.NewGuid() }; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.resx similarity index 100% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.resx rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingElement.resx diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.Designer.cs new file mode 100644 index 0000000..05cc0b6 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlEnviromentSettingList + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.cs new file mode 100644 index 0000000..9f285fc --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.cs @@ -0,0 +1,51 @@ +using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Collections.Generic; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка настроек среды + /// + public partial class ControlEnviromentSettingList : + GenericControlEntityList, + IGenericControlEntityList + { + public ControlEnviromentSettingList() + { + InitializeComponent(); + Title = "Настройки Среды"; + ControlId = new Guid("b3865c23-b1db-475b-b95c-aa51edc60388"); + AccessOperation = AccessOperation.НастройкиСреды; + ControlViewEntityElement = new ControlEnviromentSettingElement(); + _genericControlViewEntityList = this; + } + + public IControl GetInstanceGenericControl() => new ControlEnviromentSettingList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = false, + HideToolStripButton = new List + { + ToolStripButtonListNames.toolStripButtonAdd, + ToolStripButtonListNames.toolStripButtonSearch + } + }; + + public EnviromentSettingListViewModel GetDataForControl() => _businessLogic.GetList(new EnviromentSettingGetBindingModel()); + + public EnviromentSettingListViewModel GetDataFromParentForControl(Guid id) => throw new NotImplementedException(); + + public EnviromentSettingListViewModel GetDataWithPageNameForControl(string key) => throw new NotImplementedException(); + + public EnviromentSettingListViewModel GetDataWithPageNumberForControl(int page, int count) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.resx similarity index 100% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.resx rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlEnviromentSettingList.resx diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.Designer.cs new file mode 100644 index 0000000..4c188ba --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlRoleElement + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.cs new file mode 100644 index 0000000..b4917f4 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.cs @@ -0,0 +1,24 @@ +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; + +namespace SecurityWindowsDesktop.Controls +{ + public partial class ControlRoleElement : + GenericControlEntityElement, + IGenericControlEntityElement + { + public ControlRoleElement() + { + InitializeComponent(); + Title = "Роли"; + ControlId = new Guid("a905bccb-048f-4249-8665-6e4bd06fa391"); + _genericControlViewEntityElement = this; + } + + public IControl GetInstanceGenericControl() => new ControlRoleElement() { ControlId = Guid.NewGuid() }; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleElement.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.Designer.cs similarity index 97% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.Designer.cs rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.Designer.cs index 83fd87c..5484e2f 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.Designer.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.Designer.cs @@ -1,7 +1,7 @@  namespace SecurityWindowsDesktop.Controls { - partial class RolesControl + partial class ControlRoleList { /// /// Освободить все используемые ресурсы. diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.cs new file mode 100644 index 0000000..ceccd5c --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.cs @@ -0,0 +1,50 @@ +using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Collections.Generic; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка ролей + /// + public partial class ControlRoleList : + GenericControlEntityList, + IGenericControlEntityList + { + public ControlRoleList() : base() + { + InitializeComponent(); + Title = "Роли"; + ControlId = new Guid("6a33ce5c-e950-4294-9f75-2a0b35941bf7"); + AccessOperation = AccessOperation.Роли; + ControlViewEntityElement = new ControlRoleElement(); + _genericControlViewEntityList = this; + } + + public IControl GetInstanceGenericControl() => new ControlRoleList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = false, + HideToolStripButton = new List + { + ToolStripButtonListNames.toolStripButtonSearch + } + }; + + public RoleListViewModel GetDataForControl() => _businessLogic.GetList(new RoleGetBindingModel()); + + public RoleListViewModel GetDataFromParentForControl(Guid id) => throw new NotImplementedException(); + + public RoleListViewModel GetDataWithPageNameForControl(string key) => throw new NotImplementedException(); + + public RoleListViewModel GetDataWithPageNumberForControl(int page, int count) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleList.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.Designer.cs new file mode 100644 index 0000000..47aa328 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlRoleUserList + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.cs new file mode 100644 index 0000000..70b96dc --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.cs @@ -0,0 +1,51 @@ +using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Collections.Generic; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка пользователей роли + /// + public partial class ControlRoleUserList : + GenericControlEntityList, + IGenericControlEntityList + { + public ControlRoleUserList() + { + InitializeComponent(); + Title = "Связи пользователей с ролями"; + ControlId = new Guid("c5748925-c8ec-4d06-a256-c72b0983d332"); + AccessOperation = AccessOperation.ПользователиРоли; + ControlViewEntityElement = new ControlUserRoleElement(); + _genericControlViewEntityList = this; + } + + public IControl GetInstanceGenericControl() => new ControlRoleUserList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = false, + HideToolStripButton = new List + { + ToolStripButtonListNames.toolStripButtonUpd, + ToolStripButtonListNames.toolStripButtonSearch + } + }; + + public UserRoleListViewModel GetDataForControl() => throw new NotImplementedException(); + + public UserRoleListViewModel GetDataFromParentForControl(Guid id) => _businessLogic.GetList(new UserRoleGetBindingModel { RoleId = id }); + + public UserRoleListViewModel GetDataWithPageNameForControl(string key) => throw new NotImplementedException(); + + public UserRoleListViewModel GetDataWithPageNumberForControl(int page, int count) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlRoleUserList.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.Designer.cs new file mode 100644 index 0000000..8bc3be1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlUserElement + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.cs new file mode 100644 index 0000000..db4cdec --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.cs @@ -0,0 +1,24 @@ +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; + +namespace SecurityWindowsDesktop.Controls +{ + public partial class ControlUserElement : + GenericControlEntityElement, + IGenericControlEntityElement + { + public ControlUserElement() + { + InitializeComponent(); + Title = "Пользователь"; + ControlId = new Guid("5e731873-1a7e-44f5-a9b0-9529fbb01fee"); + _genericControlViewEntityElement = this; + } + + public IControl GetInstanceGenericControl() => new ControlUserElement() { ControlId = Guid.NewGuid() }; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserElement.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.Designer.cs similarity index 97% rename from DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.Designer.cs rename to DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.Designer.cs index b6b52e0..2bf01f9 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.Designer.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.Designer.cs @@ -1,7 +1,7 @@  namespace SecurityWindowsDesktop.Controls { - partial class AccessesControl + partial class ControlUserList { /// /// Освободить все используемые ресурсы. diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.cs new file mode 100644 index 0000000..2c080c9 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.cs @@ -0,0 +1,79 @@ +using DesktopTools.BaseControls; +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Linq; +using System.Windows.Forms; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка пользователей + /// + public partial class ControlUserList : + GenericControlEntityList, + IGenericControlEntityList + { + public ControlUserList() : base() + { + InitializeComponent(); + Title = "Пользователи"; + ControlId = new Guid("d5596997-d1f5-4e5e-b94b-6bdd6bca3452"); + AccessOperation = AccessOperation.Пользователи; + ControlViewEntityElement = new ControlUserElement(); + _genericControlViewEntityList = this; + FillSearchPanel(); + } + + public IControl GetInstanceGenericControl() => new ControlUserList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = true, + CountElementsOnPage = 40 + }; + + public UserListViewModel GetDataForControl() => throw new NotImplementedException(); + + public UserListViewModel GetDataFromParentForControl(Guid id) => throw new NotImplementedException(); + + public UserListViewModel GetDataWithPageNameForControl(string key) => throw new NotImplementedException(); + + public UserListViewModel GetDataWithPageNumberForControl(int page, int count) + { + var model = new UserGetBindingModel + { + PageNumber = page, + PageSize = count + }; + if (_searchValues != null) + { + var cntrl = _searchValues.FirstOrDefault(x => x.Name == "UserNameForSearch"); + if (cntrl != default) + { + model.UserNameForSearch = cntrl.Value.ToString(); + } + } + + return _businessLogic.GetList(model); + } + + private void FillSearchPanel() + { + var control = new BaseControlString("UserNameForSearch", false, false, null) + { + Location = new System.Drawing.Point(10, 10), + Size = new System.Drawing.Size(400, 23), + Name = "SearchUserName", + TabIndex = 0 + }; + control.SetTitleWidth(control.SetTitle("Имя пользователя:")); + panelSearchControls.Controls.Add(control); + } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserList.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.Designer.cs new file mode 100644 index 0000000..bda771b --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlUserRoleElement + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.cs new file mode 100644 index 0000000..47ac18a --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.cs @@ -0,0 +1,24 @@ +using DesktopTools.Controls; +using DesktopTools.Interfaces; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; + +namespace SecurityWindowsDesktop.Controls +{ + public partial class ControlUserRoleElement : + GenericControlEntityElement, + IGenericControlEntityElement + { + public ControlUserRoleElement() + { + InitializeComponent(); + Title = "Связи пользователей с ролями"; + ControlId = new Guid("c5748925-c8ec-4d06-a256-c72b0983d332"); + _genericControlViewEntityElement = this; + } + + public IControl GetInstanceGenericControl() => new ControlUserRoleElement() { ControlId = Guid.NewGuid() }; + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleElement.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.Designer.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.Designer.cs new file mode 100644 index 0000000..30fbfb2 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.Designer.cs @@ -0,0 +1,33 @@ + +namespace SecurityWindowsDesktop.Controls +{ + partial class ControlUserRoleList + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.cs new file mode 100644 index 0000000..8120be4 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.cs @@ -0,0 +1,51 @@ +using DesktopTools.Controls; +using DesktopTools.Enums; +using DesktopTools.Interfaces; +using DesktopTools.Models; +using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; +using System; +using System.Collections.Generic; + +namespace SecurityWindowsDesktop.Controls +{ + /// + /// Реализация контрола для списка ролей пользователя + /// + public partial class ControlUserRoleList : + GenericControlEntityList, + IGenericControlEntityList + { + public ControlUserRoleList() + { + InitializeComponent(); + Title = "Связи пользователей с ролями"; + ControlId = new Guid("c5748925-c8ec-4d06-a256-c72b0983d332"); + AccessOperation = AccessOperation.ПользователиРоли; + ControlViewEntityElement = new ControlUserRoleElement(); + _genericControlViewEntityList = this; + } + + public IControl GetInstanceGenericControl() => new ControlUserRoleList() { ControlId = Guid.NewGuid() }; + + public ControlViewEntityListConfiguration GetConfigControl() => new() + { + PaginationOn = false, + HideToolStripButton = new List + { + ToolStripButtonListNames.toolStripButtonUpd, + ToolStripButtonListNames.toolStripButtonSearch + } + }; + + public UserRoleListViewModel GetDataForControl() => throw new NotImplementedException(); + + public UserRoleListViewModel GetDataFromParentForControl(Guid id) => _businessLogic.GetList(new UserRoleGetBindingModel { UserId = id }); + + public UserRoleListViewModel GetDataWithPageNameForControl(string key) => throw new NotImplementedException(); + + public UserRoleListViewModel GetDataWithPageNumberForControl(int page, int count) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.resx b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/ControlUserRoleList.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs deleted file mode 100644 index c1d239f..0000000 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs +++ /dev/null @@ -1,46 +0,0 @@ -using DesktopTools.Controls; -using DesktopTools.Models; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using SecurityBusinessLogic.BindingModels; -using SecurityBusinessLogic.BusinessLogics; -using SecurityBusinessLogic.ViewModels; -using System; - -namespace SecurityWindowsDesktop.Controls -{ - public partial class EnviromentSettingControl : AbstractGenericControlEntityList - { - public EnviromentSettingControl() - { - InitializeComponent(); - Title = "Настройки Среды"; - ControlId = new Guid("b3865c23-b1db-475b-b95c-aa51edc60388"); - Order = 1; - AccessOperation = AccessOperation.НастройкиСреды; - } - - public override AbstractControlViewEntityList Clone() => new EnviromentSettingControl() { ControlId = Guid.NewGuid() }; - - protected override ControlViewEntityListConfiguration GetConfig() => new() - { - PaginationOn = false - }; - - protected override EnviromentSettingListViewModel GetData() - { - var list = _businessLogic.GetList(new EnviromentSettingGetBindingModel()); - return list; - } - - protected override EnviromentSettingListViewModel GetDataWithPageName(string key) - { - throw new NotImplementedException(); - } - - protected override EnviromentSettingListViewModel GetDataWithPageNumber(int page, int count) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs deleted file mode 100644 index 3bcc008..0000000 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs +++ /dev/null @@ -1,46 +0,0 @@ -using DesktopTools.Controls; -using DesktopTools.Models; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using SecurityBusinessLogic.BindingModels; -using SecurityBusinessLogic.BusinessLogics; -using SecurityBusinessLogic.ViewModels; -using System; - -namespace SecurityWindowsDesktop.Controls -{ - public partial class RolesControl : AbstractGenericControlEntityList - { - public RolesControl() : base() - { - InitializeComponent(); - Title = "Роли"; - ControlId = new Guid("6a33ce5c-e950-4294-9f75-2a0b35941bf7"); - Order = 1; - AccessOperation = AccessOperation.Роли; - } - - public override AbstractControlViewEntityList Clone() => new RolesControl() { ControlId = Guid.NewGuid() }; - - protected override ControlViewEntityListConfiguration GetConfig() => new() - { - PaginationOn = false - }; - - protected override RoleListViewModel GetData() - { - var list = _businessLogic.GetList(new RoleGetBindingModel()); - return list; - } - - protected override RoleListViewModel GetDataWithPageName(string key) - { - throw new NotImplementedException(); - } - - protected override RoleListViewModel GetDataWithPageNumber(int page, int count) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs deleted file mode 100644 index 1c9d009..0000000 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs +++ /dev/null @@ -1,50 +0,0 @@ -using DesktopTools.Controls; -using DesktopTools.Models; -using ModuleTools.Enums; -using SecurityBusinessLogic.BindingModels; -using SecurityBusinessLogic.BusinessLogics; -using SecurityBusinessLogic.ViewModels; -using System; - -namespace SecurityWindowsDesktop.Controls -{ - public partial class UsersControl : AbstractGenericControlEntityList - { - public UsersControl() : base() - { - InitializeComponent(); - Title = "Пользователи"; - ControlId = new Guid("d5596997-d1f5-4e5e-b94b-6bdd6bca3452"); - Order = 1; - AccessOperation = AccessOperation.Пользователи; - } - - public override AbstractControlViewEntityList Clone() => new UsersControl() { ControlId = Guid.NewGuid() }; - - protected override ControlViewEntityListConfiguration GetConfig() => new() - { - PaginationOn = true, - CountElementsOnPage = 40 - }; - - protected override UserListViewModel GetData() - { - throw new NotImplementedException(); - } - - protected override UserListViewModel GetDataWithPageName(string key) - { - throw new NotImplementedException(); - } - - protected override UserListViewModel GetDataWithPageNumber(int page, int count) - { - var list = _businessLogic.GetList(new UserGetBindingModel - { - PageNumber = page, - PageSize = count - }); - return list; - } - } -} \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs index eb4f570..8c12a43 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs @@ -1,5 +1,4 @@ -using DesktopTools.Controls; -using DesktopTools.Interfaces; +using DesktopTools.Interfaces; using DesktopTools.Models; using ModuleTools.BindingModels; using ModuleTools.BusinessLogics; @@ -21,7 +20,7 @@ namespace SecurityWindowsDesktop return null; } - if (!manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserId = manager.User }, + if (!manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserIdForAccess = manager.User }, AccessOperation.Администрирование, AccessType.View, "Администрирование"))) { return null; @@ -29,34 +28,29 @@ namespace SecurityWindowsDesktop var list = new List { - new WindowDesktopExtensionControlModel { Order = 0, Title = "Администрирование" } + new WindowDesktopExtensionControlModel { Title = "Администрирование" } }; - List _controls = new() + List _controls = new() { - new UsersControl(), - new RolesControl(), - new AccessesControl(), - new EnviromentSettingControl() + new ControlUserList(), + new ControlRoleList(), + new ControlAccessList(), + new ControlEnviromentSettingList() }; foreach (var cntrl in _controls) { - if (manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserId = manager.User }, + if (manager.CheckAccess(new SecurityManagerCheckAccessModel(new AccessBindingModel { UserIdForAccess = manager.User }, cntrl.AccessOperation, AccessType.View, cntrl.Title))) { list.Add(new WindowDesktopExtensionControlModel { Id = cntrl.ControlId, - Order = cntrl.Order, Title = cntrl.Title, Control = cntrl }); } } - DependencyManager.Instance.RegisterType(); - DependencyManager.Instance.RegisterType(); - DependencyManager.Instance.RegisterType(); - DependencyManager.Instance.RegisterType(); return list; } diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowsDesktop.csproj b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowsDesktop.csproj index 1f1202e..17a9bf4 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowsDesktop.csproj +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowsDesktop.csproj @@ -9,13 +9,6 @@ - - - - - - -