Compare commits

..

2 Commits

8 changed files with 235 additions and 205 deletions

View File

@ -69,7 +69,7 @@ namespace ComponentsLibrary
{ {
if (string.IsNullOrEmpty(emailPattern)) if (string.IsNullOrEmpty(emailPattern))
{ {
return true; // Если шаблон не задан, любая строка считается валидной. return true;
} }
return Regex.IsMatch(email, emailPattern); return Regex.IsMatch(email, emailPattern);
} }

View File

@ -1,5 +1,6 @@
using System.Reflection; using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;
namespace ComponentsLibrary namespace ComponentsLibrary
{ {
@ -62,38 +63,84 @@ namespace ComponentsLibrary
foreach (var prop in properties) foreach (var prop in properties)
{ {
string propertyValue = prop.GetValue(item)?.ToString().Replace(',', '.') ?? string.Empty; string propertyValue = prop.GetValue(item)?.ToString() ?? string.Empty;
text = text.Replace("{" + prop.Name + "}", propertyValue); text = text.Replace("{" + prop.Name + "}", propertyValue);
} }
return text; return text;
} }
// Публичный параметризованный метод для получения объекта из выбранной строки // Публичный параметризованный метод для получения объекта из выбранной строки
public T? GetSelectedItem<T>() where T : new() public T? GetSelectedItem<T>() where T : new()
{ {
var item = listBox.SelectedItem; var item = listBox.SelectedItem;
if (item != null) if (item != null)
{ {
// Получаем строковое значение
string? selectedString = item?.ToString();
if (selectedString != null) {
T obj = new T();
MatchCollection matches = Regex.Matches(selectedString, @"\d+(\,\d+)?"); PropertyInfo[] properties = typeof(T).GetProperties();
string layout = layoutString;
string pattern = @"^(.*?){T}.*?(.*?){P}";
PropertyInfo[] properties = typeof(T).GetProperties(); //string input2 = "Температура воздуха ТЕМПЕРАТУРА ВЫСОКАЯ, давление НИЗКОЕ";
string? selectedString = item?.ToString();
for (int i = 0; i < properties.Length && i < matches.Count; i++) if (selectedString != null)
{ {
object value = Convert.ChangeType(matches[i].Value.Replace(",", "."), properties[i].PropertyType); T obj = new T();
properties[i].SetValue(obj, value);
} Regex regex = new Regex(pattern);
return obj; Match match = regex.Match(layout);
}
} string[] staticText = new string[properties.Length];
return default;
} if (match.Success)
} {
// Извлекаем текст до {T} и до {P}
//string beforeT = match.Groups[1].Value;
//string beforeP = match.Groups[2].Value;
for (int i = 0; i < staticText.Length; i++)
{
staticText[i] = match.Groups[i+1].Value;
}
//string pattern2 = $@"{beforeT}(.*?)\{beforeP}(.*)\{beforeEnd}";
//"Температура воздуха (.*?)\\, давление (.*)\\, такие дела"
string patternStatic = $@"";
for (int i = 0; i < staticText.Length; i++)
{
if (i == staticText.Length - 1)
{
patternStatic += $"{staticText[i]}(.*)";
}
else {
patternStatic += $"{staticText[i]}(.*?)\\";
}
}
Regex regexValues = new Regex(patternStatic);
Match matchValues = regexValues.Match(selectedString);
if (matchValues.Success)
{
//object val1 = matchValues.Groups[1].Value;
//object val2 = matchValues.Groups[2].Value;
for (int i = 0; i < properties.Length; i++)
{
object value = Convert.ChangeType(matchValues.Groups[i+1].Value, properties[i].PropertyType);
properties[i].SetValue(obj, value);
}
return obj;
}
}
}
}
return default;
}
}
} }

View File

