using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Windows.Forms; using System.Linq; namespace HEM { public partial class MainForm : Form, INotifyPropertyChanged { private Coordinate _data; private bool _isDirty; private TabControl _mainTabControl; private Dictionary _bindingSources = new Dictionary(); public event PropertyChangedEventHandler PropertyChanged; public MainForm() { InitializeComponent(); InitializeData(); CreateMainLayout(); this.Text = "HEM Coordinate Editor"; this.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(IsDirty)) { this.Text = _isDirty ? "HEM Coordinate Editor*" : "HEM Coordinate Editor"; } }; } private void InitializeData() { _data = new Coordinate { // Initialize all main objects and collections General = new General(), ExternalConditions = new ExternalConditions(), InfiltrationVentilation = new InfiltrationVentilation(), InternalGains = new InternalGains(), HotWaterDemand = new HotWaterDemand(), HotWaterSource = new HotWaterSource(), ColdWaterSource = new ColdWaterSourceClass(), SimulationTime = new SimulationTime(), Tariff = new TariffClass(), Window_Opening_For_Cooling = new WindowOpeningForCoolingClass(), ApplianceGains = new Dictionary(), Appliances = new Dictionary(), Control = new Dictionary(), EnergySupply = new Dictionary(), Events = new Dictionary>>(), HeatSourceWet = new Dictionary(), OnSiteGeneration = new Dictionary(), PreHeatedWaterSource = new Dictionary(), SmartApplianceControls = new Dictionary(), SpaceCoolSystem = new Dictionary(), SpaceHeatSystem = new Dictionary(), WWHRS = new Dictionary(), Zone = new Dictionary() }; } private void CreateMainLayout() { _mainTabControl = new TabControl { Dock = DockStyle.Fill, Parent = this }; var properties = typeof(Coordinate).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { var propValue = prop.GetValue(_data); if (propValue == null) continue; if (IsCollectionType(prop.PropertyType)) { AddCollectionToTab2(_mainTabControl, prop.Name, propValue as IEnumerable); } else if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string)) { AddComplexObjectTab(prop.Name, propValue); } else { // Simple properties will be added to a "General" tab if (!_mainTabControl.TabPages.ContainsKey("General")) { _mainTabControl.TabPages.Add("General", "General"); } AddPropertyToTab(_mainTabControl.TabPages["General"], prop.Name, propValue, prop.PropertyType, _data, prop); } } } private void AddCollectionToTab2(TabControl parentTabControl, string collectionName, IEnumerable collection) { if (collection == null) return; var tabPage = new TabPage(collectionName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var dataGridView = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AllowUserToAddRows = true, AllowUserToDeleteRows = true, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill }; var bindingSource = new BindingSource(); if (collection is IDictionary dictionary) { // Improved dictionary display var list = new List>(); foreach (DictionaryEntry entry in dictionary) { list.Add(new KeyValuePair(entry.Key, entry.Value)); } bindingSource.DataSource = list; // Customize columns for better display dataGridView.AutoGenerateColumns = false; dataGridView.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Key", HeaderText = "Key", Name = "Key", ReadOnly = true }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Value", HeaderText = "Value", Name = "Value" }); } else { bindingSource.DataSource = collection; dataGridView.AutoGenerateColumns = true; } dataGridView.DataSource = bindingSource; _bindingSources.Add(collectionName, bindingSource); // Add buttons panel var buttonPanel = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 30, FlowDirection = FlowDirection.LeftToRight }; var addButton = new Button { Text = "Add Item" }; var removeButton = new Button { Text = "Remove Selected" }; var saveButton = new Button { Text = "Save Changes" }; addButton.Click += (sender, e) => AddItemToCollection(collection, bindingSource); removeButton.Click += (sender, e) => RemoveSelectedItem(collection, bindingSource, dataGridView); saveButton.Click += (sender, e) => IsDirty = true; buttonPanel.Controls.Add(addButton); buttonPanel.Controls.Add(removeButton); buttonPanel.Controls.Add(saveButton); panel.Controls.Add(dataGridView); panel.Controls.Add(buttonPanel); parentTabControl.TabPages.Add(tabPage); } private void AddPropertyToTab(TabPage parentTabPage, string propertyName, object propertyValue, Type propertyType, object parentObject, PropertyInfo propInfo) { var panel = parentTabPage.Controls[0] as Panel; if (panel == null) return; TableLayoutPanel tableLayout = panel.Controls.OfType().FirstOrDefault(); if (tableLayout == null) { tableLayout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, CellBorderStyle = TableLayoutPanelCellBorderStyle.Single }; panel.Controls.Add(tableLayout); } AddPropertyToTable(tableLayout, propertyName, propertyValue, propertyType, parentObject, propInfo); } private void AddComplexObjectTab(string tabName, object obj) { var tabPage = new TabPage(tabName); var mainPanel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(mainPanel); var tabControl = new TabControl { Dock = DockStyle.Fill }; mainPanel.Controls.Add(tabControl); var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { var propValue = prop.GetValue(obj); if (propValue == null) continue; if (IsCollectionType(prop.PropertyType)) { AddCollectionToTab(tabControl, prop.Name, propValue as IEnumerable); } else if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string)) { AddNestedObjectTab(tabControl, prop.Name, propValue); } else { AddPropertyToTab(tabControl, prop.Name, propValue, prop.PropertyType, obj, prop); } } _mainTabControl.TabPages.Add(tabPage); } private void AddPropertyToTab(TabControl parentTabControl, string propertyName, object propertyValue, Type propertyType, object parentObject, PropertyInfo propInfo) { var tabPage = new TabPage(propertyName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var tableLayout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, AutoScroll = true, CellBorderStyle = TableLayoutPanelCellBorderStyle.Single }; var label = new Label { Text = propertyName, AutoSize = true, Anchor = AnchorStyles.Left, Margin = new Padding(3, 3, 10, 3) }; tableLayout.Controls.Add(label); Control control = CreateControlForProperty(propertyName, propertyValue, propertyType, parentObject, propInfo); tableLayout.Controls.Add(control); if (control is CheckBox) { tableLayout.SetColumnSpan(control, 2); } panel.Controls.Add(tableLayout); parentTabControl.TabPages.Add(tabPage); } private void AddCollectionTab(string tabName, IEnumerable collection) { var tabPage = new TabPage(tabName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var dataGridView = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AllowUserToAddRows = true, AllowUserToDeleteRows = true }; var bindingSource = new BindingSource(); if (collection is IDictionary dictionary) { var list = new List(); foreach (DictionaryEntry entry in dictionary) { list.Add(entry); } bindingSource.DataSource = list; } else { bindingSource.DataSource = collection; } dataGridView.DataSource = bindingSource; _bindingSources.Add(tabName, bindingSource); // Add buttons panel var buttonPanel = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 30, FlowDirection = FlowDirection.LeftToRight }; var addButton = new Button { Text = "Add Item" }; var removeButton = new Button { Text = "Remove Selected" }; addButton.Click += (sender, e) => AddItemToCollection(collection, bindingSource); removeButton.Click += (sender, e) => RemoveSelectedItem(collection, bindingSource, dataGridView); buttonPanel.Controls.Add(addButton); buttonPanel.Controls.Add(removeButton); panel.Controls.Add(dataGridView); panel.Controls.Add(buttonPanel); _mainTabControl.TabPages.Add(tabPage); } private void AddItemToCollection(IEnumerable collection, BindingSource bindingSource) { try { if (collection is IDictionary dictionary) { // For dictionaries, we need to determine the key and value types Type[] genericArgs = dictionary.GetType().GetGenericArguments(); if (genericArgs.Length == 2) { object key = Activator.CreateInstance(genericArgs[0]); object value = Activator.CreateInstance(genericArgs[1]); dictionary.Add(key, value); } } else if (collection is IList list) { // For lists, create an instance of the element type Type elementType = list.GetType().GetGenericArguments()[0]; list.Add(Activator.CreateInstance(elementType)); } bindingSource.ResetBindings(false); IsDirty = true; } catch (Exception ex) { MessageBox.Show($"Error adding item: {ex.Message}"); } } private void RemoveSelectedItem(IEnumerable collection, BindingSource bindingSource, DataGridView dataGridView) { try { if (dataGridView.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dataGridView.SelectedRows) { if (row.DataBoundItem != null) { if (collection is IDictionary dictionary) { var entry = (DictionaryEntry)row.DataBoundItem; dictionary.Remove(entry.Key); } else if (collection is IList list) { list.Remove(row.DataBoundItem); } } } bindingSource.ResetBindings(false); IsDirty = true; } } catch (Exception ex) { MessageBox.Show($"Error removing item: {ex.Message}"); } } private void AddNestedObjectTab(TabControl parentTabControl, string tabName, object obj) { var tabPage = new TabPage(tabName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // Use FlowLayoutPanel for better dynamic layout var flowLayout = new FlowLayoutPanel { Dock = DockStyle.Fill, AutoScroll = true, FlowDirection = FlowDirection.TopDown, WrapContents = false }; foreach (var prop in properties) { var propValue = prop.GetValue(obj); if (propValue == null) continue; var propertyPanel = new Panel { Width = flowLayout.Width - 30, Height = 30, Dock = DockStyle.Top }; var label = new Label { Text = prop.Name, Width = 150, Dock = DockStyle.Left }; Control control = CreateControlForProperty(prop.Name, propValue, prop.PropertyType, obj, prop); control.Dock = DockStyle.Fill; control.Width = propertyPanel.Width - label.Width; propertyPanel.Controls.Add(control); propertyPanel.Controls.Add(label); flowLayout.Controls.Add(propertyPanel); } panel.Controls.Add(flowLayout); parentTabControl.TabPages.Add(tabPage); } private void AddSimplePropertiesTab(string tabName, List properties) { var tabPage = new TabPage(tabName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var tableLayout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, AutoScroll = true, CellBorderStyle = TableLayoutPanelCellBorderStyle.Single }; foreach (var prop in properties) { var propValue = prop.GetValue(_data); AddPropertyToTable(tableLayout, prop.Name, propValue, prop.PropertyType, _data, prop); } panel.Controls.Add(tableLayout); _mainTabControl.TabPages.Add(tabPage); } private void AddPropertyToTable(TableLayoutPanel tableLayout, string propName, object propValue, Type propType, object parentObject, PropertyInfo propInfo) { var label = new Label { Text = propName, AutoSize = true, Anchor = AnchorStyles.Left, Margin = new Padding(3, 3, 10, 3) }; tableLayout.Controls.Add(label); Control control = CreateControlForProperty(propName, propValue, propType, parentObject, propInfo); tableLayout.Controls.Add(control); if (control is CheckBox) { tableLayout.SetColumnSpan(control, 2); } } private Control CreateControlForProperty(string propName, object propValue, Type propType, object parentObject, PropertyInfo propInfo) { var underlyingType = Nullable.GetUnderlyingType(propType) ?? propType; if (underlyingType == typeof(bool)) { var checkBox = new CheckBox { Checked = propValue != null && (bool)propValue, AutoSize = true, Anchor = AnchorStyles.Left }; checkBox.CheckedChanged += (s, e) => { propInfo.SetValue(parentObject, checkBox.Checked); IsDirty = true; }; checkBox.DataBindings.Add("Checked", parentObject, propName, false, DataSourceUpdateMode.OnPropertyChanged); return checkBox; } else if (underlyingType.IsEnum) { var comboBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 200, Anchor = AnchorStyles.Left }; comboBox.Items.AddRange(Enum.GetNames(underlyingType)); comboBox.SelectedItem = propValue?.ToString(); comboBox.SelectedIndexChanged += (s, e) => { if (Enum.TryParse(underlyingType, comboBox.SelectedItem?.ToString(), out var val)) propInfo.SetValue(parentObject, val); IsDirty = true; }; return comboBox; } else if (underlyingType == typeof(string)) { var textBox = new TextBox { Width = 200, Text = propValue as string, Anchor = AnchorStyles.Left }; textBox.TextChanged += (s, e) => { propInfo.SetValue(parentObject, textBox.Text); IsDirty = true; }; return textBox; } else if (underlyingType == typeof(int) || underlyingType == typeof(long) || underlyingType == typeof(double) || underlyingType == typeof(decimal) || underlyingType == typeof(float)) { var numericUpDown = new NumericUpDown { Width = 120, Anchor = AnchorStyles.Left, DecimalPlaces = (underlyingType == typeof(double) || underlyingType == typeof(decimal) || underlyingType == typeof(float)) ? 2 : 0, Minimum = decimal.MinValue, Maximum = decimal.MaxValue }; try { numericUpDown.Value = Convert.ToDecimal(propValue ?? 0); } catch { } numericUpDown.ValueChanged += (s, e) => { propInfo.SetValue(parentObject, Convert.ChangeType(numericUpDown.Value, underlyingType)); IsDirty = true; }; return numericUpDown; } else { return new Label { Text = $"Unsupported type: {underlyingType.Name}" }; } } private void AddCollectionToTab(TabControl parentTabControl, string collectionName, IEnumerable collection) { if (collection == null) return; var tabPage = new TabPage(collectionName); var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true }; tabPage.Controls.Add(panel); var dataGridView = new DataGridView { Dock = DockStyle.Fill, AutoGenerateColumns = true, AllowUserToAddRows = true, AllowUserToDeleteRows = true }; var bindingSource = new BindingSource(); if (collection is IDictionary dictionary) { var list = new List(); foreach (DictionaryEntry entry in dictionary) { list.Add(entry); } bindingSource.DataSource = list; } else { bindingSource.DataSource = collection; dataGridView.AutoGenerateColumns = true; } dataGridView.DataSource = bindingSource; _bindingSources.Add(collectionName, bindingSource); var buttonPanel = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 30, FlowDirection = FlowDirection.LeftToRight }; var addButton = new Button { Text = "Add Item" }; var removeButton = new Button { Text = "Remove Selected" }; addButton.Click += (sender, e) => AddItemToCollection(collection, bindingSource); removeButton.Click += (sender, e) => RemoveSelectedItem(collection, bindingSource, dataGridView); buttonPanel.Controls.Add(addButton); buttonPanel.Controls.Add(removeButton); panel.Controls.Add(dataGridView); panel.Controls.Add(buttonPanel); parentTabControl.TabPages.Add(tabPage); } private bool IsCollectionType(Type type) { if (type.IsGenericType) { var genericType = type.GetGenericTypeDefinition(); return genericType == typeof(Dictionary<,>) || genericType == typeof(List<>) || typeof(IEnumerable).IsAssignableFrom(type); } return typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string); } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void BindControlToProperty(Control control, object dataSource, string propertyName, PropertyInfo propInfo) { var underlyingType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType; if (control is TextBox textBox) { textBox.DataBindings.Add("Text", dataSource, propertyName, false, DataSourceUpdateMode.OnPropertyChanged); } else if (control is NumericUpDown numericUpDown) { numericUpDown.DataBindings.Add("Value", dataSource, propertyName, false, DataSourceUpdateMode.OnPropertyChanged, 0, underlyingType == typeof(decimal) ? "N2" : "N0"); } else if (control is CheckBox checkBox) { checkBox.DataBindings.Add("Checked", dataSource, propertyName, false, DataSourceUpdateMode.OnPropertyChanged); } else if (control is ComboBox comboBox && underlyingType.IsEnum) { comboBox.DataSource = Enum.GetValues(underlyingType); comboBox.DataBindings.Add("SelectedItem", dataSource, propertyName, false, DataSourceUpdateMode.OnPropertyChanged); } // Handle control events to mark form as dirty control.Validated += (s, e) => IsDirty = true; // control.Enter += (s, e) => _lastFocusedControl = control; } public bool IsDirty { get => _isDirty; set { if (_isDirty != value) { _isDirty = value; OnPropertyChanged(nameof(IsDirty)); this.Text = _isDirty ? "HEM Coordinate Editor*" : "HEM Coordinate Editor"; } } } } }