1254 lines · 49.9 KB · C#
RawDownload
//******************************************************************************************************//  MainForm.cs - Gbtc////  Copyright © 2019, Grid Protection Alliance.  All Rights Reserved.////  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See//  the NOTICE file distributed with this work for additional information regarding copyright ownership.//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this//  file except in compliance with the License. You may obtain a copy of the License at:////      http://opensource.org/licenses/MIT////  Unless agreed to in writing, the subject software distributed under the License is distributed on an//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the//  License for the specific language governing permissions and limitations.////  Code Modification History://  ----------------------------------------------------------------------------------------------------//  02/11/2019 - J. Ritchie Carroll//       Generated original version of source code.////****************************************************************************************************** using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Diagnostics;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Windows.Forms;using GSF;using GSF.ComponentModel;using GSF.Configuration;using GSF.Console;using GSF.Diagnostics;using GSF.IO;using GSF.TimeSeries;using GSF.TimeSeries.Adapters;using GSF.Windows.Forms; // ReSharper disable AccessToModifiedClosure// ReSharper disable PossibleMultipleEnumerationnamespace GEPDataExtractor{    public partial class MainForm : Form    {        #region [ Members ]         // Fields        private Metadata m_metadata;        private readonly LogPublisher m_log;        //private readonly GraphData m_graphData;        private Settings m_settings;        private bool m_formLoaded;        private volatile bool m_prefiltering;        private volatile bool m_exporting;        private volatile bool m_formClosing;         #endregion         #region [ Constructors ]        public MainForm()        {            InitializeComponent();             dataGridViewDevices.AutoGenerateColumns = true;             // Save string format of select count label in its tag            labelSelectCount.Tag = labelSelectCount.Text;            labelSelectCount.Text = "";             labelMeasurementCount.Tag = labelMeasurementCount.Text;            labelMeasurementCount.Text = "";             // Save string format of filter expression text box in its tag            textBoxFilterExpression.Tag = textBoxFilterExpression.Text;            textBoxFilterExpression.Text = "";             // Create a new log publisher instance            m_log = Logger.CreatePublisher(typeof(MainForm), MessageClass.Application);             //m_graphData = new GraphData();        }         #endregion         #region [ Properties ]         private int SelectedDeviceCount => m_metadata?.Devices.Count(device => device.Selected) ?? 0;         #endregion         #region [ Methods ]         // Form Event Handlers         private void MainForm_Load(object sender, EventArgs e)        {            try            {                // Load current settings registering a symbolic reference to this form instance for use by default value expressions                m_settings = new Settings(new Dictionary<string, object> {{ "Form", this }}.RegisterSymbols());                 // Restore last window size/location                this.RestoreLayout();                 m_formLoaded = true;                 Arguments args = new Arguments(Environment.CommandLine, true);                linkLabelOpenExportPage.Visible = args.Exists("showLinkLabel");            }            catch (Exception ex)            {                m_log.Publish(MessageLevel.Error, "FormLoad", "Failed while loading settings", exception: ex);             #if DEBUG                throw;            #endif            }        }         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)        {            try            {                m_formClosing = true;                 // Save current window size/location                this.SaveLayout();                 // Save any updates to current screen values                m_settings.Save();            }            catch (Exception ex)            {                m_log.Publish(MessageLevel.Error, "FormClosing", "Failed while saving settings", exception: ex);             #if DEBUG                throw;            #endif            }        }         private void MainForm_FormClosed(object sender, FormClosedEventArgs e)        {            m_settings?.Dispose();        }         private void buttonConnect_Click(object sender, EventArgs e)        {            try            {                Cursor.Current = Cursors.WaitCursor;                 ShowUpdateMessage($"Loading meta-data from \"{m_settings.HostAddress}:{m_settings.Port}\"...");                m_metadata = new Metadata(m_settings);                tabControlOptions.TabIndex = 0;                 ShowUpdateMessage("Metadata loaded, extracting data types from meta-data from...");                 List<string> signals = m_metadata.Measurements.Select(row => row.SignalAcronym).Distinct().ToList();                                checkedListBoxDataTypes.Items.Clear();                checkedListBoxDataTypes.Items.AddRange(signals.OrderByDescending(s => s).Cast<object>().ToArray());                 RefreshDevicesDataGrid();                RefreshSelectedCount();                 if (!string.IsNullOrWhiteSpace(m_settings.DeviceFilter))                    textBoxDeviceFilter_TextChanged(sender, e);                 ShowUpdateMessage("Ready for user data type selection.");            }            catch (Exception ex)            {                MessageBox.Show(this, $"Failed to connect to \"{m_settings.HostAddress}:{m_settings.Port}\": {ex.Message}", "Connection Exception", MessageBoxButtons.OK);            }            finally            {                Cursor.Current = Cursors.Arrow;            }        }         private void buttonCancelPreFilter_Click(object sender, EventArgs e)        {            tabControlOptions.SelectedIndex = 0;            m_prefiltering = false;        }         private void buttonPreFilter_Click(object sender, EventArgs e)        {            m_prefiltering = true;            SetButtonsEnabledState(false);            ClearUpdateMessages();            UpdateProgressBar(0);            SetProgressBarMaximum(100);             tabControlOptions.SelectedTab = tabPageMessages;             // Kick off a thread to start archive read            new Thread(PreFilter) { IsBackground = true }.Start();        }         private void buttonShowGraph_Click(object sender, EventArgs e)        {            //m_graphData.Show();        }         private void buttonExportCancel_Click(object sender, EventArgs e)        {            tabControlOptions.SelectedIndex = 0;            m_exporting = false;        }         private void buttonExport_Click(object sender, EventArgs e)        {            if (string.IsNullOrEmpty(textBoxExportFileName.Text))            {                MessageBox.Show("You must define an export file name before export.", "Error", MessageBoxButtons.OK);            }            else            {                m_exporting = true;                SetButtonsEnabledState(false);                ClearUpdateMessages();                UpdateProgressBar(0);                SetProgressBarMaximum(100);                 tabControlOptions.SelectedTab = tabPageMessages;                 // Kick off a thread to start archive read                new Thread(ExportData) {IsBackground = true}.Start();            }        }         private void dataGridViewDevices_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)        {            DataGridViewColumn column = dataGridViewDevices.Columns[e.ColumnIndex];             if (column.SortMode == DataGridViewColumnSortMode.NotSortable)                return;             SortOrder sortOrder = InvertSortOrder(column.HeaderCell);            m_metadata.Devices.Sort(new DeviceDetailComparer(column.Name, sortOrder));             // Refresh data grid            RefreshDevicesDataGrid();            dataGridViewDevices.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = sortOrder;        }         private void dataGridViewDevices_CellContentClick(object sender, DataGridViewCellEventArgs e)        {            if (e.RowIndex < 0 || e.RowIndex > m_metadata.Devices.Count)                return;             DataGridViewColumn column = dataGridViewDevices.Columns[e.ColumnIndex];             if (column.Name.Equals("Selected", StringComparison.OrdinalIgnoreCase))            {                m_metadata.Devices[e.RowIndex].Selected = !m_metadata.Devices[e.RowIndex].Selected;                dataGridViewDevices.RefreshEdit();            }             RefreshSelectedCount();        }         private void dataGridViewDevices_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)        {            for (int i = 0; i < dataGridViewDevices.ColumnCount; i++)            {                DataGridViewColumn column = dataGridViewDevices.Columns[i];                column.ReadOnly = !column.Name.Equals("Selected", StringComparison.OrdinalIgnoreCase);                column.Visible = !column.Name.Equals("UniqueID", StringComparison.OrdinalIgnoreCase);                column.SortMode = DataGridViewColumnSortMode.Programmatic;                column.Resizable = DataGridViewTriState.True;            }             dataGridViewDevices.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;            dataGridViewDevices.Columns[0].Width = 80;        }         private void checkBoxSelectAllDevices_CheckedChanged(object sender, EventArgs e)        {                     bool selected = checkBoxSelectAllDevices.Checked;             foreach (DeviceDetail device in m_metadata.Devices)                device.Selected = selected;             RefreshDevicesDataGrid();            RefreshSelectedCount();        }         private void checkedListBoxDataTypes_SelectedIndexChanged(object sender, EventArgs e)        {                        if (!checkBoxExportFilePerDataType.Checked)                RefreshFilterExpression(-1);             RefreshSelectedCount();        }         private void checkBoxExportFilePerDataType_CheckedChanged(object sender, EventArgs e)        {            if (!m_formLoaded)                return;             RefreshFilterExpression(-1);            FormElementChanged(sender, e);        }         private void textBoxExportFileName_TextChanged(object sender, EventArgs e)        {            if (!m_formLoaded)                return;             buttonExport.Enabled = !string.IsNullOrEmpty(textBoxExportFileName.Text);            FormElementChanged(sender, e);        }         private void buttonSelectFile_Click(object sender, EventArgs e)        {            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)            {                textBoxExportFileName.Text = saveFileDialog.FileName;                textBoxExportFileName.SelectionStart = textBoxExportFileName.Text.Length;                textBoxExportFileName.SelectionLength = 0;            }        }         private void RefreshDevicesDataGrid()        {            if (InvokeRequired)            {                BeginInvoke(new Action(RefreshDevicesDataGrid));            }            else            {                dataGridViewDevices.DataSource = null;                dataGridViewDevices.DataSource = m_metadata.Devices;                 CenterColumn(nameof(DeviceDetail.Missing));                CenterColumn(nameof(DeviceDetail.BadData));                CenterColumn(nameof(DeviceDetail.BadTime));            }        }         private void CenterColumn(string name)        {            DataGridViewColumn column = dataGridViewDevices.Columns[name];             if (column is null)                return;             //column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;            column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;        }         private void RefreshSelectedCount()        {            if (InvokeRequired)            {                BeginInvoke(new Action(RefreshSelectedCount));            }            else            {                if (Visible && m_formLoaded)                {                    int selectedCount = SelectedDeviceCount;                     labelSelectCount.Text = string.Format(labelSelectCount.Tag.ToString(), selectedCount);                     if (selectedCount == m_metadata.Devices.Count && m_metadata.Devices.Count > 0)                        checkBoxSelectAllDevices.Checked = true;                    else if (selectedCount == 0)                        checkBoxSelectAllDevices.Checked = false;                     RefreshFilterExpression(selectedCount);                     try                    {                        AdapterBase.ParseFilterExpression(textBoxFilterExpression.Text, out string _, out string filterExpression, out string _, out int _);                         filterExpression = filterExpression                            .Replace("Device", "DeviceAcronym")                            .Replace("SignalType", "SignalAcronym")                            .Replace("Company", "CompanyAcronym")                            .Replace("Protocol", "ProtocolAcronym");                         int measurementCount = m_metadata.MeasurementTable.Select(filterExpression).Length;                        labelMeasurementCount.Text = string.Format(labelMeasurementCount.Tag.ToString(), measurementCount);                    }                    catch (Exception ex)                    {                        labelMeasurementCount.Text = string.Format(labelMeasurementCount.Tag.ToString(), 0);                        Logger.SwallowException(ex);                    }                     buttonPreFilter.Enabled = selectedCount > 0;                }            }        }         private void RefreshFilterExpression(int selectedCount)        {            if (selectedCount == -1)                selectedCount = SelectedDeviceCount;             textBoxFilterExpression.Text = GenerateFilterExpression(checkedListBoxDataTypes.CheckedItems.Cast<string>(), selectedCount);        }         private string GenerateFilterExpression(IEnumerable<string> signalTypes, int selectedDeviceCount)        {            StringBuilder filterExpression = new StringBuilder();             if (selectedDeviceCount > 0)                filterExpression.Append($"Device IN ({string.Join(", ", m_metadata.Devices.Where(device => device.Selected).Select(device => $"'{device.Name}'"))})");             if (m_settings.DeviceFilter?.Length > 0)                filterExpression.Append($" AND Device LIKE '{m_settings.DeviceFilter}'");             if (m_settings.PhaseFilter?.Length > 0)            {                string[] phaseValues = m_settings.PhaseFilter.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);                 if (phaseValues.Length > 0)                {                    string[] phases = phaseValues.Select(value => $"'{value.Trim()[0]}'").ToArray();                    filterExpression.Append($" AND (Phase IS NULL OR Phase IN ({string.Join(", ", phases)}))");                }            }             if (signalTypes.Any())            {                if (filterExpression.Length > 0)                    filterExpression.Append(" AND ");                 filterExpression.Append($"SignalType IN ({string.Join(", ", signalTypes.Select(item => $"'{item}'"))})");            }             return filterExpression.Length > 0 ? string.Format(textBoxFilterExpression.Tag.ToString(), filterExpression) : "";        }         private SortOrder InvertSortOrder(DataGridViewColumnHeaderCell headerCell)        {            if (headerCell.SortGlyphDirection == SortOrder.None || headerCell.SortGlyphDirection == SortOrder.Descending)            {                headerCell.SortGlyphDirection = SortOrder.Ascending;                return SortOrder.Ascending;            }             headerCell.SortGlyphDirection = SortOrder.Descending;            return SortOrder.Descending;        }         private void textBoxDeviceFilter_TextChanged(object sender, EventArgs e)        {            if (InvokeRequired)            {                BeginInvoke(new Action<object, EventArgs>(textBoxDeviceFilter_TextChanged), sender, e);            }            else            {                FormElementChanged(sender, e);                RefreshSelectedCount();                 ThreadPool.QueueUserWorkItem(_ =>                {                    try                    {                        string deviceFilter = textBoxDeviceFilter.Text;                         if (!string.IsNullOrWhiteSpace(deviceFilter))                        {                            foreach (DeviceDetail record in m_metadata.Devices)                                record.Selected = false;                             foreach (DataRow row in m_metadata.DeviceTable.Select($"Acronym LIKE '{deviceFilter}'"))                            {                                if (!Guid.TryParse(row["UniqueID"].ToString(), out Guid uniqueID))                                    continue;                                 DeviceDetail record = m_metadata.Devices.FirstOrDefault(device => device.UniqueID == uniqueID);                                 if (record is null)                                    continue;                                 record.Selected = true;                            }                             RefreshDevicesDataGrid();                            RefreshSelectedCount();                        }                    }                    catch (Exception ex)                    {                        Logger.SwallowException(ex);                    }                });

Lines 1–500 of 1254.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t