@ -20,55 +20,43 @@
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Код, автоматически созданный конструктором компонентов #region Код, автоматически созданный конструктором компонентов
/// <summary> /// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте /// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода. /// содержимое этого метода с помощью редактора кода.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
comboBoxComponent = new ComboBox(); comboBoxComponent = new ComboBox();
buttonClear = new Button(); SuspendLayout();
SuspendLayout(); //
// // comboBoxComponent
// comboBoxComponent //
// comboBoxComponent.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxComponent.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.FormattingEnabled = true; comboBoxComponent.Items.AddRange(new object[] { "Значение 1", "Значение 2", "Значение 3", "Значение 4", "Значение 5" });
comboBoxComponent.Items.AddRange(new object[] { "Значение 1", "Значение 2", "Значение 3", "Значение 4", "Значение 5" }); comboBoxComponent.Location = new Point(17, 31);
comboBoxComponent.Location = new Point(15, 23); comboBoxComponent.Margin = new Padding(3, 4, 3, 4);
comboBoxComponent.Name = "comboBoxComponent"; comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(121, 23); comboBoxComponent.Size = new Size(138, 28);
comboBoxComponent.TabIndex = 0; comboBoxComponent.TabIndex = 0;
comboBoxComponent.SelectedIndexChanged += comboBoxComponent_SelectedIndexChanged; comboBoxComponent.SelectedIndexChanged += comboBoxComponent_SelectedIndexChanged;
// //
// buttonClear // VisualSelectionComponent
// //
buttonClear.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; AutoScaleDimensions = new SizeF(8F, 20F);
buttonClear.Location = new Point(16, 56); AutoScaleMode = AutoScaleMode.Font;
buttonClear.Name = "buttonClear"; BorderStyle = BorderStyle.FixedSingle;
buttonClear.Size = new Size(120, 23); Controls.Add(comboBoxComponent);
buttonClear.TabIndex = 1; Margin = new Padding(3, 4, 3, 4);
buttonClear.Text = "Очистить"; Name = "VisualSelectionComponent";
buttonClear.UseVisualStyleBackColor = true; Size = new Size(169, 87);
buttonClear.Click += buttonClear_Click; ResumeLayout(false);
// }
// VisualSelectionComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BorderStyle = BorderStyle.FixedSingle;
Controls.Add(buttonClear);
Controls.Add(comboBoxComponent);
Name = "VisualSelectionComponent";
Size = new Size(148, 94);
ResumeLayout(false);
}
#endregion #endregion
private ComboBox comboBoxComponent; private ComboBox comboBoxComponent;
private Button buttonClear;
} }
} }

View File

@ -11,24 +11,14 @@ namespace ComponentsLab
//Публичное свойство (set, get) для установки и получения выбранного значения (возвращает пустую строку, если нет выбранного значения) //Публичное свойство (set, get) для установки и получения выбранного значения (возвращает пустую строку, если нет выбранного значения)
public string comboBoxSelectedValue public string comboBoxSelectedValue
{ {
get get
{ {
if (comboBoxComponent.SelectedItem != null) return comboBoxComponent.SelectedItem?.ToString() ?? string.Empty;
{ }
return comboBoxComponent.GetItemText(comboBoxComponent.SelectedItem); set
} {
else comboBoxComponent.SelectedItem = value;
{ }
return string.Empty;
}
}
set
{
if (comboBoxComponent.SelectedIndex != -1)
{
comboBoxComponent.Items[comboBoxComponent.SelectedIndex] = value;
}
}
} }
// Событие, вызываемое при смене значения в ComboBox // Событие, вызываемое при смене значения в ComboBox
@ -42,13 +32,10 @@ namespace ComponentsLab
_changeComboBox?.Invoke(this, e); _changeComboBox?.Invoke(this, e);
} }
// Отдельный публичный метод отчистки списка // Отдельный публичный метод отчистки списка
private void buttonClear_Click(object sender, EventArgs e) public void clearList()
{ {
comboBoxComponent.Items.Clear(); comboBoxComponent.Items.Clear();
comboBoxComponent.Text = string.Empty;
comboBoxComponent.SelectedItem = null;
MessageBox.Show($"The list has been cleared");
} }

View File

