Files
tbf/TBF/UI/Bench/Components/ComponentsManagerDlg.cs
T
michal d43bfadcd8 feat(ui): add bulk parameter editing for component configurations
- Introduced `BulkComponentParametersDlg` to support simultaneous parameter updates for selected components.
- Added context menu in `ComponentsManagerDlg` with bulk edit and copy column options.
- Updated resource strings for localization of bulk editing actions and tooltips.
- Enhanced UI controls to handle mixed values, validation, and conditional updates efficiently.
- Included new providers (iPerl and WaterMeter) for bulk parameter management.
2026-10-15 12:03:13 +02:00

1063 lines
42 KiB
C#

///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using log4net;
using NHibernate;
using Common;
using Common.Forms;
using Config.Entities;
using TBF.Rig;
using TBF.Rig.Generic;
using TBF.Resources;
using TBF.UI.Shared;
namespace TBF.UI.Bench.Components
{
public partial class ComponentsManagerDlg : Form, IParentOfListViewEx
{
static readonly ILog log = LogManager.GetLogger(typeof(ComponentsManagerDlg));
/// <summary>
/// List of components (=component configuration instances)
/// </summary>
IList<Component> cmpntEntities;
IList<Component> toBeDeletedEntities;
ISession session;
SelectComponentClassDlg selectComponentTypeDlg; /// Constructed once, the selection is kept between dialog usages
CfgUpdateFlags flags; /// Or-ed from particular Flags from ComponentParametersDlg
/// <summary>
/// ListViewEx columns
/// </summary>
enum Column
{
Number,
Name,
ClassName,
ParentName,
DebugMode,
Logging,
Parameters,
ColumnsCount,
}
MySortOrder sortOrder = MySortOrder.Ascending;
int sortColumn = -1; /// 0-based index of column to be used for sorting
/// Editors used by listViewEx
ComboBox debugCB;
ComboBox logCB;
bool unlocked;
readonly ContextMenuStrip selectionContextMenu = new ContextMenuStrip();
readonly ToolStripMenuItem bulkEditMenuItem = new ToolStripMenuItem();
readonly ToolStripMenuItem copyColumnMenuItem = new ToolStripMenuItem();
SubItemEventArgs lastRightClickedSubItem;
public ComponentsManagerDlg()
{
toBeDeletedEntities = new List<Component>();
InitializeComponent();
selectionContextMenu.Items.Add(bulkEditMenuItem);
selectionContextMenu.Items.Add(new ToolStripSeparator());
selectionContextMenu.Items.Add(copyColumnMenuItem);
bulkEditMenuItem.Click += bulkEditMenuItem_Click;
copyColumnMenuItem.Click += copyColumnMenuItem_Click;
listViewEx.MouseDown += listViewEx_MouseDown;
flags = CfgUpdateFlags.None;
selectComponentTypeDlg = new SelectComponentClassDlg();
/// SharedDlgSearchForListView configuration
sharedSearchForListView1.OwnerForm = this;
sharedSearchForListView1.ListViewEx = listViewEx;
sharedSearchForListView1.nrLabel.Text = "Component nr.";
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists };
sharedButtons.OptionalButtons = SharedButtons.Buttons.Add |
SharedButtons.Buttons.Remove |
SharedButtons.Buttons.Up |
SharedButtons.Buttons.Down |
SharedButtons.Buttons.Edit |
SharedButtons.Buttons.Copy |
SharedButtons.Buttons.Export |
SharedButtons.Buttons.Import;
sharedButtons.Unlocked += Unlocked;
sharedButtons.OKClicked += okButton_Click;
sharedButtons.CancelClicked += cancelButton_Click;
sharedButtons.AddClicked += addButton_Click;
sharedButtons.RemoveClicked += removeButton_Click;
sharedButtons.UpClicked += upButton_Click;
sharedButtons.DownClicked += downButton_Click;
sharedButtons.EditClicked += editButton_Click;
sharedButtons.CopyClicked += copyButton_Click;
sharedButtons.ExportClicked += exportButton_Click;
sharedButtons.ImportClicked += importButton_Click;
}
private void ComponentsManagerDlg_Load(object sender, EventArgs e)
{
LoadFormPosition();
Text = Strings.Test_Bench_Components_Configuration;
LocalSettings ls = Program.LocalSettings;
listViewEx.Columns.Add(Strings.Nr, (ls.ComponentsColumnCount > 0) ? ls.ComponentsColumnWidths[0] : 40);
listViewEx.Columns.Add(Strings.Name, (ls.ComponentsColumnCount > 1) ? ls.ComponentsColumnWidths[1] : 80);
listViewEx.Columns.Add(Strings.Type, (ls.ComponentsColumnCount > 2) ? ls.ComponentsColumnWidths[2] : 120);
listViewEx.Columns.Add(Strings.Parent, (ls.ComponentsColumnCount > 3) ? ls.ComponentsColumnWidths[3] : 55);
listViewEx.Columns.Add(Strings.Mode, (ls.ComponentsColumnCount > 4) ? ls.ComponentsColumnWidths[4] : 55);
listViewEx.Columns.Add(Strings.Logging, (ls.ComponentsColumnCount > 5) ? ls.ComponentsColumnWidths[5] : 55);
listViewEx.Columns.Add(Strings.Parameters, (ls.ComponentsColumnCount > 6) ? ls.ComponentsColumnWidths[6] : 600);
listViewEx.HeaderStyle = ColumnHeaderStyle.Clickable;
debugCB = new ComboBox();
for (DebugMode level = 0; level < DebugMode.Count; level++) debugCB.Items.Add(level.ToDescription());
splitContainer.Panel1.Controls.Add(debugCB);
logCB = new ComboBox();
for (LogLevel level = 0; level < LogLevel.Count; level++) logCB.Items.Add(level.ToDescription());
splitContainer.Panel1.Controls.Add(logCB);
listViewEx.SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked);
listViewEx.SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing);
sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit);
session = TBF.DB.CreateSession(DBKind.Config);
cmpntEntities = session.QueryOver<Component>()
.OrderBy(x => x.ItemNr).Asc
.List<Component>();
RedrawAll();
}
void listViewEx_SubItemClicked(object sender, SubItemEventArgs e)
{
if (unlocked && e.SubItem == (int)Column.DebugMode)
{
listViewEx.StartEditing(debugCB, e.Item, e.SubItem);
}
else if (unlocked && e.SubItem == (int)Column.Logging)
{
listViewEx.StartEditing(logCB, e.Item, e.SubItem);
}
}
private void listViewEx_SubItemRightClicked(object sender, SubItemEventArgs e)
{
lastRightClickedSubItem = e;
ShowSelectionContextMenu();
}
private void listViewEx_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right) return;
ListViewHitTestInfo hit = listViewEx.HitTest(e.Location);
if (hit.Item == null || hit.Item.Selected) return;
var oldSelection = new List<ListViewItem>();
foreach (ListViewItem selected in listViewEx.SelectedItems) oldSelection.Add(selected);
foreach (ListViewItem selected in oldSelection) selected.Selected = false;
hit.Item.Selected = true;
hit.Item.Focused = true;
}
private IList<Component> SelectedComponents()
{
var selected = new List<Component>();
foreach (ListViewItem item in listViewEx.SelectedItems)
{
Component component = item.Tag as Component;
if (component != null) selected.Add(component);
}
return selected;
}
private void ShowSelectionContextMenu()
{
IList<Component> selected = SelectedComponents();
var configs = new List<IComponentCfg>();
foreach (Component component in selected)
{
IComponentCfg config = TbfComponents.CmpntCfgFromCmpntEntity(component);
if (config == null) { configs.Clear(); break; }
configs.Add(config);
}
bulkEditMenuItem.Text = Strings.BulkEditSelectedMenu;
bulkEditMenuItem.Enabled = unlocked && BulkComponentParametersDlg.CanEdit(configs);
copyColumnMenuItem.Text = Strings.BulkEditCopyBelow;
copyColumnMenuItem.Enabled = unlocked && selected.Count == 1 && lastRightClickedSubItem != null &&
(lastRightClickedSubItem.SubItem == (int)Column.DebugMode || lastRightClickedSubItem.SubItem == (int)Column.Logging);
selectionContextMenu.Show(Cursor.Position);
}
private void copyColumnMenuItem_Click(object sender, EventArgs e)
{
SubItemEventArgs e0 = lastRightClickedSubItem;
if (e0 == null || !unlocked) return;
if (DialogResult.Yes == MessageBox.Show(Strings.Do_you_want_to_copy_this_value_to_all_cells_below_this_cell,
Strings.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
int columnNr = e0.SubItem;
string value = null;
///
foreach (ListViewItem item in listViewEx.Items)
{
if ((value != null) && (item.SubItems.Count > columnNr))
{
/// Modify values in subsequent items (when value != null)
Component cmpnt = (Component)item.Tag;
if (e0.SubItem == (int)Column.DebugMode)
{
for (DebugMode mode = 0; mode < DebugMode.Count; mode++)
{
if (value.Equals(mode.ToDescription()))
{
cmpnt.DebugMode = mode;
item.SubItems[columnNr].Text = value;
flags |= CfgUpdateFlags.RestartRqrd;
break;
}
}
}
else if (e0.SubItem == (int)Column.Logging)
{
for (LogLevel level = 0; level < LogLevel.Count; level++)
{
if (value.Equals(level.ToDescription()))
{
cmpnt.LogLevel = level;
item.SubItems[columnNr].Text = value;
flags |= CfgUpdateFlags.RestartRqrd;
break;
}
}
}
}
else if (item == e0.Item)
{
/// Pick value to be copied from this item
value = item.SubItems[columnNr].Text;
}
}
}
}
private void bulkEditMenuItem_Click(object sender, EventArgs e)
{
IList<Component> components = SelectedComponents();
var configs = new List<IComponentCfg>();
foreach (Component component in components)
{
IComponentCfg config = TbfComponents.CmpntCfgFromCmpntEntity(component);
if (config == null) return;
configs.Add(config);
}
if (!BulkComponentParametersDlg.CanEdit(configs)) return;
var iperlHeads = new List<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg>();
foreach (IComponentCfg config in configs)
{
var head = config as Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg;
if (head == null) { iperlHeads.Clear(); break; }
iperlHeads.Add(head);
}
if (iperlHeads.Count == configs.Count)
{
EditIperlHeadsUsingOriginalDialog(components, configs, iperlHeads);
return;
}
using (var dialog = new BulkComponentParametersDlg(configs))
{
if (dialog.ShowDialog(this) != DialogResult.OK) return;
PersistBulkConfigs(components, configs);
flags |= dialog.Flags;
if (dialog.Flags != CfgUpdateFlags.None) sharedButtons.UnlockButtons();
RedrawAll();
}
}
/// <summary>
/// Uses the normal, designer-backed iPerl/ASIC editor for a bulk selection.
/// Values differing from the first selected reader are shown grey. The event
/// tracker is important: it lets an operator deliberately apply a value which
/// happens to equal the first reader's value to every selected reader.
/// </summary>
private void EditIperlHeadsUsingOriginalDialog(IList<Component> components, IList<IComponentCfg> configs,
IList<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg> heads)
{
var model = heads[0];
var changed = new HashSet<string>();
IComponentCfgCtrl control = model.GetControl(cmpntEntities);
control.Config = model;
using (var dialog = new ComponentParametersDlg(this, components[0].Id))
{
var nameToolTip = new ToolTip();
dialog.CmpntEntities = cmpntEntities;
dialog.ComponentCfgCtrl = control;
dialog.UnlockAfterStart = true;
dialog.Shown += delegate
{
LockBulkComponentName(control as Control, nameToolTip);
MarkIperlMixedControls(control as Control, heads, changed);
};
dialog.FormClosed += delegate { nameToolTip.Dispose(); };
if (dialog.ShowDialog(this) != DialogResult.OK) return;
ApplyChangedIperlValues(model, heads, changed);
PersistBulkConfigs(components, configs);
flags |= dialog.Flags;
if (dialog.Flags != CfgUpdateFlags.None) sharedButtons.UnlockButtons();
RedrawAll();
}
}
private static void PersistBulkConfigs(IList<Component> components, IList<IComponentCfg> configs)
{
for (int i = 0; i < configs.Count; i++)
{
Component modified = configs[i].CreateDbEntity();
Component original = components[i];
original.DebugMode = modified.DebugMode;
original.LogLevel = modified.LogLevel;
original.Parameters = modified.Parameters;
}
}
private static void MarkIperlMixedControls(Control root,
IList<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg> heads, ISet<string> changed)
{
if (root == null) return;
MarkMixed(root, "radioButton1", !AllSame(heads, h => h.UseTcpIP), "UseTcpIP", changed);
MarkMixed(root, "radioButton2", !AllSame(heads, h => h.UseTcpIP), "UseTcpIP", changed);
MarkMixed(root, "ipAddressTextBox", !AllSame(heads, h => h.OptoIPAddress), "OptoIPAddress", changed);
MarkMixed(root, "tcpipPortTextBox", !AllSame(heads, h => h.OptoTcpipPortNr), "OptoTcpipPortNr", changed);
MarkMixed(root, "optoSerialPortTextBox", !AllSame(heads, h => h.OptoComPortNr), "OptoComPortNr", changed);
MarkMixed(root, "rfidPortNrTextBox", !AllSame(heads, h => h.RfidComPortNr), "RfidComPortNr", changed);
MarkMixed(root, "muxBoardNrTextBox", !AllSame(heads, h => h.MuxBoardNr), "MuxBoardNr", changed);
MarkMixed(root, "groupTextBox", !AllSame(heads, h => h.Group), "Group", changed);
MarkMixed(root, "comboBoxCommunicationInterface", !AllSame(heads, h => h.CommunicationInterface), "CommunicationInterface", changed);
MarkMixed(root, "headPortNrTextBox", !AllSame(heads, h => h.HeadCommunicationComPortNr), "HeadCommunicationComPortNr", changed);
MarkMixed(root, "calibFactorNominalTextBox", !AllSame(heads, h => h.CalibFactorNominal), "CalibFactorNominal", changed);
}
private static void LockBulkComponentName(Control root, ToolTip toolTip)
{
if (root == null) return;
Control[] controls = root.Controls.Find("nameTextBox", true);
if (controls.Length != 1) return;
controls[0].Enabled = false;
controls[0].TabStop = false;
toolTip.SetToolTip(controls[0], Strings.BulkEditUniqueName);
}
private static bool AllSame<T>(IList<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg> heads, Func<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg, T> value)
{
T first = value(heads[0]);
for (int i = 1; i < heads.Count; i++) if (!EqualityComparer<T>.Default.Equals(first, value(heads[i]))) return false;
return true;
}
private static void MarkMixed(Control root, string controlName, bool mixed, string field, ISet<string> changed)
{
Control[] controls = root.Controls.Find(controlName, true);
if (controls.Length != 1) return;
Control control = controls[0];
control.ForeColor = mixed ? System.Drawing.Color.Gray : System.Drawing.SystemColors.ControlText;
EventHandler changedHandler = delegate { control.ForeColor = System.Drawing.SystemColors.ControlText; changed.Add(field); };
var textBox = control as TextBox;
if (textBox != null) textBox.TextChanged += changedHandler;
var comboBox = control as ComboBox;
if (comboBox != null) comboBox.SelectedIndexChanged += changedHandler;
var radioButton = control as RadioButton;
if (radioButton != null) radioButton.CheckedChanged += changedHandler;
}
private static void ApplyChangedIperlValues(Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg model,
IList<Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg> heads, ISet<string> changed)
{
foreach (var head in heads)
{
if (changed.Contains("UseTcpIP")) head.UseTcpIP = model.UseTcpIP;
if (changed.Contains("OptoIPAddress")) head.OptoIPAddress = model.OptoIPAddress;
if (changed.Contains("OptoTcpipPortNr")) head.OptoTcpipPortNr = model.OptoTcpipPortNr;
if (changed.Contains("OptoComPortNr")) head.OptoComPortNr = model.OptoComPortNr;
if (changed.Contains("RfidComPortNr")) head.RfidComPortNr = model.RfidComPortNr;
if (changed.Contains("MuxBoardNr")) head.MuxBoardNr = model.MuxBoardNr;
if (changed.Contains("Group")) head.Group = model.Group;
if (changed.Contains("CommunicationInterface")) head.CommunicationInterface = model.CommunicationInterface;
if (changed.Contains("HeadCommunicationComPortNr")) head.HeadCommunicationComPortNr = model.HeadCommunicationComPortNr;
if (changed.Contains("CalibFactorNominal")) head.CalibFactorNominal = model.CalibFactorNominal;
}
}
void listViewEx_SubItemEndEditing(object sender, SubItemEndEditingEventArgs e)
{
Component cmpnt = (Component)e.Item.Tag;
if (e.SubItem == (int)Column.DebugMode)
{
for (DebugMode level = 0; level < DebugMode.Count; level++)
{
if (debugCB.Text.Equals(level.ToDescription()))
{
cmpnt.DebugMode = level;
flags |= CfgUpdateFlags.RestartRqrd;
return;
}
}
e.DisplayText = cmpnt.DebugMode.ToString();
}
else if (e.SubItem == (int)Column.Logging)
{
for (LogLevel level = 0; level < LogLevel.Count; level++)
{
if (logCB.Text.Equals(level.ToDescription()))
{
cmpnt.LogLevel = level;
flags |= CfgUpdateFlags.RestartRqrd;
return;
}
}
e.DisplayText = cmpnt.LogLevel.ToString();
}
}
private void Unlocked(object sender, EventArgs e)
{
unlocked = true;
if (listViewEx.SelectedItems.Count == 1)
{
int ix = listViewEx.SelectedIndices[0];
Focus();
listViewEx.Items[ix].Selected = true;
listViewEx.Items[ix].EnsureVisible();
}
}
void RedrawAll()
{
listViewEx.Items.Clear();
foreach (var cmpnt in cmpntEntities) DrawOne(cmpnt);
}
void DrawOne(Component cmpnt)
{
ListViewItem lvi = new ListViewItem(cmpnt.ItemNr.ToString());
lvi.Tag = cmpnt;
lvi.SubItems.Add(cmpnt.Name);
lvi.SubItems.Add(string.IsNullOrEmpty(cmpnt.ClassName) ? string.Empty : cmpnt.ClassName);
lvi.SubItems.Add(string.IsNullOrEmpty(cmpnt.Parent) ? string.Empty : cmpnt.Parent);
IComponentCfg cmpCfg = TbfComponents.CmpntCfgFromCmpntEntity(cmpnt);
if (cmpCfg != null)
{
lvi.SubItems.Add(cmpCfg.DebugLevel.ToDescription());
lvi.SubItems.Add(cmpCfg.LogLevel.ToDescription());
lvi.SubItems.Add(cmpCfg.ToString(-1));
}
else
{
lvi.SubItems.Add("---");
lvi.SubItems.Add("---");
lvi.SubItems.Add("Not a component");
}
listViewEx.Items.Add(lvi);
}
///
/// Save DB changes, return true when DB changes saved OK
///
bool SaveDBChanges(ISession session)
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
foreach (var cmpnt in toBeDeletedEntities) session.Delete(cmpnt);
int itemNr = 1;
foreach (var cmpnt in cmpntEntities)
{
cmpnt.ItemNr = itemNr++;
session.SaveOrUpdate(cmpnt);
}
transaction.Commit();
session.Flush();
return true;
}
catch (Exception exc)
{
transaction.Rollback();
log.ErrorFormat("Exception when saving components : {1}", exc.Message);
return false;
}
}
}
private void LoadFormPosition()
{
LocalSettings ls = Program.LocalSettings;
Width = (ls.ComponentsDlgWidth > 0) ? ls.ComponentsDlgWidth : 850;
Height = (ls.ComponentsDlgHeight > 0) ? ls.ComponentsDlgHeight : 500;
Left = (ls.ComponentsDlgLeft != 0) ? ls.ComponentsDlgLeft : 200;
Top = (ls.ComponentsDlgTop != 0) ? ls.ComponentsDlgTop : 100;
}
/// <summary>
/// Save the dialog position and ListViewEx column widths
/// </summary>
void SaveUISettings()
{
/// Obtain ComponentsmanagerDlg dimensions, etc.
bool isMaximized = (WindowState == FormWindowState.Maximized);
int left = (WindowState == FormWindowState.Normal) ? Location.X : RestoreBounds.Left;
int top = (WindowState == FormWindowState.Normal) ? Location.Y : RestoreBounds.Top;
int width = (WindowState == FormWindowState.Normal) ? Size.Width : RestoreBounds.Width;
int height = (WindowState == FormWindowState.Normal) ? Size.Height : RestoreBounds.Height;
LocalSettings ls = Program.LocalSettings;
/// Compare list view column widths with the saved ones
bool anyColumnDiffers = false;
if ((int)Column.ColumnsCount != ls.ComponentsColumnCount)
{
anyColumnDiffers = true;
}
else
{
for (int i = 0; i < (int)Column.ColumnsCount; i++)
{
if (listViewEx.Columns[i].Width != ls.ComponentsColumnWidths[i]) { anyColumnDiffers = true; break; }
}
}
if (ls != null && (ls.ComponentsDlgMaximized != isMaximized ||
ls.ComponentsDlgLeft != left ||
ls.ComponentsDlgTop != top ||
ls.ComponentsDlgWidth != width ||
ls.ComponentsDlgHeight != height ||
anyColumnDiffers))
{
/// At least one ComponentsManagerDlg dimension differs => Update local settings and save them
///
ls.ComponentsDlgMaximized = isMaximized;
ls.ComponentsDlgLeft = left;
ls.ComponentsDlgTop = top;
ls.ComponentsDlgWidth = width;
ls.ComponentsDlgHeight = height;
/// List view column widths
ls.ComponentsColumnWidths = new int[(int)Column.ColumnsCount];
for (int i = 0; i < (int)Column.ColumnsCount; i++)
{
ls.ComponentsColumnWidths[i] = listViewEx.Columns[i].Width;
}
ls.Save();
}
}
///
/// OK
///
private void okButton_Click(object sender, EventArgs e)
{
if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0)
{
SaveDBChanges(session);
flags = CfgUpdateFlags.None; /// Changes saved
}
SaveUISettings();
DialogResult = DialogResult.OK;
Close();
return;
}
/// Cancel
private void cancelButton_Click(object sender, EventArgs e)
{
SaveUISettings();
if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0)
{
DialogResult dr = MessageBox.Show(Strings.Changes_will_be_lost_Do_you_want_to_proceed,
Strings.Warning,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (dr != DialogResult.Yes) return;
}
flags = CfgUpdateFlags.None; /// Abandoning changes confirmed
DialogResult = DialogResult.Cancel;
Close();
return;
}
/// Add a new component
private void addButton_Click(object sender, EventArgs e)
{
selectComponentTypeDlg.SelectedScriptName = null;
DialogResult dialogRslt = selectComponentTypeDlg.ShowDialog();
if (dialogRslt != DialogResult.OK) return;
IComponentFactory factory = selectComponentTypeDlg.SlctdCmpntFactory;
IComponentCfg cfg = factory.DefaultConfig();
if (selectComponentTypeDlg.SelectedScriptName == null)
{
///
/// Create a single component of the selected type
///
IComponentCfgCtrl cfgControl = cfg.GetControl(cmpntEntities);
cfgControl.Config = cfg;
if (cfgControl.Config == null)
{
string controlType = cfgControl.GetType().FullName;
string configType = cfg.GetType().FullName;
string details = string.Join(Environment.NewLine, new[]
{
"CONFIGURATION CONTROL",
controlType,
"",
"RECEIVED CONFIGURATION",
configType,
"",
"PROBABLE CAUSE",
"The configuration control expects a different configuration type.",
"Check the type cast in the Config property setter of the configuration control."
});
log.Error(details);
ErrorDetailsDlg.ShowError(this, "Invalid component configuration", "The component could not be added.", details);
return;
}
int lastItemNr = (cmpntEntities.Count > 0) ? cmpntEntities[cmpntEntities.Count - 1].ItemNr : 0;
cfgControl.Config.ItemNr = lastItemNr + 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
cfgForm.CmpntEntities = cmpntEntities;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
dialogRslt = cfgForm.ShowDialog();
if (dialogRslt != DialogResult.OK) return;
flags |= CfgUpdateFlags.RestartRqrd;
AddOne(cfgForm.Config.CreateDbEntity());
}
else
{
///
/// Create more components, read their names and other properties from a file
///
using (TextReader reader = new StreamReader(selectComponentTypeDlg.SelectedScriptName))
{
int zeroBasedIdx = 0;
string line = reader.ReadLine();
while (line != null)
{
line.Trim();
if (line.Length > 0)
{
string[] words = line.Split(new char[] { ' ', '\t' });
if (UpdateCfg(ref cfg, words, ref zeroBasedIdx))
{
flags |= CfgUpdateFlags.RestartRqrd;
cfg.ItemNr = (cmpntEntities.Count > 0) ? (cmpntEntities[cmpntEntities.Count - 1].ItemNr + 1) : 1;
AddOne(cfg.CreateDbEntity());
}
zeroBasedIdx++;
}
line = reader.ReadLine();
}
}
}
}
void AddOne(Component cmpnt)
{
cmpntEntities.Add(cmpnt);
DrawOne(cmpnt);
}
/// Delete the component
private void removeButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
int ix = listViewEx.SelectedIndices[0];
if (ix < 0) return;
Component selectedCmpnt = (Component)listViewEx.Items[ix].Tag;
if (selectedCmpnt.Id != 0) toBeDeletedEntities.Add(selectedCmpnt);
cmpntEntities.Remove(selectedCmpnt);
flags |= CfgUpdateFlags.AnyChange;
RedrawAll();
}
/// DoubleClick -> Edit the component
private void listViewEx_MouseDoubleClick(object sender, MouseEventArgs e)
{
editButton_Click(sender, e);
}
/// Edit a component
private void editButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
ListViewItem lvi = listViewEx.SelectedItems[0];
Component component = lvi.Tag as Component;
if (component == null) return;
IComponentCfg cfg = TbfComponents.CmpntCfgFromCmpntEntity(component);
if (cfg != null)
{
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this, component.Id);
cfgForm.CmpntEntities = cmpntEntities;
cfgForm.ComponentCfgCtrl = cfg.GetControl(cmpntEntities);
cfgForm.ComponentCfgCtrl.Config = cfg;
DialogResult dr = cfgForm.ShowDialog();
if (dr != DialogResult.OK) return;
flags |= cfgForm.Flags;
sharedButtons.UnlockButtons(); /// Unlock this dialog buttons as changes were enabled
unlocked = true; /// in the ComponentParametersDlg.
Component modified = cfgForm.Config.CreateDbEntity();
Component original = (Component)lvi.Tag;
original.Name = modified.Name;
original.ClassName = modified.ClassName;
original.Parent = modified.Parent;
original.DebugMode = modified.DebugMode;
original.LogLevel = modified.LogLevel;
original.Parameters = modified.Parameters;
RedrawAll();
}
}
/// Copy a component
private void copyButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
ListViewItem lvi = listViewEx.SelectedItems[0];
IComponentCfg cfg = TbfComponents.CmpntCfgFromCmpntEntity((Component)lvi.Tag);
if (cfg != null)
{
cfg.Name += Strings.New_name_copy;
if (selectComponentTypeDlg.SelectedScriptName == null)
{
IComponentCfgCtrl cfgControl = cfg.GetControl(cmpntEntities);
cfgControl.Config = cfg;
cfgControl.Config.ItemNr = (cmpntEntities.Count > 0) ? (cmpntEntities[cmpntEntities.Count - 1].ItemNr + 1) : 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
cfgForm.CmpntEntities = cmpntEntities;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
if (cfgForm.ShowDialog() != DialogResult.OK) return;
flags |= CfgUpdateFlags.RestartRqrd;
AddOne(cfgForm.Config.CreateDbEntity());
}
}
}
/// Export a component to a file
private void exportButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
Component component = listViewEx.SelectedItems[0].Tag as Component;
if (component == null) return;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = string.Format("{0}.pro", component.Name);
if (dlg.ShowDialog() == DialogResult.OK)
{
component.Export(new StreamWriter(dlg.FileName, false, System.Text.Encoding.UTF8));
}
}
/// Import a component form a file
private void importButton_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK) return;
/// Import a procedure from a file
Component newComponent = Component.Import(new StreamReader(dlg.FileName, System.Text.Encoding.UTF8));
IComponentCfg cfg = TbfComponents.CmpntCfgFromCmpntEntity(newComponent);
if (cfg != null)
{
IComponentCfgCtrl cfgControl = cfg.GetControl(cmpntEntities);
cfgControl.Config = cfg;
cfgControl.Config.Name = cfgControl.Config.Name + " imported";
cfgControl.Config.ItemNr = (cmpntEntities.Count > 0) ? (cmpntEntities[cmpntEntities.Count - 1].ItemNr + 1) : 1;
ComponentParametersDlg cfgForm = new ComponentParametersDlg(this);
cfgForm.CmpntEntities = cmpntEntities;
cfgForm.ComponentCfgCtrl = cfgControl;
cfgForm.UnlockAfterStart = true;
if (cfgForm.ShowDialog() != DialogResult.OK) return;
flags |= CfgUpdateFlags.RestartRqrd;
AddOne(cfgForm.Config.CreateDbEntity());
}
}
private void upButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
int ix = listViewEx.SelectedIndices[0];
if (ix < 1) return;
Component item1 = (Component)(listViewEx.Items[ix - 1].Tag);
Component item2 = (Component)(listViewEx.Items[ix].Tag);
(item1 as IHasItemNr).ItemNr++;
(item2 as IHasItemNr).ItemNr--;
cmpntEntities.RemoveAt(ix);
cmpntEntities.Insert(ix - 1, item2);
flags |= CfgUpdateFlags.AnyChange;
RedrawAll();
Focus();
listViewEx.Items[ix - 1].Selected = true;
listViewEx.Items[ix - 1].EnsureVisible();
}
private void downButton_Click(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count != 1) return;
int ix = listViewEx.SelectedIndices[0];
if (ix >= listViewEx.Items.Count - 1) return;
Component item1 = (Component)(listViewEx.Items[ix].Tag);
Component item2 = (Component)(listViewEx.Items[ix + 1].Tag);
(item1 as IHasItemNr).ItemNr++;
(item2 as IHasItemNr).ItemNr--;
cmpntEntities.RemoveAt(ix + 1);
cmpntEntities.Insert(ix, item2);
flags |= CfgUpdateFlags.AnyChange;
RedrawAll();
Focus();
listViewEx.Items[ix + 1].Selected = true;
listViewEx.Items[ix + 1].EnsureVisible();
}
private void componentsListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (listViewEx.SelectedIndices.Count == 1)
{
sharedButtons.EnableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit);
}
else
{
sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit);
}
}
public void UpdateButtonStates(SharedButtons.SelectedItemPos selectedItemPos)
{
if (selectedItemPos == SharedButtons.SelectedItemPos.None)
{
sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Up | SharedButtons.Buttons.Down);
}
else if (selectedItemPos == SharedButtons.SelectedItemPos.First)
{
sharedButtons.EnableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Down);
sharedButtons.DisableButtons(SharedButtons.Buttons.Up);
}
else if (selectedItemPos == SharedButtons.SelectedItemPos.Last)
{
sharedButtons.EnableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Up);
sharedButtons.DisableButtons(SharedButtons.Buttons.Down);
}
else if (selectedItemPos == SharedButtons.SelectedItemPos.FirstAndLast)
{
sharedButtons.EnableButtons(SharedButtons.Buttons.Remove);
sharedButtons.DisableButtons(SharedButtons.Buttons.Up | SharedButtons.Buttons.Down);
}
else
{
sharedButtons.EnableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Up | SharedButtons.Buttons.Down);
}
}
private void ComponentsManagerDlg_FormClosing(object sender, FormClosingEventArgs e)
{
SaveUISettings();
if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0)
{
DialogResult dr = MessageBox.Show(Strings.Do_you_want_to_save_changes,
Strings.Warning,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
SaveDBChanges(session);
}
}
if (CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
}
/// <summary>
/// Updates component configuration from a script file
/// </summary>
/// <param name="cfg"></param>
/// <param name="words"></param>
/// <param name="zeroBasedIdx"></param>
/// <returns>true = udated component configuration should be saved, new component should be created</returns>
bool UpdateCfg(ref IComponentCfg cfg, string[] words, ref int zeroBasedIdx)
{
string name = words[words.Length - 1]; /// The last word is the component name
cfg.Name = name.Replace("#", (zeroBasedIdx + 1).ToString());
if (cfg is Rig.BuiltIn.Valve.ValveCfg)
{
int bitNr = zeroBasedIdx;
if (words.Length >= 2 && words[0].StartsWith("D") && int.TryParse(words[0].Substring(1), out bitNr))
{
zeroBasedIdx = bitNr;
}
if (name != "-")
{
(cfg as Rig.BuiltIn.Valve.ValveCfg).BitNr = bitNr;
(cfg as Rig.BuiltIn.Valve.ValveCfg).Category =
name.Contains("L") ? ValveCategory.Bench :
name.Contains("I") ? ValveCategory.Output :
name.Contains("Z") ? ValveCategory.Feeding : ValveCategory.None;
return true;
}
}
else if (cfg is Rig.Uni.FlowMeter.FlowMeterCfg)
{
(cfg as IChildComponentCfg).ParentName = "UniCB";
(cfg as Rig.Uni.FlowMeter.FlowMeterCfg).Idx1 = zeroBasedIdx + 1;
return true;
}
else if (cfg is Rig.Uni.RegValve.RegValveCfg)
{
(cfg as IChildComponentCfg).ParentName = "UniCB";
(cfg as Rig.Uni.RegValve.RegValveCfg).Idx1 = zeroBasedIdx + 1;
return true;
}
else if (cfg is Rig.Modbus.TempMeter.Groch.TempMeterCfg)
{
(cfg as IChildComponentCfg).ParentName = "CB";
(cfg as Rig.Modbus.TempMeter.Groch.TempMeterCfg).Channel = zeroBasedIdx;
return true;
}
else if (cfg is Rig.Modbus.PressureMeter.Meret.PressureMeterCfg)
{
(cfg as IChildComponentCfg).ParentName = "CB";
(cfg as Rig.Modbus.PressureMeter.Meret.PressureMeterCfg).ModbusAddress = (byte)(zeroBasedIdx + 1);
return true;
}
else if (cfg is Rig.Modbus.Meret.AdjustableScale.AdjustableMeterCfg)
{
(cfg as IChildComponentCfg).ParentName = "CB";
(cfg as Rig.Modbus.Meret.AdjustableScale.AdjustableMeterCfg).ModbusAddress = (byte)(zeroBasedIdx + 1);
return true;
}
else if (cfg is Rig.RegisterReaders.PulsesFromUniCB.RRCfg)
{
(cfg as IChildComponentCfg).ParentName = "UniCB";
(cfg as Rig.RegisterReaders.PulsesFromUniCB.RRCfg).Position = zeroBasedIdx + 1;
return true;
}
else if (cfg is Rig.RegisterReaders.StandingStartStop.RRCfg)
{
(cfg as IChildComponentCfg).ParentName = "UniCB";
return true;
}
else if (cfg is Rig.RegisterReaders.KPackE.RegisterReader.RRCfg)
{
(cfg as IChildComponentCfg).ParentName = "KPackE.Radio";
return true;
}
else if (cfg is Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg)
{
return true;
}
else if (cfg is Rig.WaterMeters.WaterMeter.WaterMeterCfg)
{
return true;
}
return false;
}
private void listViewEx_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (e.Column == sortColumn)
{
sortOrder = (sortOrder == MySortOrder.Ascending) ? MySortOrder.Descending : MySortOrder.Ascending;
}
else
{
/// Clicked on another column header => set sortOrder to SortOrder.Ascending
sortColumn = e.Column;
sortOrder = MySortOrder.Ascending;
}
if (sortColumn == (int)Column.Number)
{
listViewEx.ListViewItemSorter = new LviIntColumnComparer(sortColumn, sortOrder);
}
else
{
listViewEx.ListViewItemSorter = new LviTextColumnComparer(sortColumn, sortOrder);
}
listViewEx.SetSortIcon(sortColumn, sortOrder);
listViewEx.Sort();
}
}
}