示例#1
0
 private void ButtonAddMore_Click(object sender, RoutedEventArgs e)
 {
     OutputStreamDevice.AddDevices(null, m_outputStreamID, new ObservableCollection <Device>(m_newDevices.Where(d => d.Enabled)),
                                   (bool)CheckBoxAddDigitals.IsChecked, (bool)CheckBoxAddAnalogs.IsChecked);
     LoadCurrentDevices();
     PopupAddMore.IsOpen = false;
 }
示例#2
0
        void SaveOutputStreamDevice(OutputStreamDevice outputStreamDevice, bool isNew, string originalAcronym)
        {
            SystemMessages sm;

            try
            {
                string result = CommonFunctions.SaveOutputStreamDevice(null, outputStreamDevice, isNew, originalAcronym);
                sm = new SystemMessages(new Message()
                {
                    UserMessage = result, SystemMessage = string.Empty, UserMessageType = MessageType.Success
                },
                                        ButtonType.OkOnly);
                sm.Owner = Window.GetWindow(this);
                sm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                sm.ShowPopup();
                GetOutputStreamDeviceList();
                //ClearForm();

                //make this newly added or updated item as default selected. So user can click initialize right away.
                ListBoxOutputStreamDeviceList.SelectedItem = ((List <OutputStreamDevice>)ListBoxOutputStreamDeviceList.ItemsSource).Find(c => c.Acronym == outputStreamDevice.Acronym);
            }
            catch (Exception ex)
            {
                CommonFunctions.LogException(null, "WPF.SaveOutputStreamDevice", ex);
                sm = new SystemMessages(new Message()
                {
                    UserMessage = "Failed to Save Output Stream Device Information", SystemMessage = ex.Message, UserMessageType = MessageType.Error
                },
                                        ButtonType.OkOnly);
                sm.Owner = Window.GetWindow(this);
                sm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                sm.ShowPopup();
            }
        }
示例#3
0
        private void LoadCurrentDevices()
        {
            IList <int> keys = OutputStreamDevice.LoadKeys(null, m_outputStreamID);

            m_currentDevices = OutputStreamDevice.Load(null, keys);
            DataGridCurrentDevices.ItemsSource = m_currentDevices;
            if (m_currentDevices.Count == 0)
            {
                PopupAddMore.IsOpen = true;
            }
        }
示例#4
0
        void ListBoxOutputStreamDeviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListBoxOutputStreamDeviceList.SelectedIndex >= 0)
            {
                m_selectedOutputStreamDevice             = ListBoxOutputStreamDeviceList.SelectedItem as OutputStreamDevice;
                m_originalAcronym                        = m_selectedOutputStreamDevice.Acronym;
                GridOutputStreamDeviceDetail.DataContext = m_selectedOutputStreamDevice;
                CheckBoxEnabled.IsChecked                = m_selectedOutputStreamDevice.Enabled;

                if (string.IsNullOrEmpty(m_selectedOutputStreamDevice.AnalogDataFormat))
                {
                    ComboboxAnalogDataFormat.SelectedIndex = 0;
                }
                else
                {
                    ComboboxAnalogDataFormat.SelectedItem = m_selectedOutputStreamDevice.AnalogDataFormat;
                }

                if (string.IsNullOrEmpty(m_selectedOutputStreamDevice.CoordinateFormat))
                {
                    ComboboxCoordinateFormat.SelectedIndex = 0;
                }
                else
                {
                    ComboboxCoordinateFormat.SelectedItem = m_selectedOutputStreamDevice.CoordinateFormat;
                }

                if (string.IsNullOrEmpty(m_selectedOutputStreamDevice.FrequencyDataFormat))
                {
                    ComboboxFrequencyDataFormat.SelectedIndex = 0;
                }
                else
                {
                    ComboboxFrequencyDataFormat.SelectedItem = m_selectedOutputStreamDevice.FrequencyDataFormat;
                }

                if (string.IsNullOrEmpty(m_selectedOutputStreamDevice.PhasorDataFormat))
                {
                    ComboboxPhasorDataFormat.SelectedIndex = 0;
                }
                else
                {
                    ComboboxPhasorDataFormat.SelectedItem = m_selectedOutputStreamDevice.PhasorDataFormat;
                }
                m_inEditMode           = true;
                m_outputStreamDeviceID = m_selectedOutputStreamDevice.ID;

                ButtonSave.Tag = "Update";
            }
        }