@ -20,107 +20,101 @@
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
imageLoad = new ImageLoad(); imageLoad = new ImageLoad();
visualSelectionComponent1 = new VisualSelectionComponent(); visualSelectionComponent1 = new VisualSelectionComponent();
emailComponent = new ComponentsLibrary.Email(); emailComponent = new ComponentsLibrary.Email();
buttonCheckEmail = new Button(); buttonCheckEmail = new Button();
listBoxValues = new ComponentsLibrary.ListBoxValues(); listBoxValues = new ComponentsLibrary.ListBoxValues();
buttonGetListSelectedItem = new Button(); SuspendLayout();
SuspendLayout(); //
// // imageLoad
// imageLoad //
// imageLoad.Avatar = null;
imageLoad.Avatar = null; imageLoad.BorderStyle = BorderStyle.FixedSingle;
imageLoad.BorderStyle = BorderStyle.FixedSingle; imageLoad.Location = new Point(14, 16);
imageLoad.Location = new Point(12, 12); imageLoad.Margin = new Padding(3, 5, 3, 5);
imageLoad.Name = "imageLoad"; imageLoad.Name = "imageLoad";
imageLoad.Size = new Size(147, 92); imageLoad.Size = new Size(168, 122);
imageLoad.TabIndex = 0; imageLoad.TabIndex = 0;
imageLoad.AvatarChanged += ImageLoad_AvatarChanged; imageLoad.AvatarChanged += ImageLoad_AvatarChanged;
// //
// visualSelectionComponent1 // visualSelectionComponent1
// //
visualSelectionComponent1.BorderStyle = BorderStyle.FixedSingle; visualSelectionComponent1.BorderStyle = BorderStyle.FixedSingle;
visualSelectionComponent1.comboBoxSelectedValue = ""; visualSelectionComponent1.comboBoxSelectedValue = "";
visualSelectionComponent1.Location = new Point(181, 12); visualSelectionComponent1.Location = new Point(207, 16);
visualSelectionComponent1.Name = "visualSelectionComponent1"; visualSelectionComponent1.Margin = new Padding(3, 5, 3, 5);
visualSelectionComponent1.Size = new Size(156, 92); visualSelectionComponent1.Name = "visualSelectionComponent1";
visualSelectionComponent1.TabIndex = 1; visualSelectionComponent1.Size = new Size(178, 122);
visualSelectionComponent1.ChangeComboBox += visualSelectionComponent1_ChangeComboBox; visualSelectionComponent1.TabIndex = 1;
// visualSelectionComponent1.ChangeComboBox += visualSelectionComponent1_ChangeComboBox;
// emailComponent //
// // emailComponent
emailComponent.BorderStyle = BorderStyle.FixedSingle; //
emailComponent.EmailPattern = null; emailComponent.BorderStyle = BorderStyle.FixedSingle;
emailComponent.Location = new Point(356, 12); emailComponent.EmailPattern = null;
emailComponent.Name = "emailComponent"; emailComponent.Location = new Point(407, 16);
emailComponent.Size = new Size(172, 92); emailComponent.Margin = new Padding(3, 5, 3, 5);
emailComponent.TabIndex = 2; emailComponent.Name = "emailComponent";
emailComponent.ChangeEmail += emailComponent_ChangeEmail; emailComponent.Size = new Size(196, 122);
// emailComponent.TabIndex = 2;
// buttonCheckEmail emailComponent.ChangeEmail += emailComponent_ChangeEmail;
// //
buttonCheckEmail.Location = new Point(374, 66); // buttonCheckEmail
buttonCheckEmail.Name = "buttonCheckEmail"; //
buttonCheckEmail.Size = new Size(136, 23); buttonCheckEmail.Location = new Point(427, 88);
buttonCheckEmail.TabIndex = 3; buttonCheckEmail.Margin = new Padding(3, 4, 3, 4);
buttonCheckEmail.Text = "Проверить email"; buttonCheckEmail.Name = "buttonCheckEmail";
buttonCheckEmail.UseVisualStyleBackColor = true; buttonCheckEmail.Size = new Size(155, 31);
buttonCheckEmail.Click += buttonCheckEmail_Click; buttonCheckEmail.TabIndex = 3;
// buttonCheckEmail.Text = "Проверить email";
// listBoxValues buttonCheckEmail.UseVisualStyleBackColor = true;
// buttonCheckEmail.Click += buttonCheckEmail_Click;
listBoxValues.BorderStyle = BorderStyle.FixedSingle; //
listBoxValues.Location = new Point(12, 110); // listBoxValues
listBoxValues.Name = "listBoxValues"; //
listBoxValues.SelectedIndex = -1; listBoxValues.BorderStyle = BorderStyle.FixedSingle;
listBoxValues.Size = new Size(516, 224); listBoxValues.Location = new Point(14, 147);
listBoxValues.TabIndex = 4; listBoxValues.Margin = new Padding(3, 5, 3, 5);
listBoxValues.GetObject += listBoxValues_GetObject; listBoxValues.Name = "listBoxValues";
listBoxValues.Load += listBoxValues_Load; listBoxValues.SelectedIndex = -1;
// listBoxValues.Size = new Size(589, 298);
// buttonGetListSelectedItem listBoxValues.TabIndex = 4;
// listBoxValues.GetObject += listBoxValues_GetObject;
buttonGetListSelectedItem.Location = new Point(12, 341); listBoxValues.Load += listBoxValues_Load;
buttonGetListSelectedItem.Name = "buttonGetListSelectedItem"; //
buttonGetListSelectedItem.Size = new Size(133, 23); // FormComponents
buttonGetListSelectedItem.TabIndex = 5; //
buttonGetListSelectedItem.Text = "Получить объект"; AutoScaleDimensions = new SizeF(8F, 20F);
buttonGetListSelectedItem.UseVisualStyleBackColor = true; AutoScaleMode = AutoScaleMode.Font;
// ClientSize = new Size(630, 501);
// FormComponents Controls.Add(listBoxValues);
// Controls.Add(buttonCheckEmail);
AutoScaleDimensions = new SizeF(7F, 15F); Controls.Add(emailComponent);
AutoScaleMode = AutoScaleMode.Font; Controls.Add(visualSelectionComponent1);
ClientSize = new Size(551, 376); Controls.Add(imageLoad);
Controls.Add(buttonGetListSelectedItem); Margin = new Padding(3, 4, 3, 4);
Controls.Add(listBoxValues); Name = "FormComponents";
Controls.Add(buttonCheckEmail); Text = "FormComponents";
Controls.Add(emailComponent); ResumeLayout(false);
Controls.Add(visualSelectionComponent1); }
Controls.Add(imageLoad);
Name = "FormComponents";
Text = "FormComponents";
ResumeLayout(false);
}
#endregion #endregion
private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.ComponentModel.BackgroundWorker backgroundWorker1;
private ComponentsLab.ImageLoad imageLoad; private ComponentsLab.ImageLoad imageLoad;
private ComponentsLab.VisualSelectionComponent visualSelectionComponent1; private ComponentsLab.VisualSelectionComponent visualSelectionComponent1;
private ComponentsLibrary.Email emailComponent; private ComponentsLibrary.Email emailComponent;
private Button buttonCheckEmail; private Button buttonCheckEmail;
private ComponentsLibrary.ListBoxValues listBoxValues; private ComponentsLibrary.ListBoxValues listBoxValues;
private Button buttonGetListSelectedItem;
} }
} }

