diff --git a/DepartmentPortal/Common/DatabaseCore/Models/Security/Access.cs b/DepartmentPortal/Common/DatabaseCore/Models/Security/Access.cs index 1414c2c..13453e7 100644 --- a/DepartmentPortal/Common/DatabaseCore/Models/Security/Access.cs +++ b/DepartmentPortal/Common/DatabaseCore/Models/Security/Access.cs @@ -21,7 +21,7 @@ namespace DatabaseCore.Models.Security [Required] [DataMember] - [MapConfiguration("Operation")] + [MapConfiguration("AccessOperation")] public AccessOperation AccessOperation { get; set; } [Required] diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.Designer.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.Designer.cs new file mode 100644 index 0000000..ff108fa --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.Designer.cs @@ -0,0 +1,71 @@ + +namespace DesktopTools.BaseControls +{ + partial class AbstractBaseControl + { + /// + /// Обязательная переменная конструктора. + /// + protected System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + this.labelTitle = new System.Windows.Forms.Label(); + this.panelControl = new System.Windows.Forms.Panel(); + this.SuspendLayout(); + // + // labelTitle + // + this.labelTitle.Dock = System.Windows.Forms.DockStyle.Left; + this.labelTitle.Location = new System.Drawing.Point(0, 0); + this.labelTitle.Name = "labelTitle"; + this.labelTitle.Size = new System.Drawing.Size(93, 25); + this.labelTitle.TabIndex = 0; + this.labelTitle.Text = "Наименование:"; + this.labelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // panelControl + // + this.panelControl.Dock = System.Windows.Forms.DockStyle.Fill; + this.panelControl.Location = new System.Drawing.Point(93, 0); + this.panelControl.Name = "panelControl"; + this.panelControl.Size = new System.Drawing.Size(407, 25); + this.panelControl.TabIndex = 1; + // + // BaseControl + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.panelControl); + this.Controls.Add(this.labelTitle); + this.Name = "BaseControl"; + this.Size = new System.Drawing.Size(500, 25); + this.ResumeLayout(false); + + } + + #endregion + + protected System.Windows.Forms.Label labelTitle; + protected System.Windows.Forms.Panel panelControl; + } +} diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs new file mode 100644 index 0000000..a18528e --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.cs @@ -0,0 +1,121 @@ +using ModuleTools.Extensions; +using System; +using System.Windows.Forms; + +namespace DesktopTools.BaseControls +{ + public abstract partial class AbstractBaseControl : UserControl + { + /// + /// Оригинальное значение (требуется при откате изменений) + /// + protected object _originalValue; + + /// + /// Необходимость проверки при получении данных + /// + protected bool _mustCheckValue; + + /// + /// Название свойства, по которму идет отображение + /// + protected string PropertyName { get; private set; } + + /// + /// Событие изменения значения в контроле + /// + protected event Action OnValueChange; + + /// + /// Событие изменения значения в контроле + /// + public event Action OnValueChangeEvent { add { OnValueChange += value; } remove { OnValueChange -= value; } } + + /// + /// Вызов события в дочерних контролах + /// + protected void CallOnValueChangeEvent() => OnValueChange?.Invoke(); + + + public AbstractBaseControl(string propertyName) + { + InitializeComponent(); + PropertyName = propertyName; + } + + #region Работа с заголовком + /// + /// Установка заголовка + /// + /// + /// Ширину полученного загаловка + public int SetTitle(string title) + { + labelTitle.Text = title; + labelTitle.AutoSize = true; + return labelTitle.Width; + } + + /// + /// Установка ширины заголовка (вызывается через событие, чтобы у всех заголовков получилась одна ширина) + /// + /// + public void SetTitleWidth(int width) + { + labelTitle.AutoSize = false; + labelTitle.Width = width; + } + #endregion + + /// + /// Устанвока контрола в режим только просмотра + /// + /// + public abstract void SetReadOnly(bool readOnly); + + /// + /// Установка значения + /// + /// + public virtual void SetValueToControl(object value) => _originalValue = value; + + /// + /// Сброс значения + /// + public abstract void DropValue(); + + /// + /// Установка флага необхоидмости проверки + /// + /// + public void SetMustCheckValue(bool mustCheckValue) => _mustCheckValue = mustCheckValue; + + /// + /// Проверка на заполненность + /// + /// + public abstract bool CheckValue(); + + /// + /// Получение значение с контрола + /// + /// + protected abstract object GetValueFromControl(); + + /// + /// Заполнение свойства объекта значением из контрола + /// + /// + public void FillPropertyToObject(object obj) + { + if (obj != null && PropertyName.IsNotEmpty()) + { + var property = obj.GetType().GetProperty(PropertyName); + if (property != null) + { + property.SetValue(obj, GetValueFromControl()); + } + } + } + } +} diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.resx b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/AbstractBaseControl.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Common/DesktopTools/BaseControls/BaseControlInt.Designer.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.Designer.cs new file mode 100644 index 0000000..23f8023 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.Designer.cs @@ -0,0 +1,58 @@ + +namespace DesktopTools.BaseControls +{ + partial class BaseControlInt + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + 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; + this.checkBoxNullable = new System.Windows.Forms.CheckBox(); + this.numericUpDown = new System.Windows.Forms.NumericUpDown(); + // + // checkBoxNullable + // + this.checkBoxNullable.AutoSize = true; + this.checkBoxNullable.Location = new System.Drawing.Point(41, 14); + this.checkBoxNullable.Name = "checkBoxNullable"; + this.checkBoxNullable.Size = new System.Drawing.Size(83, 19); + this.checkBoxNullable.TabIndex = 1; + this.checkBoxNullable.UseVisualStyleBackColor = true; + this.checkBoxNullable.Dock = System.Windows.Forms.DockStyle.Left; + // + // numericUpDown + // + this.numericUpDown.Dock = System.Windows.Forms.DockStyle.Fill; + this.numericUpDown.Location = new System.Drawing.Point(148, 9); + this.numericUpDown.Name = "numericUpDown"; + this.numericUpDown.Size = new System.Drawing.Size(120, 23); + this.numericUpDown.TabIndex = 2; + this.numericUpDown.Minimum = int.MinValue; + this.numericUpDown.Maximum = int.MaxValue; + } + + #endregion + + private System.Windows.Forms.CheckBox checkBoxNullable; + private System.Windows.Forms.NumericUpDown numericUpDown; + } +} diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs new file mode 100644 index 0000000..5a57b03 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.cs @@ -0,0 +1,64 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace DesktopTools.BaseControls +{ + public partial class BaseControlInt : AbstractBaseControl + { + public BaseControlInt(string propertyName) : base(propertyName) + { + InitializeComponent(); + checkBoxNullable.Visible = false; + panelControl.Controls.Add(checkBoxNullable); + checkBoxNullable.CheckedChanged += (object sender, EventArgs e) => + { + numericUpDown.Enabled = !(sender as CheckBox).Checked; + CallOnValueChangeEvent(); + }; + + panelControl.Controls.Add(numericUpDown); + numericUpDown.ValueChanged += (object sender, EventArgs e) => { CallOnValueChangeEvent(); }; + _originalValue = 0; + } + + public override void SetReadOnly(bool readOnly) + { + numericUpDown.Enabled = !readOnly; + checkBoxNullable.Enabled = !readOnly; + } + + public override void SetValueToControl(object value) + { + base.SetValueToControl(value); + if (value != null) + { + numericUpDown.Value = Convert.ToInt32(value); + } + } + + public override void DropValue() + { + numericUpDown.Value = _originalValue != null ? Convert.ToInt32(_originalValue) : 0; + } + + public override bool CheckValue() + { + if (_mustCheckValue && checkBoxNullable.Checked) + { + BackColor = Color.OrangeRed; + return false; + } + return true; + } + + protected override object GetValueFromControl() + { + if (_mustCheckValue && checkBoxNullable.Checked) + { + throw new ArgumentNullException($"Поле свойства '{labelTitle.Text}' должно быть заполнено"); + } + return checkBoxNullable.Checked? null : Convert.ToInt32(numericUpDown.Value); + } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.resx b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlInt.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/Common/DesktopTools/BaseControls/BaseControlText.Designer.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.Designer.cs new file mode 100644 index 0000000..9b1136c --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.Designer.cs @@ -0,0 +1,42 @@ + +namespace DesktopTools.BaseControls +{ + partial class BaseControlText + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + this.textBox = new System.Windows.Forms.TextBox(); + // + // textBox + // + this.textBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBox.Location = new System.Drawing.Point(0, 0); + this.textBox.Name = "textBox"; + this.textBox.Size = new System.Drawing.Size(1000, 1000); + this.textBox.TabIndex = 1; + } + + #endregion + + private System.Windows.Forms.TextBox textBox; + } +} diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs new file mode 100644 index 0000000..fdd35da --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.cs @@ -0,0 +1,46 @@ +using ModuleTools.Extensions; +using System; +using System.Drawing; + +namespace DesktopTools.BaseControls +{ + public partial class BaseControlText : AbstractBaseControl + { + public BaseControlText(string propertyName) : base(propertyName) + { + InitializeComponent(); + panelControl.Controls.Add(textBox); + textBox.TextChanged += (object sender, EventArgs e) => { CallOnValueChangeEvent(); }; + _originalValue = string.Empty; + } + + public override void SetReadOnly(bool readOnly) => textBox.Enabled = !readOnly; + + public override void SetValueToControl(object value) + { + base.SetValueToControl(value); + textBox.Text = value.ToString(); + } + + public override void DropValue() => textBox.Text = _originalValue.ToString(); + + public override bool CheckValue() + { + if(_mustCheckValue && textBox.Text.IsEmpty()) + { + BackColor = Color.OrangeRed; + return false; + } + return true; + } + + protected override object GetValueFromControl() + { + if (_mustCheckValue && textBox.Text.IsEmpty()) + { + throw new ArgumentNullException($"Поле свойства '{labelTitle.Text}' должно быть заполнено"); + } + return textBox.Text; + } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.resx b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/BaseControls/BaseControlText.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Common/DesktopTools/Controls/BaseControlViewEntityElement.Designer.cs b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.Designer.cs new file mode 100644 index 0000000..f7f02ab --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.Designer.cs @@ -0,0 +1,46 @@ + +namespace DesktopTools.Controls +{ + partial class BaseControlViewEntityElement + { + /// + /// Обязательная переменная конструктора. + /// + protected System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // BaseControlViewEntityElement + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Name = "BaseControlViewEntityElement"; + this.Size = new System.Drawing.Size(695, 578); + this.ResumeLayout(false); + + } + + #endregion + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.cs new file mode 100644 index 0000000..7a08c43 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.cs @@ -0,0 +1,104 @@ +using DesktopTools.Helpers; +using ModuleTools.Enums; +using System; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class BaseControlViewEntityElement : UserControl + { + /// + /// Признак налиичия изменений + /// + protected bool _haveChages = false; + + /// + /// Событие, вызываемое при закрытии контрола + /// + protected event Action CloseEvent; + + /// + /// Событие, вызываемое при закрытии контрола + /// + public event Action CloseEventAdd { add { CloseEvent += value; } remove { CloseEvent -= value; } } + + /// + /// Открытие формы + /// + public virtual void Open() { } + + /// + /// Закрытие формы + /// + public virtual void Close() + { + if(_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == + DialogResult.Yes) + { + if (!Save()) + { + return; + } + } + CloseEvent?.Invoke(ControlId); + Form?.Close(); + Dispose(); + } + + protected virtual bool Save() { return true; } + + /// + /// Дубликат контрола + /// + /// + public virtual BaseControlViewEntityElement Clone() { return null; } + + /// + /// Установка флага, что есть изменения + /// + 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 BaseControlViewEntityElement() + { + InitializeComponent(); + } + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.resx b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityElement.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Common/DesktopTools/Controls/BaseControlViewEntityList.cs b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityList.cs index e7e7380..150c3c5 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityList.cs +++ b/DepartmentPortal/Common/DesktopTools/Controls/BaseControlViewEntityList.cs @@ -26,7 +26,7 @@ namespace DesktopTools.Controls /// public virtual void Close() { - CloseEvent?.Invoke(Id); + CloseEvent?.Invoke(ControlId); Dispose(); } @@ -39,7 +39,7 @@ namespace DesktopTools.Controls /// /// Идентификатор контрола /// - public Guid Id { get; protected set; } + public Guid ControlId { get; protected set; } /// /// Заголовок контрола diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs new file mode 100644 index 0000000..5a5ec29 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.Designer.cs @@ -0,0 +1,107 @@ + +namespace DesktopTools.Controls +{ + partial class GenericControlEntityElement + { + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + this.toolStripActions = new System.Windows.Forms.ToolStrip(); + this.toolStripButtonSave = new System.Windows.Forms.ToolStripButton(); + this.toolStripButtonReload = new System.Windows.Forms.ToolStripButton(); + this.toolStripButtonClose = new System.Windows.Forms.ToolStripButton(); + this.panelContainer = new System.Windows.Forms.Panel(); + this.toolStripActions.SuspendLayout(); + this.SuspendLayout(); + // + // toolStripActions + // + this.toolStripActions.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripButtonSave, + this.toolStripButtonReload, + this.toolStripButtonClose}); + this.toolStripActions.Location = new System.Drawing.Point(0, 0); + this.toolStripActions.Name = "toolStripActions"; + this.toolStripActions.Size = new System.Drawing.Size(594, 25); + this.toolStripActions.TabIndex = 0; + this.toolStripActions.Text = "toolStrip1"; + // + // toolStripButtonSave + // + this.toolStripButtonSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButtonSave.Image = global::DesktopTools.Properties.Resources.Save; + this.toolStripButtonSave.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButtonSave.Name = "toolStripButtonSave"; + this.toolStripButtonSave.Size = new System.Drawing.Size(23, 22); + this.toolStripButtonSave.Text = "Сохранить"; + // + // toolStripButtonReload + // + this.toolStripButtonReload.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButtonReload.Image = global::DesktopTools.Properties.Resources.Reload; + this.toolStripButtonReload.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButtonReload.Name = "toolStripButtonReload"; + this.toolStripButtonReload.Size = new System.Drawing.Size(23, 22); + this.toolStripButtonReload.Text = "Обновить"; + // + // toolStripButtonClose + // + this.toolStripButtonClose.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; + this.toolStripButtonClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButtonClose.Image = global::DesktopTools.Properties.Resources.Close; + this.toolStripButtonClose.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButtonClose.Name = "toolStripButtonClose"; + this.toolStripButtonClose.Size = new System.Drawing.Size(23, 22); + this.toolStripButtonClose.Text = "Закрыть"; + // + // panelContainer + // + this.panelContainer.AutoScroll = true; + this.panelContainer.Dock = System.Windows.Forms.DockStyle.Fill; + this.panelContainer.Location = new System.Drawing.Point(0, 25); + this.panelContainer.Name = "panelContainer"; + this.panelContainer.Size = new System.Drawing.Size(594, 485); + this.panelContainer.TabIndex = 1; + // + // GenericControlEntityElement + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + 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.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.ToolStrip toolStripActions; + private System.Windows.Forms.ToolStripButton toolStripButtonSave; + private System.Windows.Forms.ToolStripButton toolStripButtonReload; + private System.Windows.Forms.ToolStripButton toolStripButtonClose; + private System.Windows.Forms.Panel panelContainer; + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs new file mode 100644 index 0000000..9bb77f7 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.cs @@ -0,0 +1,151 @@ +using DesktopTools.BaseControls; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; +using ModuleTools.BusinessLogics; +using ModuleTools.ViewModels; +using System; +using System.Linq; +using System.Reflection; +using System.Windows.Forms; + +namespace DesktopTools.Controls +{ + public partial class GenericControlEntityElement : BaseControlViewEntityElement + 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 DropValues; + + private event Func CheckValues; + + private event Action GetValues; + private E Element { get; set; } + + public GenericControlEntityElement(Guid? id) + { + InitializeComponent(); + InitEvents(); + _businessLogic = DependencyManager.Instance.Resolve(); + Element = _businessLogic.GetElement(new G { Id = id }); + } + + + public override void Open() + { + base.Open(); + if (panelContainer.Controls.Count == 0) + { + Configurate(); + } + //LoadList(); + } + + 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 (property.PropertyType.Name.ToLower()) + { + case "string": + control = new BaseControlText(property.Name); + break; + case "int32": + control = new BaseControlInt(property.Name); + break; + } + if (control == null) + { + continue; + } + if (Element != null) + { + control.SetValueToControl(property.GetValue(Element)); + } + + var widthTitle = control.SetTitle(attribute.DisplayName); + if (widthTitle > titleWidth) + { + titleWidth = widthTitle; + } + + control.OnValueChangeEvent += ValueChange; + DropValues += control.DropValue; + CheckValues += control.CheckValue; + SetTitleWidth += control.SetTitleWidth; + GetValues += control.FillPropertyToObject; + + 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; + + control.SetReadOnly(attribute.ReadOnly); + control.SetMustCheckValue(attribute.MustHaveValue); + + 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}"); + } + + MessageBox.Show("Сохранение прошло успешно", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + return true; + } + + return false; + } + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.resx b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityElement.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Common/DesktopTools/Controls/GenericControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityList.cs index b0aa7a5..ffbb43e 100644 --- a/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityList.cs +++ b/DepartmentPortal/Common/DesktopTools/Controls/GenericControlEntityList.cs @@ -6,15 +6,17 @@ 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 : BaseControlViewEntityList - where G : GetBindingModel - where S : SetBindingModel - where L: ListViewModel + where G : GetBindingModel, new() + where S : SetBindingModel, new() + where L : ListViewModel where E : ElementViewModel where BL : GenericBusinessLogic { @@ -33,14 +35,14 @@ namespace DesktopTools.Controls _businessLogic = DependencyManager.Instance.Resolve(); } - public override void Open() + public override async void Open() { base.Open(); if (dataGridViewList.Columns.Count == 0) { Configurate(GetConfig()); } - LoadList(); + await LoadListAsync(); } public override void Close() @@ -54,7 +56,7 @@ namespace DesktopTools.Controls /// Настройки private void Configurate(ControlViewEntityListConfiguration config) { - if(config == null) + if (config == null) { return; } @@ -66,7 +68,8 @@ namespace DesktopTools.Controls var attr = property.GetCustomAttribute(); if (attr != null) { - dataGridViewList.Columns.Add(new DataGridViewTextBoxColumn + var colIndex = attr.DisplayName == "Идентификатор" ? 0 : dataGridViewList.Columns.Count; + dataGridViewList.Columns.Insert(colIndex, new DataGridViewTextBoxColumn { HeaderText = attr.DisplayName, Name = string.Format("Column{0}", property.Name), @@ -158,10 +161,10 @@ namespace DesktopTools.Controls 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 += (object sender, EventArgs e) => { LoadList(); }; + toolStripButtonRef.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; toolStripButtonClose.Click += (object sender, EventArgs e) => { Close(); }; - buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); }; + buttonSearch.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; }; dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => @@ -184,37 +187,37 @@ namespace DesktopTools.Controls CallUpdElementEvent(); }; - toolStripButtonPrev.Click += (object sender, EventArgs e) => + toolStripButtonPrev.Click += async (object sender, EventArgs e) => { if (int.TryParse(toolStripTextBoxPage.Text, out int page)) { toolStripTextBoxPage.Text = (page - 1).ToString(); - LoadList(); + await LoadListAsync(); } }; - toolStripButtonNext.Click += (object sender, EventArgs e) => + toolStripButtonNext.Click += async (object sender, EventArgs e) => { if (int.TryParse(toolStripTextBoxPage.Text, out int page)) { toolStripTextBoxPage.Text = (page + 1).ToString(); - LoadList(); + await LoadListAsync(); } }; - toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) => + toolStripTextBoxPage.KeyDown += async (object sender, KeyEventArgs e) => { if (e.KeyData == Keys.Enter) { - LoadList(); + await LoadListAsync(); } }; - toolStripComboBoxPageNames.SelectedIndexChanged += (object sender, EventArgs e) => { LoadList(); }; + toolStripComboBoxPageNames.SelectedIndexChanged += async (object sender, EventArgs e) => { await LoadListAsync(); }; } /// /// Вызов события загрузки данных на datagrid /// - private void LoadList() + private async Task LoadListAsync() { var cursor = Cursor.Current; L data = null; @@ -229,7 +232,7 @@ namespace DesktopTools.Controls { if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxPage.Tag.ToString(), out int count)) { - data = GetDataWithPageNumber(page, count); + await Task.Run(() => data = GetDataWithPageNumber(page, count)); } } // поименная @@ -238,13 +241,13 @@ namespace DesktopTools.Controls var key = toolStripComboBoxPageNames.Text; if (key.IsNotEmpty()) { - data = GetDataWithPageName(key); + await Task.Run(() => data = GetDataWithPageName(key)); } } } else { - data = GetData(); + await Task.Run(() => data = GetData()); } if (data == null) @@ -254,7 +257,7 @@ namespace DesktopTools.Controls } toolStripLabelCountPages.Text = $"из {data.MaxCount}"; - FillDataOnGrid(data.List); + FillDataOnGridAsync(data.List); } finally { @@ -266,7 +269,7 @@ namespace DesktopTools.Controls /// Заполнение таблицы /// /// - private void FillDataOnGrid(List data) + private void FillDataOnGridAsync(List data) { if (data == null) { @@ -288,7 +291,7 @@ namespace DesktopTools.Controls /// /// Вызов события при добавлении элемента /// - private void CallAddElementEvent() => AddElement(); + private void CallAddElementEvent() => LaunchControl(null); /// /// Вызов события при изменении элемента @@ -297,8 +300,7 @@ namespace DesktopTools.Controls { foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) { - var id = new Guid(selected.Cells[0].Value.ToString()); - UpdElement(id); + LaunchControl(new Guid(selected.Cells[0].Value.ToString())); } } @@ -309,21 +311,60 @@ namespace DesktopTools.Controls { if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + var cursor = Cursor.Current; + try { - var id = new Guid(selected.Cells[0].Value.ToString()); - DelElement(id); + 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; } } } - protected virtual void AddElement() { } + /// + /// Создание формы с контролом для работы с элементом + /// + /// + private void LaunchControl(Guid? id) + { + try + { + var control = new GenericControlEntityElement(id); + control.Open(); + 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 virtual void UpdElement(Guid id) { } - - protected virtual void DelElement(Guid id) { } - - protected virtual ControlViewEntityListConfiguration GetConfig() { return null; } + protected virtual ControlViewEntityListConfiguration GetConfig() => new(); protected virtual L GetData() { return null; } diff --git a/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs b/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs new file mode 100644 index 0000000..7cd0172 --- /dev/null +++ b/DepartmentPortal/Common/DesktopTools/Helpers/DialogHelper.cs @@ -0,0 +1,15 @@ +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 MessageQuestion(string message, string title) => + MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question); + } +} diff --git a/DepartmentPortal/Common/DesktopTools/Properties/Resources.Designer.cs b/DepartmentPortal/Common/DesktopTools/Properties/Resources.Designer.cs index 3e6b29a..baf6ccf 100644 --- a/DepartmentPortal/Common/DesktopTools/Properties/Resources.Designer.cs +++ b/DepartmentPortal/Common/DesktopTools/Properties/Resources.Designer.cs @@ -130,6 +130,16 @@ namespace DesktopTools.Properties { } } + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Reload { + get { + object obj = ResourceManager.GetObject("Reload", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// @@ -140,6 +150,16 @@ namespace DesktopTools.Properties { } } + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Save { + get { + object obj = ResourceManager.GetObject("Save", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// diff --git a/DepartmentPortal/Common/DesktopTools/Properties/Resources.resx b/DepartmentPortal/Common/DesktopTools/Properties/Resources.resx index 7708092..e565783 100644 --- a/DepartmentPortal/Common/DesktopTools/Properties/Resources.resx +++ b/DepartmentPortal/Common/DesktopTools/Properties/Resources.resx @@ -112,43 +112,49 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Resources\Add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Clear.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Del.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Down.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Left.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - + ..\Resources\Ref.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\Right.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\Upd.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Left.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Resources\Search.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\Up.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\Resources\Upd.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\Del.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Down.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Save.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Clear.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Reload.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a \ No newline at end of file diff --git a/DepartmentPortal/Common/DesktopTools/Resources/Reload.png b/DepartmentPortal/Common/DesktopTools/Resources/Reload.png new file mode 100644 index 0000000..b488c43 Binary files /dev/null and b/DepartmentPortal/Common/DesktopTools/Resources/Reload.png differ diff --git a/DepartmentPortal/Common/DesktopTools/Resources/Save.png b/DepartmentPortal/Common/DesktopTools/Resources/Save.png new file mode 100644 index 0000000..c488b69 Binary files /dev/null and b/DepartmentPortal/Common/DesktopTools/Resources/Save.png differ diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/MapConfigurationAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/MapConfigurationAttribute.cs index 358439b..ef1374d 100644 --- a/DepartmentPortal/Common/ModuleTools/Attributes/MapConfigurationAttribute.cs +++ b/DepartmentPortal/Common/ModuleTools/Attributes/MapConfigurationAttribute.cs @@ -19,24 +19,20 @@ namespace ModuleTools.Attributes /// /// Сложное свойство (свойствое в другом классе-свойстве) /// - public bool IsDifficle { get; set; } + public bool IsDifficle { get; set; } = false; /// /// Можно копировать поле даже при доступе без прав /// - public bool AllowCopyWithoutRigth { get; set; } + public bool AllowCopyWithoutRigth { get; set; } = true; /// /// Настройка для полей сущности правил маппинга /// /// Название свойства с класса, из которого извлекаем данные - /// Сложное свойство (свойствое в другом классе-свойстве) - /// Можно копировать поле даже при доступе без прав - public MapConfigurationAttribute(string propertyNameFromMModel, bool isDifficle = false, bool allowCopyWithoutRigth = true) + public MapConfigurationAttribute(string propertyNameFromMModel) { PropertyNameFromModel = propertyNameFromMModel; - IsDifficle = isDifficle; - AllowCopyWithoutRigth = allowCopyWithoutRigth; } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs new file mode 100644 index 0000000..594fe45 --- /dev/null +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnElementPropertyAttribute.cs @@ -0,0 +1,59 @@ +using System; + +namespace ModuleTools.Attributes +{ + /// + /// Настройка отображения свойства класса при выводе объекта класса (требуется для автоматизации вывода элемента, + /// применяется к классам ElementViewModel) + /// + [AttributeUsage(AttributeTargets.Property)] + public class ViewModelOnElementPropertyAttribute : Attribute + { + /// + /// Название на форме + /// + public string DisplayName { get; set; } + + /// + /// Поле должно быть обязательно заполнено + /// + public bool MustHaveValue { get; set; } = false; + + /// + /// Запрет на редактирование, только вывод + /// + public bool ReadOnly { get; set; } = false; + + /// + /// Ширина + /// + public int? Width { get; set; } + + /// + /// Высота + /// + public int? Height { get; set; } + + /// + /// Конструктор + /// + /// Название на форме + public ViewModelOnElementPropertyAttribute(string displayName) + { + DisplayName = displayName; + } + + /// + /// Конструктор + /// + /// Название на форме + /// Ширина + /// Высота + public ViewModelOnElementPropertyAttribute(string displayName, int width, int height) + { + DisplayName = displayName; + Width = width; + Height = height; + } + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs index 5c30c61..d7c3bbc 100644 --- a/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs +++ b/DepartmentPortal/Common/ModuleTools/Attributes/ViewModelOnListPropertyAttribute.cs @@ -17,27 +17,24 @@ namespace ModuleTools.Attributes /// /// Скрывать или нет при выводе списка /// - public bool IsHide { get; set; } + public bool IsHide { get; set; } = false; /// /// Ширина колонки /// - public int? ColumnWidth { get; set; } + public int? ColumnWidth { get; set; } = null; /// /// Настройка отображения элемента в контролах /// /// Название на форме - /// Скрывать или нет - public ViewModelOnListPropertyAttribute(string displayName, bool isHide = false) + public ViewModelOnListPropertyAttribute(string displayName) { DisplayName = displayName; - ColumnWidth = null; - IsHide = isHide; } /// - /// Конструктор + /// Настройка отображения элемента в контролах /// /// Название на форме /// Ширина колонки @@ -45,7 +42,6 @@ namespace ModuleTools.Attributes { DisplayName = displayName; ColumnWidth = columnWidth; - IsHide = false; } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/BindingModels/SetBindingModel.cs b/DepartmentPortal/Common/ModuleTools/BindingModels/SetBindingModel.cs index 4a94cfd..27f748a 100644 --- a/DepartmentPortal/Common/ModuleTools/BindingModels/SetBindingModel.cs +++ b/DepartmentPortal/Common/ModuleTools/BindingModels/SetBindingModel.cs @@ -1,4 +1,5 @@ -using System; +using ModuleTools.Attributes; +using System; namespace ModuleTools.BindingModels { @@ -10,6 +11,7 @@ namespace ModuleTools.BindingModels /// /// Идентификатор записи /// + [MapConfiguration("Id")] public Guid Id { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs index 0d2252b..39f72b4 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs @@ -70,10 +70,10 @@ namespace ModuleTools.BusinessLogics { if (Security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity))) { - Errors.Add(("Ошибка безопасности", Security.ErrorMessage)); - return true; + return false; } - return false; + Errors.Add(("Ошибка безопасности", Security.ErrorMessage)); + return true; } /// @@ -86,7 +86,7 @@ namespace ModuleTools.BusinessLogics Errors.Clear(); try { - model.HaveRight = NoAccess(model, AccessType.View); + model.HaveRight = !NoAccess(model, AccessType.View); if (model.HaveRight && !_allowSimpleView) { throw new MethodAccessException("Нет прав на получение списка"); @@ -117,7 +117,7 @@ namespace ModuleTools.BusinessLogics Errors.Clear(); try { - model.HaveRight = NoAccess(model, AccessType.View); + model.HaveRight = !NoAccess(model, AccessType.View); if (model.HaveRight && !_allowSimpleView) { throw new MethodAccessException("Нет прав на получение списка"); diff --git a/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs b/DepartmentPortal/Common/ModuleTools/ViewModels/ElementViewModel.cs index 17ef36a..dc1e826 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)] + [ViewModelOnListProperty("Идентификатор", IsHide = true)] [MapConfiguration("Id")] public Guid Id { get; set; } } diff --git a/DepartmentPortal/DepartmentPortalDesctop/FormEnter.Designer.cs b/DepartmentPortal/DepartmentPortalDesctop/FormEnter.Designer.cs index e335ee2..88bffc0 100644 --- a/DepartmentPortal/DepartmentPortalDesctop/FormEnter.Designer.cs +++ b/DepartmentPortal/DepartmentPortalDesctop/FormEnter.Designer.cs @@ -72,7 +72,6 @@ namespace DepartmentPortalDesctop this.textBoxPassword.Size = new System.Drawing.Size(242, 23); this.textBoxPassword.TabIndex = 3; this.textBoxPassword.UseSystemPasswordChar = true; - this.textBoxPassword.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxPassword_KeyDown); // // buttonEnter // @@ -91,6 +90,7 @@ namespace DepartmentPortalDesctop // // FormEnter // + this.AcceptButton = this.buttonEnter; this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(324, 131); diff --git a/DepartmentPortal/DepartmentPortalDesctop/FormEnter.cs b/DepartmentPortal/DepartmentPortalDesctop/FormEnter.cs index 008995e..5a5b36d 100644 --- a/DepartmentPortal/DepartmentPortalDesctop/FormEnter.cs +++ b/DepartmentPortal/DepartmentPortalDesctop/FormEnter.cs @@ -18,7 +18,7 @@ namespace DepartmentPortalDesctop InitializeComponent(); } - private void Login() + private void ButtonEnter_Click(object sender, EventArgs e) { if (textBoxLogin.Text.IsEmpty()) { @@ -40,15 +40,5 @@ namespace DepartmentPortalDesctop ErrorMessanger.PrintErrorMessage("При аутентфикации возникла ошибка: ", new List> { new KeyValuePair("Аутентфикация", ex.Message) }); } } - - private void ButtonEnter_Click(object sender, EventArgs e) => Login(); - - private void TextBoxPassword_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - Login(); - } - } } } diff --git a/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs b/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs index 3d10871..2bcd419 100644 --- a/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs +++ b/DepartmentPortal/DepartmentPortalDesctop/FormMain.cs @@ -66,16 +66,16 @@ namespace DepartmentPortalDesctop } var ctrl = _baseControls[id].Clone(); - if (!_controls.ContainsKey(ctrl.Id)) + if (!_controls.ContainsKey(ctrl.ControlId)) { ctrl.CloseEventAdd += CloseControl; ctrl.Dock = DockStyle.Fill; ctrl.Open(); - _controls.Add(ctrl.Id, ctrl); + _controls.Add(ctrl.ControlId, ctrl); splitContainerMain.Panel1.Controls.Clear(); splitContainerMain.Panel1.Controls.Add(ctrl); - dataGridViewControls.Rows.Add(new object[] { ctrl.Id, ctrl.Title }); + dataGridViewControls.Rows.Add(new object[] { ctrl.ControlId, ctrl.Title }); dataGridViewControls.Rows[^1].Selected = true; } } @@ -97,7 +97,7 @@ namespace DepartmentPortalDesctop } for (int i = 0; i < dataGridViewControls.Rows.Count; ++i) { - if (dataGridViewControls.Rows[i].Cells[0].Value.ToString() == ctrl.Id.ToString()) + if (dataGridViewControls.Rows[i].Cells[0].Value.ToString() == ctrl.ControlId.ToString()) { dataGridViewControls.Rows.RemoveAt(i); if (i < dataGridViewControls.Rows.Count - 1) @@ -113,7 +113,7 @@ namespace DepartmentPortalDesctop break; } } - _controls.Remove(ctrl.Id); + _controls.Remove(ctrl.ControlId); } /// diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/AccessBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/AccessBindingModels.cs index 4da537b..7686133 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/AccessBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/AccessBindingModels.cs @@ -1,4 +1,5 @@ -using ModuleTools.BindingModels; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; using ModuleTools.Enums; using System; using System.ComponentModel.DataAnnotations; @@ -23,11 +24,14 @@ namespace SecurityBusinessLogic.BindingModels /// public class AccessSetBindingModel : SetBindingModel { + [MapConfiguration("RoleId")] public Guid RoleId { get; set; } [Required(ErrorMessage = "required")] - public AccessOperation Operation { get; set; } + [MapConfiguration("AccessOperation")] + public AccessOperation AccessOperation { get; set; } + [MapConfiguration("AccessType")] public AccessType AccessType { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/EnviromentSettingBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/EnviromentSettingBindingModels.cs index 3d0a232..36256a5 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/EnviromentSettingBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/EnviromentSettingBindingModels.cs @@ -1,4 +1,5 @@ -using ModuleTools.BindingModels; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; using System.ComponentModel.DataAnnotations; namespace SecurityBusinessLogic.BindingModels @@ -17,12 +18,15 @@ namespace SecurityBusinessLogic.BindingModels public class EnviromentSettingSetBindingModel : SetBindingModel { [Required(ErrorMessage = "required")] + [MapConfiguration("Key")] public string Key { get; set; } [Required(ErrorMessage = "required")] + [MapConfiguration("Value")] public string Value { get; set; } [Required(ErrorMessage = "required")] + [MapConfiguration("Description")] public string Description { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs index 6849acc..c60bae7 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs @@ -1,4 +1,5 @@ -using ModuleTools.BindingModels; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; using System.ComponentModel.DataAnnotations; namespace SecurityBusinessLogic.BindingModels @@ -14,9 +15,11 @@ namespace SecurityBusinessLogic.BindingModels public class RoleSetBindingModel : SetBindingModel { [Required(ErrorMessage = "required")] + [MapConfiguration("RoleName")] public string RoleName { get; set; } [Required(ErrorMessage = "required")] + [MapConfiguration("RolePriority")] public int RolePriority { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs index 56b6111..0b7d64f 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs @@ -1,6 +1,6 @@ -using ModuleTools.BindingModels; +using ModuleTools.Attributes; +using ModuleTools.BindingModels; using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SecurityBusinessLogic.BindingModels @@ -18,25 +18,34 @@ namespace SecurityBusinessLogic.BindingModels public class UserSetBindingModel : SetBindingModel { [Required(ErrorMessage = "required")] + [MapConfiguration("Login")] public string Login { get; set; } [Required(ErrorMessage = "required")] public string Password { get; set; } + [MapConfiguration("StudentId")] public Guid? StudentId { get; set; } + [MapConfiguration("LecturerId")] public Guid? LecturerId { get; set; } + [MapConfiguration("EmployeeId")] public Guid? EmployeeId { get; set; } + [MapConfiguration("Avatar")] public byte[] Avatar { get; set; } + [MapConfiguration("DateLastVisit")] public DateTime? DateLastVisit { get; set; } + [MapConfiguration("IsBanned")] public bool IsBanned { get; set; } + [MapConfiguration("DateBanned")] public DateTime? DateBanned { get; set; } + [MapConfiguration("CountAttempt")] public int CountAttempt { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs index d375835..f211e8d 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/AccessViewModels.cs @@ -19,7 +19,7 @@ namespace SecurityBusinessLogic.ViewModels public Guid RoleId { get; set; } [ViewModelOnListProperty("Роль", 100)] - [MapConfiguration("Role.RoleName", true, AllowCopyWithoutRigth = false)] + [MapConfiguration("Role.RoleName", IsDifficle = true, AllowCopyWithoutRigth = false)] public string RoleName { get; set; } [MapConfiguration("AccessOperation", AllowCopyWithoutRigth = false)] diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs index d970518..0708c4f 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/EnviromentSettingViewModels.cs @@ -14,14 +14,17 @@ namespace SecurityBusinessLogic.ViewModels public class EnviromentSettingViewModel : ElementViewModel { [ViewModelOnListProperty("Ключ")] + [ViewModelOnElementProperty("Ключ", MustHaveValue = true, ReadOnly = true)] [MapConfiguration("Key", AllowCopyWithoutRigth = false)] public string Key { get; set; } [ViewModelOnListProperty("Значение")] + [ViewModelOnElementProperty("Значение", MustHaveValue = true)] [MapConfiguration("Value", AllowCopyWithoutRigth = false)] public string Value { get; set; } [ViewModelOnListProperty("Описание")] + [ViewModelOnElementProperty("Описание")] [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 bc975a9..5433185 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/RoleViewModels.cs @@ -14,10 +14,12 @@ namespace SecurityBusinessLogic.ViewModels public class RoleViewModel : ElementViewModel { [ViewModelOnListProperty("Название роли")] + [ViewModelOnElementProperty("Название роли")] [MapConfiguration("RoleName")] public string RoleName { get; set; } [ViewModelOnListProperty("Приоритет", 100)] + [ViewModelOnElementProperty("Приоритет")] [MapConfiguration("RolePriority")] public int RolePriority { get; set; } diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs index bcdaf7c..9f5480d 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/ViewModels/UserViewModels.cs @@ -15,9 +15,13 @@ namespace SecurityBusinessLogic.ViewModels public class UserViewModel : ElementViewModel { [ViewModelOnListProperty("Пользователь")] + [ViewModelOnElementProperty("Логин")] [MapConfiguration("UserName")] public string Login { get; set; } + [MapConfiguration("PasswordHash", AllowCopyWithoutRigth = false)] + public string Password { get; set; } + [MapConfiguration("StudentId")] public Guid? StudentId { get; set; } diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs index 818eaa8..5fa71cf 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs @@ -22,7 +22,7 @@ namespace SecurityImplementation.SecurityDatabaseImplementation { using var context = DatabaseManager.GetContext; - var exsistEntity = context.Accesses.FirstOrDefault(x => x.AccessOperation == model.Operation && x.RoleId == model.RoleId && x.AccessType == model.AccessType); + var exsistEntity = context.Accesses.FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType); if (exsistEntity == null) { var entity = Mapper.MapToClass(model, true); diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs index d1ae95e..bd4fadd 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/AccessesControl.cs @@ -20,12 +20,12 @@ namespace SecurityWindowsDesktop.Controls InitializeComponent(); _roleBusinessLogic = DependencyManager.Instance.Resolve(); Title = "Доступы"; - Id = new Guid("6eebc4c4-cb86-4368-93e0-33dbdbb7409a"); + ControlId = new Guid("6eebc4c4-cb86-4368-93e0-33dbdbb7409a"); Order = 1; AccessOperation = AccessOperation.Доступы; } - public override BaseControlViewEntityList Clone() => new AccessesControl() { Id = Guid.NewGuid() }; + public override BaseControlViewEntityList Clone() => new AccessesControl() { ControlId = Guid.NewGuid() }; protected override ControlViewEntityListConfiguration GetConfig() => new() { diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs index 9b02f5b..2b8430a 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/EnviromentSettingControl.cs @@ -15,12 +15,12 @@ namespace SecurityWindowsDesktop.Controls { InitializeComponent(); Title = "Настройки Среды"; - Id = new Guid("b3865c23-b1db-475b-b95c-aa51edc60388"); + ControlId = new Guid("b3865c23-b1db-475b-b95c-aa51edc60388"); Order = 1; AccessOperation = AccessOperation.НастройкиСреды; } - public override BaseControlViewEntityList Clone() => new EnviromentSettingControl() { Id = Guid.NewGuid() }; + public override BaseControlViewEntityList Clone() => new EnviromentSettingControl() { ControlId = Guid.NewGuid() }; protected override ControlViewEntityListConfiguration GetConfig() => new() { diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs index d50577e..4073835 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/RolesControl.cs @@ -15,12 +15,12 @@ namespace SecurityWindowsDesktop.Controls { InitializeComponent(); Title = "Роли"; - Id = new Guid("6a33ce5c-e950-4294-9f75-2a0b35941bf7"); + ControlId = new Guid("6a33ce5c-e950-4294-9f75-2a0b35941bf7"); Order = 1; AccessOperation = AccessOperation.Роли; } - public override BaseControlViewEntityList Clone() => new RolesControl() { Id = Guid.NewGuid() }; + public override BaseControlViewEntityList Clone() => new RolesControl() { ControlId = Guid.NewGuid() }; protected override ControlViewEntityListConfiguration GetConfig() => new() { diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs index 1bb23cd..e437dbb 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/Controls/UsersControl.cs @@ -15,12 +15,12 @@ namespace SecurityWindowsDesktop.Controls { InitializeComponent(); Title = "Пользователи"; - Id = new Guid("d5596997-d1f5-4e5e-b94b-6bdd6bca3452"); + ControlId = new Guid("d5596997-d1f5-4e5e-b94b-6bdd6bca3452"); Order = 1; AccessOperation = AccessOperation.Пользователи; } - public override BaseControlViewEntityList Clone() => new UsersControl() { Id = Guid.NewGuid() }; + public override BaseControlViewEntityList Clone() => new UsersControl() { ControlId = Guid.NewGuid() }; protected override ControlViewEntityListConfiguration GetConfig() => new() { diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs index bae0957..18fa103 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/SecurityWindowDesktopExtension.cs @@ -46,7 +46,7 @@ namespace SecurityWindowsDesktop { list.Add(new WindowDesktopExtensionControlModel { - Id = cntrl.Id, + Id = cntrl.ControlId, Order = cntrl.Order, Title = cntrl.Title, Control = cntrl