示例#5
0
 public string SaveOutputStreamDevice(OutputStreamDevice outputStreamDevice, bool isNew, string originalAcronym)
 {
     try
     {
         return(CommonFunctions.SaveOutputStreamDevice(null, outputStreamDevice, isNew, originalAcronym));
     }
     catch (Exception ex)
     {
         CommonFunctions.LogException(null, "Service.SaveOutputStreamDevice", ex);
         CustomServiceFault fault = new CustomServiceFault()
         {
             UserMessage = "Failed to Save Output Stream Device Information", SystemMessage = ex.Message
         };
         throw new FaultException <CustomServiceFault>(fault);
     }
 }
        private void ButtonDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (OutputStreamDevice outputStreamDevice in m_currentDevices)
                {
                    if (outputStreamDevice.Selected)
                    {
                        OutputStreamDevice.Delete(null, m_outputStreamID, outputStreamDevice.Acronym);
                    }
                }

                LoadCurrentDevices();
                LoadNewDevices(string.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Delete Output Stream Device");
            }
        }
示例#7
0
        private void ButtonAddMore_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OutputStreamDevice.AddDevices(null, m_outputStreamID, new ObservableCollection <Device>(m_newDevices.Where(d => d.Enabled)),
                                              (bool)CheckBoxAddDigitals.IsChecked, (bool)CheckBoxAddAnalogs.IsChecked);

                LoadCurrentDevices();
                PopupAddMore.IsOpen = false;
            }
            catch (Exception ex)
            {
                string message = $"Error while adding device to output stream:{Environment.NewLine}{ex.Message}";

                if (ex.Message.Contains("FK_OutputStreamMeasurement_Historian"))
                {
                    message += Environment.NewLine + Environment.NewLine + "The device may be referencing a non-existent historian.";
                }

                MessageBox.Show(Application.Current.MainWindow, message, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                CommonFunctions.LogException(null, "Output Wizard Add More", ex);
            }
        }
示例#8
0
        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
#if SILVERLIGHT
            Storyboard sb = new Storyboard();
            sb            = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();
#endif
            if (IsValid())
            {
                OutputStreamDevice outputStreamDevice = new OutputStreamDevice();
                App app = (App)Application.Current;
                outputStreamDevice.NodeID              = app.NodeValue;
                outputStreamDevice.AdapterID           = m_sourceOutputStreamID;
                outputStreamDevice.Acronym             = TextBoxAcronym.Text.CleanText();
                outputStreamDevice.BpaAcronym          = TextBoxBPAAcronym.Text.CleanText();
                outputStreamDevice.Name                = TextBoxName.Text.CleanText();
                outputStreamDevice.LoadOrder           = TextBoxLoadOrder.Text.ToInteger();
                outputStreamDevice.Enabled             = (bool)CheckBoxEnabled.IsChecked;
                outputStreamDevice.PhasorDataFormat    = ComboboxPhasorDataFormat.SelectedIndex == 0 ? string.Empty : ComboboxPhasorDataFormat.SelectedItem.ToString();
                outputStreamDevice.FrequencyDataFormat = ComboboxFrequencyDataFormat.SelectedIndex == 0 ? string.Empty : ComboboxFrequencyDataFormat.SelectedItem.ToString();
                outputStreamDevice.AnalogDataFormat    = ComboboxAnalogDataFormat.SelectedIndex == 0 ? string.Empty : ComboboxAnalogDataFormat.SelectedItem.ToString();
                outputStreamDevice.CoordinateFormat    = ComboboxCoordinateFormat.SelectedIndex == 0 ? string.Empty : ComboboxCoordinateFormat.SelectedItem.ToString();
                outputStreamDevice.IdCode              = TextBoxIDCode.Text.ToInteger();

                if (m_inEditMode == true && m_outputStreamDeviceID > 0)
                {
                    outputStreamDevice.ID = m_outputStreamDeviceID;
                    SaveOutputStreamDevice(outputStreamDevice, false, m_originalAcronym);
                }
                else
                {
                    SaveOutputStreamDevice(outputStreamDevice, true, string.Empty);
                }
            }
        }