View File

@ -63,11 +63,11 @@ namespace ComponentsLab
listBoxValues.SetLayout("Òåìïåðàòóðà âîçäóõà {T}, äàâëåíèå {P}", '{', '}'); listBoxValues.SetLayout("Òåìïåðàòóðà âîçäóõà {T}, äàâëåíèå {P}", '{', '}');
var objectList = new List<ObjectClass> var objectList = new List<ObjectClass>
{ {
new ObjectClass { T = 20.5, P = 1012 }, new ObjectClass { T = "òåìïåðàòóðà âûñîêàÿ", P = "1008" },
new ObjectClass { T = 18.3, P = 1008 }, new ObjectClass { T = "òåìïåðàòóðà2", P = "1008" },
new ObjectClass { T = 50.1, P = 1010 }, new ObjectClass { T = "òåìïåðàòóðà3", P = 1010 },
new ObjectClass { T = 30.0, P = 1011 }, new ObjectClass { T = "òåìïåðàòóðà4", P = 1011 },
new ObjectClass { T = 18.9, P = 1009 }, new ObjectClass { T = "òåìïåðàòóðà5", P = 1009 },
}; };
listBoxValues.FillListBox(objectList); listBoxValues.FillListBox(objectList);
} }
@ -77,12 +77,23 @@ namespace ComponentsLab
try try
{ {
var selectedItem = listBoxValues.GetSelectedItem<ObjectClass>(); var selectedItem = listBoxValues.GetSelectedItem<ObjectClass>();
MessageBox.Show($"Îáúĺęň ńîçäŕí: {selectedItem}"); checkParametrs();
} }
catch (EmailException ex) catch (EmailException ex)
{ {
MessageBox.Show(ex.Message, $"Îøèáêà ïðè çàïîëíåíèè ñâîéñòâ îáúåêòà", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, $"Îøèáêà ïðè çàïîëíåíèè ñâîéñòâ îáúåêòà", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
}
private void checkParametrs()
{
ObjectClass obj = listBoxValues.GetSelectedItem<ObjectClass>();
object? T = obj?.T;
object? P = obj?.P;
MessageBox.Show($"Îáúåêò ñîçäàí, ïåðâîå çíà÷åíèå: {T}, âòîðîå çíà÷åíèå: {P}");
}
}
} }

View File

@ -2,7 +2,7 @@
{ {
public class ObjectClass public class ObjectClass
{ {
public double T { get; set; } public object T { get; set; }
public double P { get; set; } public object P { get; set; }
} }
} }

View File

@ -1,3 +1,5 @@
using System.Text.RegularExpressions;
namespace ComponentsLab namespace ComponentsLab
{ {
internal static class Program internal static class Program
@ -8,10 +10,11 @@ namespace ComponentsLab
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // To customize application configuration such as set high DPI settings or default font,
ApplicationConfiguration.Initialize(); // see https://aka.ms/applicationconfiguration.
Application.Run(new FormComponents()); ApplicationConfiguration.Initialize();
} Application.Run(new FormComponents());
} }
}
} }