示例#9
0
        /// <summary>
        /// Deletes current item from the database.
        /// </summary>
        public override void Delete()
        {
            try
            {
                if (CurrentItem.IsConcentrator)
                {
                    IList <int> keys = Device.LoadKeys(null, CurrentItem.ID);
                    ObservableCollection <Device> deviceList = Device.Load(null, keys);
                    int outputStreamDeviceCount = 0;

                    string result;

                    foreach (Device device in deviceList)
                    {
                        outputStreamDeviceCount += OutputStreamDevice.GetOutputStreamDevices(null, "WHERE Acronym = '" + device.Acronym + "'").Count;
                    }

                    string confirm = "Are you sure you want to delete concentrator device?";
                    if (deviceList.Count > 1)
                    {
                        confirm += Environment.NewLine + "There are " + deviceList.Count.ToString() + " associated children devices.";
                    }
                    else if (deviceList.Count > 0)
                    {
                        confirm += Environment.NewLine + "There is " + deviceList.Count.ToString() + " associated child device.";
                    }

                    if (outputStreamDeviceCount > 1)
                    {
                        confirm += Environment.NewLine + "There are " + outputStreamDeviceCount.ToString() + " output stream devices that exist.";
                    }
                    else if (outputStreamDeviceCount > 0)
                    {
                        confirm += Environment.NewLine + "There is " + outputStreamDeviceCount.ToString() + " output stream device that exists.";
                    }

                    if (Confirm(confirm, "Delete Device"))
                    {
                        foreach (Device device in deviceList)
                        {
                            Device.Delete(null, device);
                        }

                        result = Device.Delete(null, CurrentItem);
                        DisplayStatusMessage(result);
                    }
                }
                else
                {
                    ObservableCollection <OutputStreamDevice> outputStreamDevices = OutputStreamDevice.GetOutputStreamDevices(null, "WHERE Acronym = '" + CurrentItem.Acronym + "'");
                    string confirm = "Are you sure you want to delete this device?";

                    if (outputStreamDevices.Count > 1)
                    {
                        confirm += Environment.NewLine + "It exists in " + outputStreamDevices.Count.ToString() + " output streams.";
                    }
                    else if (outputStreamDevices.Count > 0)
                    {
                        confirm += Environment.NewLine + "It exists in " + outputStreamDevices.Count.ToString() + " output stream.";
                    }

                    if (Confirm(confirm, "Delete Device"))
                    {
                        string result = Device.Delete(null, CurrentItem);
                        DisplayStatusMessage(result);
                    }
                }

                Device.NotifyService(null, CurrentItem.HistorianID);
                CommonFunctions.LoadUserControl("Browse Devices", typeof(DeviceListUserControl));
            }
            catch (Exception ex)
            {
                if ((object)ex.InnerException != null)
                {
                    Popup(ex.Message + Environment.NewLine + "Inner Exception: " + ex.InnerException.Message, "Delete Device Exception:", MessageBoxImage.Error);
                    CommonFunctions.LogException(null, "Delete Device", ex.InnerException);
                }
                else
                {
                    Popup(ex.Message, "Delete Device Exception:", MessageBoxImage.Error);
                    CommonFunctions.LogException(null, "Delete Device", ex);
                }
            }
        }
示例#10
0
        /// <summary>
        /// Saves <see cref="Device"/> information into database.
        /// </summary>
        public override void Save()
        {
            Mouse.OverrideCursor = Cursors.Wait;

            try
            {
                Device originalDevice = null;

                // If it is an existing device being modified, get prior state so we can determine if a rename occurred.
                if (CurrentItem.ID > 0)
                {
                    originalDevice = Device.GetDevice(null, "WHERE ID = " + CurrentItem.ID);
                }

                // Attempt to save base record before possible rename attempt as base record save can fail
                base.Save();

                try
                {
                    // If renaming a phasor device (e.g., a PMU not a PDC), check if user would like to update device acronym in output streams - this happens here
                    // instead of in the view model such that a message box can be displayed in the UI to engage user about desire to update output streams. We only
                    // perform this task for phasor style connections since renaming subscribed devices, although functional, will not "stick" - renamed devices will
                    // be reverted back to their original names at the next meta-data refresh.
                    if (!CurrentItem.IsConcentrator && (object)originalDevice != null && string.Compare(CurrentItem.ProtocolCategory, "Phasor", StringComparison.OrdinalIgnoreCase) == 0 &&
                        (string.CompareOrdinal(CurrentItem.Acronym, originalDevice.Acronym) != 0 || string.CompareOrdinal(CurrentItem.Name, originalDevice.Name) != 0) &&
                        Confirm("Device was renamed, do you want to also update the device name where it may exist in output streams?", "Update Output Stream Device"))
                    {
                        ObservableCollection <OutputStreamDevice> outputStreamDevices = OutputStreamDevice.GetOutputStreamDevices(null, "WHERE Acronym = '" + originalDevice.Acronym + "'");

                        foreach (OutputStreamDevice device in outputStreamDevices)
                        {
                            device.Acronym    = CurrentItem.Acronym;
                            device.BpaAcronym = CurrentItem.Acronym.Substring(0, 4);
                            device.Name       = CurrentItem.Name;
                            OutputStreamDevice.Save(null, device);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if ((object)ex.InnerException != null)
                    {
                        Popup(ex.Message + Environment.NewLine + "Inner Exception: " + ex.InnerException.Message, "Device Rename:", MessageBoxImage.Error);
                        CommonFunctions.LogException(null, "Device Rename", ex.InnerException);
                    }
                    else
                    {
                        Popup(ex.Message, "Device Rename Exception:", MessageBoxImage.Error);
                        CommonFunctions.LogException(null, "Device Rename", ex);
                    }
                }

                // If user is on form page then go back to list page after save.
                if (ItemsPerPage == 0)
                {
                    if (!m_stayOnConfigurationScreen)
                    {
                        CommonFunctions.LoadUserControl("Browse Devices", typeof(DeviceListUserControl));
                    }
                }
            }
            catch (Exception ex)
            {
                if ((object)ex.InnerException != null)
                {
                    Popup(ex.Message + Environment.NewLine + "Inner Exception: " + ex.InnerException.Message, "Save Device Exception:", MessageBoxImage.Error);
                    CommonFunctions.LogException(null, "Save Device", ex.InnerException);
                }
                else
                {
                    Popup(ex.Message, "Save Device Exception:", MessageBoxImage.Error);
                    CommonFunctions.LogException(null, "Save Device", ex);
                }
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
        }
示例#11
0
        static int Main()
        {
            int row = 0;

            try
            {
                // Handle command line arguments
                Arguments args = new Arguments(Environment.CommandLine, true);
                bool      skipFirstRow;
                int       successes = 0, failures = 0;

                // First ordered argument is source CSV file name, it is required
                if (args.Count < RequiredArgumentCount)
                {
                    throw new ArgumentException($"Expected {RequiredArgumentCount:N0} argument, received {args.Count:N0}.");
                }

                // Check for switch based arguments
                if (!args.TryGetValue("sourceApp", out string sourceApp))   // Source GPA application, defaults to "SIEGate"
                {
                    sourceApp = DefaultSourceApp;
                }

                if (!args.TryGetValue("outputName", out string outputName)) // Target IEEE C37.118 output stream name, defaults to "IMPORTEDSTREAM"
                {
                    outputName = DefaultOutputName;
                }

                if (args.TryGetValue("skipFirstRow", out string setting))   // Setting to skip first row of import file, default to true
                {
                    skipFirstRow = setting.ParseBoolean();
                }
                else
                {
                    skipFirstRow = true;
                }

                // Make sure output name is upper case, this is an acronym for the output adapter in the target system
                outputName = outputName.ToUpperInvariant();

                // Make provided files name are relative to run path if not other path was provided
                string sourceFileName = FilePath.GetAbsolutePath(args["OrderedArg1"]);

            #if DEBUG
                string configFile = "C:\\Program Files\\openPDC\\openPDC.exe.config";
            #else
                string configFile = FilePath.GetAbsolutePath($"{sourceApp}.exe.config");
            #endif

                if (!File.Exists(configFile))
                {
                    configFile = FilePath.GetAbsolutePath($"..\\{sourceApp}.exe.config");

                    // Fail if source config file cannot be found
                    if (!File.Exists(configFile))
                    {
                        throw new FileNotFoundException($"Config file for {sourceApp} application \"{configFile}\" was not found. Checked this folder and parent folder.");
                    }
                }

                // Load needed database settings from target config file
                XDocument serviceConfig = XDocument.Load(configFile);

                nodeID = Guid.Parse(serviceConfig
                                    .Descendants("systemSettings")
                                    .SelectMany(systemSettings => systemSettings.Elements("add"))
                                    .Where(element => "NodeID".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                    .Select(element => (string)element.Attribute("value"))
                                    .FirstOrDefault());

                string connectionString = serviceConfig
                                          .Descendants("systemSettings")
                                          .SelectMany(systemSettings => systemSettings.Elements("add"))
                                          .Where(element => "ConnectionString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                          .Select(element => (string)element.Attribute("value"))
                                          .FirstOrDefault();

                string dataProviderString = serviceConfig
                                            .Descendants("systemSettings")
                                            .SelectMany(systemSettings => systemSettings.Elements("add"))
                                            .Where(element => "DataProviderString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                            .Select(element => (string)element.Attribute("value"))
                                            .FirstOrDefault();

                // Open database schema and input CSV file
                using (AdoDataConnection connection = new AdoDataConnection(connectionString, dataProviderString))
                    using (StreamReader reader = File.OpenText(sourceFileName))
                    {
                        // Configuration database tracks user changes for CIP reasons, use current user for ID
                        currentUserID = UserInfo.CurrentUserID ?? DefaultUserID;

                        // Setup database table operations for OutputStream table - this allows model, i.e., class instance representing record, based CRUD operations
                        TableOperations <OutputStream> outputStreamTable = new TableOperations <OutputStream>(connection);

                        // See if target output stream already exists
                        OutputStream outputStream = outputStreamTable.QueryRecordWhere("NodeID = {0} AND Acronym = {1}", nodeID, outputName);

                        if (outputStream == null)
                        {
                            // Setup a new output stream using default settings (user can adjust later as needed)
                            outputStream = new OutputStream
                            {
                                NodeID                        = nodeID,
                                Acronym                       = outputName,
                                Name                          = outputName,
                                ConnectionString              = "RoundToNearestTimestamp=True; addPhaseLabelSuffix=false;",
                                DataChannel                   = "port=-1; clients=localhost:4712; interface=0.0.0.0",
                                AutoPublishConfigFrame        = true,
                                AutoStartDataChannel          = true,
                                NominalFrequency              = 60,
                                FramesPerSecond               = 30,
                                LagTime                       = 5.0D,
                                LeadTime                      = 5.0D,
                                AllowSortsByArrival           = true,
                                TimeResolution                = 330000,
                                AllowPreemptivePublishing     = true,
                                PerformTimeReasonabilityCheck = true,
                                DownsamplingMethod            = "LastReceived",
                                DataFormat                    = "FloatingPoint",
                                CoordinateFormat              = "Polar",
                                CurrentScalingValue           = 2423,
                                VoltageScalingValue           = 2725785,
                                AnalogScalingValue            = 1373291,
                                DigitalMaskValue              = -65536,
                                Enabled                       = true,
                                CreatedOn                     = DateTime.UtcNow,
                                CreatedBy                     = currentUserID,
                                UpdatedOn                     = DateTime.UtcNow,
                                UpdatedBy                     = currentUserID
                            };

                            outputStreamTable.AddNewRecord(outputStream);
                            outputStream = outputStreamTable.QueryRecordWhere("NodeID = {0} AND Acronym = {1}", nodeID, outputName);

                            if (outputStream == null)
                            {
                                throw new InvalidOperationException($"Failed to lookup OutputStream record with Acronym of \"{outputName}\".");
                            }
                        }
                        else
                        {
                            // If record already exists, just track updates by user with timestamp
                            outputStream.UpdatedOn = DateTime.UtcNow;
                            outputStream.UpdatedBy = currentUserID;
                            outputStreamTable.UpdateRecord(outputStream);
                        }

                        // Setup database table operations for other needed tables
                        TableOperations <Device>                   deviceTable                   = new TableOperations <Device>(connection);
                        TableOperations <Measurement>              measurementTable              = new TableOperations <Measurement>(connection);
                        TableOperations <Phasor>                   phasorTable                   = new TableOperations <Phasor>(connection);
                        TableOperations <OutputStreamDevice>       outputStreamDeviceTable       = new TableOperations <OutputStreamDevice>(connection);
                        TableOperations <OutputStreamMeasurement>  outputStreamMeasurementTable  = new TableOperations <OutputStreamMeasurement>(connection);
                        TableOperations <OutputStreamDevicePhasor> outputStreamDevicePhasorTable = new TableOperations <OutputStreamDevicePhasor>(connection);

                        Device             device             = null;
                        OutputStreamDevice outputStreamDevice = null;

                        string line, lastDeviceName = null;
                        int    deviceIndex = 0, phasorIndex = 0;

                        // Loop through each line in CSV input file
                        while ((line = reader.ReadLine()) != null)
                        {
                            row++;

                            if (skipFirstRow)
                            {
                                skipFirstRow = false;
                                continue;
                            }

                            string[] columns = line.Split(',');

                            if (columns.Length < 6)
                            {
                                Console.WriteLine($"Not enough columns in CSV file at row {row} - expected 6, encountered {columns.Length}, skipped row.");
                                continue;
                            }

                            // Read columns of data from current row
                            string sourceDeviceName = columns[0].ToUpperInvariant().Trim();
                            string destDeviceName   = columns[1].ToUpperInvariant().Trim();
                            string sourcePhasorName = columns[2].ToUpperInvariant().Trim();
                            string destPhasorName   = columns[3].ToUpperInvariant().Trim();
                            ushort idCode           = ushort.Parse(columns[4].Trim());
                            string description      = columns[5].Trim();

                            if (!sourceDeviceName.Equals(lastDeviceName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                lastDeviceName = sourceDeviceName;
                                deviceIndex++;
                                phasorIndex = 0;

                                // Lookup existing source device
                                device = deviceTable.QueryRecordWhere("Acronym = {0}", sourceDeviceName);

                                if (device == null)
                                {
                                    Console.WriteLine($"Failed to find source device \"{sourceDeviceName}\" - cannot create new output stream device for \"{destDeviceName}\".");
                                    failures++;
                                    continue;
                                }

                                Console.WriteLine($"Mapping source device \"{sourceDeviceName}\" to output stream device \"{destDeviceName}\"...");

                                // Setup a new output stream device
                                outputStreamDevice = outputStreamDeviceTable.QueryRecordWhere("NodeID = {0} AND AdapterID = {1} AND Acronym = {2}", nodeID, outputStream.ID, destDeviceName);

                                if (outputStreamDevice == null)
                                {
                                    outputStreamDevice = new OutputStreamDevice
                                    {
                                        NodeID    = nodeID,
                                        AdapterID = outputStream.ID,
                                        IDCode    = idCode > 0 ? idCode : deviceIndex,
                                        Acronym   = destDeviceName,
                                        Name      = destDeviceName.ToTitleCase(),
                                        Enabled   = true,
                                        CreatedOn = DateTime.UtcNow,
                                        CreatedBy = currentUserID,
                                        UpdatedOn = DateTime.UtcNow,
                                        UpdatedBy = currentUserID
                                    };

                                    outputStreamDeviceTable.AddNewRecord(outputStreamDevice);
                                    outputStreamDevice = outputStreamDeviceTable.QueryRecordWhere("NodeID = {0} AND AdapterID = {1} AND Acronym = {2}", nodeID, outputStream.ID, destDeviceName);

                                    if (outputStreamDevice == null)
                                    {
                                        throw new InvalidOperationException($"Failed to lookup OutputStreamDevice record with Acronym of \"{destDeviceName}\".");
                                    }
                                }
                                else
                                {
                                    // TODO: Could augment existing record, current logic just skips existing to account for possible input file errors
                                    outputStreamDevice.IDCode    = idCode > 0 ? idCode : deviceIndex;
                                    outputStreamDevice.UpdatedOn = DateTime.UtcNow;
                                    outputStreamDevice.UpdatedBy = currentUserID;
                                    outputStreamDeviceTable.UpdateRecord(outputStreamDevice);
                                }

                                // Validate base output stream measurements exist
                                foreach (string signalType in new[] { "SF", "FQ", "DF" }) // Status flags, frequency and dF/dT (delta frequency over delta time, i.e., rate of change of frequency)
                                {
                                    AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-{signalType}", $"{destDeviceName}-{signalType}");
                                }
                            }

                            if (device == null)
                            {
                                failures++;
                                continue;
                            }

                            //                  123456789012345678901234567890
                            Console.WriteLine($"    Adding phasors for \"{$"{destPhasorName} - {description}".TrimWithEllipsisEnd(70)}\"");

                            // Lookup existing device phasor record
                            Phasor phasor = phasorTable.QueryRecordWhere("DeviceID = {0} AND Label = {1}", device.ID, sourcePhasorName);
                            phasorIndex++;

                            if (phasor == null)
                            {
                                Console.WriteLine($"Failed to lookup Phasor record with Label of \"{sourcePhasorName}\"");
                                failures++;
                            }
                            else
                            {
                                // Setup a new output stream device phasor
                                OutputStreamDevicePhasor outputStreamDevicePhasor = outputStreamDevicePhasorTable.QueryRecordWhere("NodeID = {0} AND OutputStreamDeviceID = {1} AND Label = {2}", nodeID, outputStreamDevice.ID, destPhasorName);

                                if (outputStreamDevicePhasor == null)
                                {
                                    outputStreamDevicePhasor = new OutputStreamDevicePhasor
                                    {
                                        NodeID = nodeID,
                                        OutputStreamDeviceID = outputStreamDevice.ID,
                                        Label     = destPhasorName,
                                        Type      = phasor.Type,
                                        Phase     = phasor.Phase,
                                        LoadOrder = phasorIndex,
                                        CreatedOn = DateTime.UtcNow,
                                        CreatedBy = currentUserID,
                                        UpdatedOn = DateTime.UtcNow,
                                        UpdatedBy = currentUserID
                                    };

                                    outputStreamDevicePhasorTable.AddNewRecord(outputStreamDevicePhasor);
                                    outputStreamDevicePhasor = outputStreamDevicePhasorTable.QueryRecordWhere("NodeID = {0} AND OutputStreamDeviceID = {1} AND Label = {2}", nodeID, outputStreamDevice.ID, destPhasorName);

                                    if (outputStreamDevicePhasor == null)
                                    {
                                        throw new InvalidOperationException($"Failed to lookup OutputStreamDevicePhasor record with Label of \"{destPhasorName}\".");
                                    }
                                }
                                else
                                {
                                    // TODO: Could augment existing record, current logic just skips existing to account for possible input file errors
                                    outputStreamDevicePhasor.UpdatedOn = DateTime.UtcNow;
                                    outputStreamDevicePhasor.UpdatedBy = currentUserID;
                                    outputStreamDevicePhasorTable.UpdateRecord(outputStreamDevicePhasor);
                                }

                                // Define output stream phasor measurements
                                AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-PA{phasor.SourceIndex}", $"{destDeviceName}-PA{phasorIndex}");
                                AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-PM{phasor.SourceIndex}", $"{destDeviceName}-PM{phasorIndex}");

                                successes++;
                            }
                        }
                    }

                Console.WriteLine();
                Console.WriteLine($"{successes:N0} successful phasor imports.");
                Console.WriteLine($"{failures:N0} failed phasor imports.");

            #if DEBUG
                Console.ReadKey();
            #endif

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"Import halted at row {row}!");
                Console.Error.WriteLine($"Load Exception: {ex.Message}");

                return(1);
            }
        }
 void SaveOutputStreamDevice(OutputStreamDevice outputStreamDevice, bool isNew, string originalAcronym)
 {
     m_client.SaveOutputStreamDeviceAsync(outputStreamDevice, isNew, originalAcronym);
 }
示例#13
0
 void SaveOutputStreamDevice(OutputStreamDevice outputStreamDevice, bool isNew, string originalAcronym)
 {
     m_client.SaveOutputStreamDeviceAsync(outputStreamDevice, isNew, originalAcronym);
 }