diff --git a/Source/Applications/Wave Demo Apps/UpdateWAVMetaData/Program.cs b/Source/Applications/Wave Demo Apps/UpdateWAVMetaData/Program.cs index d2b86fb8485..5eaf983d0bc 100755 --- a/Source/Applications/Wave Demo Apps/UpdateWAVMetaData/Program.cs +++ b/Source/Applications/Wave Demo Apps/UpdateWAVMetaData/Program.cs @@ -48,24 +48,9 @@ static int Main(string[] args) Guid nodeID = systemSettings["NodeID"].ValueAs(); bool useMemoryCache = systemSettings["UseMemoryCache"].ValueAsBoolean(false); string connectionString = systemSettings["ConnectionString"].Value; - string nodeIDQueryString = null; string parameterizedQuery; int protocolID, signalTypePMID, signalTypePAID; - // Define guid with query string delimiters according to database needs - Dictionary settings = connectionString.ParseKeyValuePairs(); - string setting; - - if (settings.TryGetValue("Provider", out setting)) - { - // Check if provider is for Access since it uses braces as Guid delimiters - if (setting.StartsWith("Microsoft.Jet.OLEDB", StringComparison.OrdinalIgnoreCase)) - nodeIDQueryString = "{" + nodeID + "}"; - } - - if (string.IsNullOrWhiteSpace(nodeIDQueryString)) - nodeIDQueryString = "'" + nodeID + "'"; - using (AdoDataConnection database = new AdoDataConnection("systemSettings")) { IDbConnection connection = database.Connection; @@ -109,12 +94,12 @@ static int Main(string[] args) if (Convert.ToInt32(connection.ExecuteScalar(database.ParameterizedQueryString("SELECT COUNT(*) FROM Device WHERE Acronym = {0}", "acronym"), acronym)) == 0) { parameterizedQuery = database.ParameterizedQueryString("INSERT INTO Device(NodeID, Acronym, Name, ProtocolID, FramesPerSecond, " + - "MeasurementReportingInterval, ConnectionString, Enabled) VALUES(" + nodeIDQueryString + ", {0}, {1}, {2}, {3}, {4}, {5}, {6})", + "MeasurementReportingInterval, ConnectionString, Enabled) VALUES({7}, {0}, {1}, {2}, {3}, {4}, {5}, {6})", "acronym", "name", "protocolID", "framesPerSecond", "measurementReportingInterval", "connectionString", "enabled"); // Insert new device record - connection.ExecuteNonQuery(parameterizedQuery, acronym, name, protocolID, sourceWave.SampleRate, 1000000, $"wavFileName={FilePath.GetAbsolutePath(sourceFileName)}; connectOnDemand=true; outputSourceIDs={acronym}; memoryCache={useMemoryCache}", database.Bool(true)); + connection.ExecuteNonQuery(parameterizedQuery, acronym, name, protocolID, sourceWave.SampleRate, 1000000, $"wavFileName={FilePath.GetAbsolutePath(sourceFileName)}; connectOnDemand=true; outputSourceIDs={acronym}; memoryCache={useMemoryCache}", database.Bool(true), nodeID); int deviceID = Convert.ToInt32(connection.ExecuteScalar(database.ParameterizedQueryString("SELECT ID FROM Device WHERE Acronym = {0}", "acronym"), acronym)); string pointTag; int lastPhasorIndex = 0; diff --git a/Source/Libraries/Adapters/DeviceStatAdapters/DeviceStats.cs b/Source/Libraries/Adapters/DeviceStatAdapters/DeviceStats.cs index fdd56efd076..56d3a682479 100644 --- a/Source/Libraries/Adapters/DeviceStatAdapters/DeviceStats.cs +++ b/Source/Libraries/Adapters/DeviceStatAdapters/DeviceStats.cs @@ -406,7 +406,7 @@ public override void Initialize() { // Load any newly defined devices into the statistics device table TableOperations deviceTable = new(statConnection); - DataRow[] devices = gsfConnection.RetrieveData($"SELECT * FROM Device WHERE IsConcentrator = 0 AND AccessID <> {DeviceGroupAccessID}").Select(); + DataRow[] devices = gsfConnection.RetrieveData("SELECT * FROM Device WHERE IsConcentrator = 0 AND AccessID <> {0}", DeviceGroupAccessID).Select(); foreach (DataRow device in devices) { diff --git a/Source/Libraries/Adapters/GrafanaAdapters/DeviceAlarmStateAdapter.cs b/Source/Libraries/Adapters/GrafanaAdapters/DeviceAlarmStateAdapter.cs index d8e269d7ff9..23f88982208 100644 --- a/Source/Libraries/Adapters/GrafanaAdapters/DeviceAlarmStateAdapter.cs +++ b/Source/Libraries/Adapters/GrafanaAdapters/DeviceAlarmStateAdapter.cs @@ -415,14 +415,16 @@ private void LoadAlarmStates(bool reload = false) m_alarmStateIDs[alarmStateRecord.ID] = alarmState; } - // Define SQL expression for direct connect and parent devices or all direct connect and child devices - string deviceSQL = TargetParentDevices ? - "SELECT * FROM Device WHERE (IsConcentrator != 0 OR ParentID IS NULL) AND ID NOT IN (SELECT DeviceID FROM AlarmDevice)" : - $"SELECT * FROM Device WHERE IsConcentrator = 0 AND AccessID <> {DeviceGroupAccessID} AND ID NOT IN (SELECT DeviceID FROM AlarmDevice)"; - // Load any newly defined devices into the alarm device table TableOperations alarmDeviceTable = new(connection); - DataRow[] newDevices = connection.RetrieveData(deviceSQL).Select(); + DataRow[] newDevices; + + // Define SQL expression for direct connect and parent devices or all direct connect and child devices + if (TargetParentDevices) + newDevices = connection.RetrieveData("SELECT * FROM Device WHERE (IsConcentrator != 0 OR ParentID IS NULL) " + + "AND ID NOT IN (SELECT DeviceID FROM AlarmDevice)").Select(); + else newDevices = connection.RetrieveData("SELECT * FROM Device WHERE IsConcentrator = 0 " + + "AND AccessID <> {0} AND ID NOT IN (SELECT DeviceID FROM AlarmDevice)", DeviceGroupAccessID).Select(); foreach (DataRow newDevice in newDevices) { @@ -451,7 +453,9 @@ private void LoadAlarmStates(bool reload = false) { // Querying from MeasurementDetail because we also want to include disabled device measurements string measurementSQL = TargetParentDevices ? - "SELECT MeasurementDetail.SignalID AS SignalID, MeasurementDetail.ID AS ID FROM MeasurementDetail INNER JOIN DeviceDetail ON MeasurementDetail.DeviceID = DeviceDetail.ID WHERE (DeviceDetail.Acronym = {0} OR DeviceDetail.ParentAcronym = {0}) AND MeasurementDetail.SignalAcronym = 'FREQ'" : + "SELECT MeasurementDetail.SignalID AS SignalID, MeasurementDetail.ID AS ID FROM MeasurementDetail " + + "INNER JOIN DeviceDetail ON MeasurementDetail.DeviceID = DeviceDetail.ID " + + "WHERE (DeviceDetail.Acronym = {0} OR DeviceDetail.ParentAcronym = {0}) AND MeasurementDetail.SignalAcronym = 'FREQ'" : "SELECT SignalID, ID FROM MeasurementDetail WHERE DeviceAcronym = {0} AND SignalAcronym = 'FREQ'"; DataTable table = connection.RetrieveData(measurementSQL, metadata.ConvertField("Acronym")); diff --git a/Source/Libraries/Adapters/HistorianAdapters/LocalOutputAdapter.cs b/Source/Libraries/Adapters/HistorianAdapters/LocalOutputAdapter.cs index 57c67cdad7f..5ca67b5c1a3 100755 --- a/Source/Libraries/Adapters/HistorianAdapters/LocalOutputAdapter.cs +++ b/Source/Libraries/Adapters/HistorianAdapters/LocalOutputAdapter.cs @@ -939,11 +939,11 @@ private static void OptimizeLocalHistorianSettings(AdoDataConnection database, s statusMessage("Optimizing settings for local historians..."); // Load the defined local system historians - IEnumerable historians = database.Connection.RetrieveData(database.AdapterType, $"SELECT AdapterName FROM RuntimeHistorian WHERE NodeID = {nodeIDQueryString} AND TypeName = 'HistorianAdapters.LocalOutputAdapter'").AsEnumerable(); - IEnumerable readers = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM CustomInputAdapter WHERE NodeID = {nodeIDQueryString} AND TypeName = 'HistorianAdapters.LocalInputAdapter'").AsEnumerable(); + IEnumerable historians = database.Connection.RetrieveData(database.AdapterType, "SELECT AdapterName FROM RuntimeHistorian WHERE NodeID = {0} AND TypeName = 'HistorianAdapters.LocalOutputAdapter'", nodeIDQueryString).AsEnumerable(); + IEnumerable readers = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM CustomInputAdapter WHERE NodeID = {0} AND TypeName = 'HistorianAdapters.LocalInputAdapter'", nodeIDQueryString).AsEnumerable(); // Also check for local historian adapters loaded into CustomOutputAdapters - historians = historians.Concat(database.Connection.RetrieveData(database.AdapterType, $"SELECT AdapterName, ConnectionString FROM RuntimeCustomOutputAdapter WHERE NodeID = {nodeIDQueryString} AND TypeName = 'HistorianAdapters.LocalOutputAdapter'").AsEnumerable()); + historians = historians.Concat(database.Connection.RetrieveData(database.AdapterType, "SELECT AdapterName, ConnectionString FROM RuntimeCustomOutputAdapter WHERE NodeID = {0} AND TypeName = 'HistorianAdapters.LocalOutputAdapter'", nodeIDQueryString).AsEnumerable()); string name, acronym, instanceName; @@ -1202,11 +1202,11 @@ private static void OptimizeLocalHistorianSettings(AdoDataConnection database, s private static void AddPIHistorianReaders(AdoDataConnection database, string nodeIDQueryString, Action processException) { // Load the defined local PI historians - IEnumerable historians = database.Connection.RetrieveData(database.AdapterType, $"SELECT AdapterName, ConnectionString FROM RuntimeHistorian WHERE NodeID = {nodeIDQueryString} AND TypeName = 'PIAdapters.PIOutputAdapter'").AsEnumerable(); - IEnumerable readers = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM CustomInputAdapter WHERE NodeID = {nodeIDQueryString} AND TypeName = 'PIAdapters.PIPBInputAdapter'").AsEnumerable(); + IEnumerable historians = database.Connection.RetrieveData(database.AdapterType, "SELECT AdapterName, ConnectionString FROM RuntimeHistorian WHERE NodeID = {0} AND TypeName = 'PIAdapters.PIOutputAdapter'", nodeIDQueryString).AsEnumerable(); + IEnumerable readers = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM CustomInputAdapter WHERE NodeID = {0} AND TypeName = 'PIAdapters.PIPBInputAdapter'", nodeIDQueryString).AsEnumerable(); // Also check for PI adapters loaded into CustomOutputAdapters - historians = historians.Concat(database.Connection.RetrieveData(database.AdapterType, $"SELECT AdapterName, ConnectionString FROM RuntimeCustomOutputAdapter WHERE NodeID = {nodeIDQueryString} AND TypeName = 'PIAdapters.PIOutputAdapter'").AsEnumerable()); + historians = historians.Concat(database.Connection.RetrieveData(database.AdapterType, "SELECT AdapterName, ConnectionString FROM RuntimeCustomOutputAdapter WHERE NodeID = {0} AND TypeName = 'PIAdapters.PIOutputAdapter'", nodeIDQueryString).AsEnumerable()); // Make sure a temporal reader is defined for each OSI-PI historian foreach (DataRow row in historians) diff --git a/Source/Libraries/Adapters/MetadataAdapters/MetadataExportAdapter.cs b/Source/Libraries/Adapters/MetadataAdapters/MetadataExportAdapter.cs index c0dd33398d8..1f094cd1e38 100644 --- a/Source/Libraries/Adapters/MetadataAdapters/MetadataExportAdapter.cs +++ b/Source/Libraries/Adapters/MetadataAdapters/MetadataExportAdapter.cs @@ -303,7 +303,7 @@ private DataSet AcquireMetadata() DataSet metadata = new DataSet(); // Initialize active node ID - Guid nodeID = Guid.Parse(dbConnection.ExecuteScalar($"SELECT NodeID FROM IaonActionAdapter WHERE ID = {ID}").ToString()); + Guid nodeID = Guid.Parse(dbConnection.ExecuteScalar("SELECT NodeID FROM IaonActionAdapter WHERE ID = {0}", ID).ToString()); // Copy key metadata tables foreach (string tableExpression in MetadataTables.Split(';')) diff --git a/Source/Libraries/Adapters/MetadataAdapters/MetadataImportAdapter.cs b/Source/Libraries/Adapters/MetadataAdapters/MetadataImportAdapter.cs index 43ee9044b9a..e85ded81471 100644 --- a/Source/Libraries/Adapters/MetadataAdapters/MetadataImportAdapter.cs +++ b/Source/Libraries/Adapters/MetadataAdapters/MetadataImportAdapter.cs @@ -443,7 +443,7 @@ private Action GetSynchronizeMetadataAction() // Determine the active node ID - we cache this since this value won't change for the lifetime of this class if (nodeID == Guid.Empty) - nodeID = Guid.Parse(command.ExecuteScalar($"SELECT NodeID FROM IaonActionAdapter WHERE ID = {(int)ID}", MetadataSynchronizationTimeout).ToString()); + nodeID = Guid.Parse(command.ExecuteScalar("SELECT NodeID FROM IaonActionAdapter WHERE ID = {0}", (int)ID, MetadataSynchronizationTimeout).ToString()); // Determine the protocol record auto-inc ID value for the gateway transport protocol (GEP) - this value is also cached since it shouldn't change for the lifetime of this class if (virtualProtocolID == 0) @@ -462,7 +462,7 @@ private Action GetSynchronizeMetadataAction() if (sourceID == null || sourceID == DBNull.Value) { // Get a historian ID, but exclude the STAT historian - object randomHistorianID = command.ExecuteScalar($"SELECT ID FROM Historian WHERE Acronym <> 'STAT'", MetadataSynchronizationTimeout); + object randomHistorianID = command.ExecuteScalar("SELECT ID FROM Historian WHERE Acronym <> 'STAT'", MetadataSynchronizationTimeout); command.ExecuteNonQuery(insertParentDeviceSql, MetadataSynchronizationTimeout, database.Guid(nodeID), randomHistorianID, ParentDeviceAcronym, ParentDeviceAcronym, virtualProtocolID); sourceID = command.ExecuteScalar(parentDeviceIDSql, MetadataSynchronizationTimeout, ParentDeviceAcronym); } @@ -470,11 +470,11 @@ private Action GetSynchronizeMetadataAction() int parentID = Convert.ToInt32(sourceID); // Validate that the subscriber device is marked as a concentrator (we are about to associate children devices with it) - if (!command.ExecuteScalar($"SELECT IsConcentrator FROM Device WHERE ID = {parentID}", MetadataSynchronizationTimeout).ToString().ParseBoolean()) - command.ExecuteNonQuery($"UPDATE Device SET IsConcentrator = 1 WHERE ID = {parentID}", MetadataSynchronizationTimeout); + if (!command.ExecuteScalar("SELECT IsConcentrator FROM Device WHERE ID = {0}", parentID, MetadataSynchronizationTimeout).ToString().ParseBoolean()) + command.ExecuteNonQuery("UPDATE Device SET IsConcentrator = 1 WHERE ID = {0}", parentID, MetadataSynchronizationTimeout); // Get any historian associated with the subscriber device - object historianID = command.ExecuteScalar($"SELECT HistorianID FROM Device WHERE ID = {parentID}", MetadataSynchronizationTimeout); + object historianID = command.ExecuteScalar("SELECT HistorianID FROM Device WHERE ID = {0}", parentID, MetadataSynchronizationTimeout); // Ascertain total number of actions required for all metadata synchronization so some level feed back can be provided on progress initSyncProgress(metadata.Tables.Cast().Sum(dataTable => (long)dataTable.Rows.Count) + 3); diff --git a/Source/Libraries/Adapters/MySqlAdapters/MySqlOutputAdapter.cs b/Source/Libraries/Adapters/MySqlAdapters/MySqlOutputAdapter.cs index 8aa9b784f33..aa6acc166fa 100755 --- a/Source/Libraries/Adapters/MySqlAdapters/MySqlOutputAdapter.cs +++ b/Source/Libraries/Adapters/MySqlAdapters/MySqlOutputAdapter.cs @@ -176,17 +176,12 @@ protected override void ProcessMeasurements(IMeasurement[] measurements) foreach (IMeasurement measurement in measurements) { // Create the command string to insert the measurement as a record in the table. - StringBuilder commandString = new StringBuilder("INSERT INTO Measurement VALUES ('"); IDbCommand command = m_connection.CreateCommand(); + command.Parameters.Add(measurement.ID); + command.Parameters.Add((long)measurement.Timestamp); + command.Parameters.Add(measurement.AdjustedValue); - commandString.Append(measurement.ID); - commandString.Append("','"); - commandString.Append((long)measurement.Timestamp); - commandString.Append("',"); - commandString.Append(measurement.AdjustedValue); - commandString.Append(')'); - - command.CommandText = commandString.ToString(); + command.CommandText = "INSERT INTO Measurement VALUES ({0}, {1}, {2})"; command.ExecuteNonQuery(); } diff --git a/Source/Libraries/Adapters/PIAdapters/PIOutputAdapter.cs b/Source/Libraries/Adapters/PIAdapters/PIOutputAdapter.cs index 7be4ed87386..1d1fff1a927 100755 --- a/Source/Libraries/Adapters/PIAdapters/PIOutputAdapter.cs +++ b/Source/Libraries/Adapters/PIAdapters/PIOutputAdapter.cs @@ -2475,7 +2475,7 @@ protected override void ExecuteMetadataRefresh() { // Attempt to look up last update time for record database ??= new AdoDataConnection("systemSettings"); - updateTime = Convert.ToDateTime(database.Connection.ExecuteScalar($"SELECT UpdatedOn FROM Measurement WHERE SignalID = '{signalID}'")); + updateTime = Convert.ToDateTime(database.Connection.ExecuteScalar("SELECT UpdatedOn FROM Measurement WHERE SignalID = '{0}'", signalID)); } } catch diff --git a/Source/Libraries/Adapters/PhasorProtocolAdapters/CommonPhasorServices.cs b/Source/Libraries/Adapters/PhasorProtocolAdapters/CommonPhasorServices.cs index e4a9e1237c5..c81c40ec271 100755 --- a/Source/Libraries/Adapters/PhasorProtocolAdapters/CommonPhasorServices.cs +++ b/Source/Libraries/Adapters/PhasorProtocolAdapters/CommonPhasorServices.cs @@ -1112,7 +1112,7 @@ private static void MeasurementDeviceAssociation(AdoDataConnection connection, s } // Make sure device acronym exists - if (connection.ExecuteScalar($"SELECT COUNT(*) FROM Device WHERE NodeID={nodeIDQueryString} AND Acronym={{0}}", deviceAcronym) == 0) + if (connection.ExecuteScalar("SELECT COUNT(*) FROM Device WHERE NodeID={0} AND Acronym={1}", nodeIDQueryString, deviceAcronym) == 0) { // Lookup virtual device protocol if (connection.ExecuteScalar("SELECT COUNT(*) FROM Protocol WHERE Acronym='VirtualInput'") == 0) @@ -1132,10 +1132,10 @@ private static void MeasurementDeviceAssociation(AdoDataConnection connection, s statusMessage($"Validating \"{deviceAcronym}\" virtual device measurement associations..."); // Get device ID - int deviceID = connection.ExecuteScalar($"SELECT ID FROM Device WHERE NodeID={nodeIDQueryString} AND Acronym={{0}}", deviceAcronym); + int deviceID = connection.ExecuteScalar("SELECT ID FROM Device WHERE NodeID={0} AND Acronym={1}", nodeIDQueryString, deviceAcronym); // Get measurements that should be associated with device ID but are not currently - IEnumerable measurements = connection.RetrieveData($"SELECT PointID FROM Measurement WHERE ({lookupExpression}) AND (DeviceID IS NULL OR DeviceID <> {{0}})", deviceID).AsEnumerable(); + IEnumerable measurements = connection.RetrieveData("SELECT PointID FROM Measurement WHERE ({0}) AND (DeviceID IS NULL OR DeviceID <> {{1}})", lookupExpression, deviceID).AsEnumerable(); int associatedMeasurements = 0; @@ -1296,7 +1296,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin statusMessage("Verifying statistics archive exists..."); // Validate that the statistics historian exists - if (Convert.ToInt32(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM Historian WHERE Acronym='STAT' AND NodeID={nodeIDQueryString}")) == 0) + if (Convert.ToInt32(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM Historian WHERE Acronym='STAT' AND NodeID={0}", nodeIDQueryString)) == 0) database.Connection.ExecuteNonQuery($"INSERT INTO Historian(NodeID, Acronym, Name, AssemblyName, TypeName, ConnectionString, IsLocal, Description, LoadOrder, Enabled) VALUES({nodeIDQueryString}, 'STAT', 'Statistics Archive', 'HistorianAdapters.dll', 'HistorianAdapters.LocalOutputAdapter', '', 1, 'Local historian used to archive system statistics', 9999, 1)"); // Make sure statistics path exists to hold historian files @@ -1351,7 +1351,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin configFile.Save(); // Get the needed statistic related IDs - int statHistorianID = Convert.ToInt32(database.Connection.ExecuteScalar($"SELECT ID FROM Historian WHERE Acronym='STAT' AND NodeID={nodeIDQueryString}")); + int statHistorianID = Convert.ToInt32(database.Connection.ExecuteScalar("SELECT ID FROM Historian WHERE Acronym='STAT' AND NodeID={0}, nodeIDQueryString")); // Load the defined system statistics IEnumerable statistics = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Statistic ORDER BY Source, SignalIndex").AsEnumerable(); @@ -1457,7 +1457,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin // Determine how many changes were made to devices and measurements - // if no changes were made, we can skip the next few steps if (trackedTables.Contains("Device") && trackedTables.Contains("Measurement")) - changes = Convert.ToUInt64(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM TrackedChange WHERE (TableName = 'Device' OR TableName = 'Measurement') AND ID > {trackingVersion}")); + changes = Convert.ToUInt64(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM TrackedChange WHERE (TableName = 'Device' OR TableName = 'Measurement') AND ID > {0}", nodeIDQueryString)); else changes = ulong.MaxValue; } @@ -1487,7 +1487,8 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin int qualityFlagsSignalTypeID = Convert.ToInt32(database.Connection.ExecuteScalar("SELECT ID FROM SignalType WHERE Acronym='QUAL'")); // Make sure one device quality flags measurement exists for each "connection" for devices that support time quality flags - foreach (DataRow device in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM Device WHERE ((IsConcentrator = 0 AND ParentID IS NULL) OR IsConcentrator = 1) AND NodeID = {nodeIDQueryString} AND ProtocolID IN ({timeQualityProtocolIDs})").Rows) + foreach (DataRow device in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Device WHERE ((IsConcentrator = 0 AND ParentID IS NULL) " + + "OR IsConcentrator = 1) AND NodeID = {0} AND ProtocolID IN ({1})", nodeIDQueryString, timeQualityProtocolIDs).Rows) { Dictionary connectionSettings = device.Field("ConnectionString")?.ParseKeyValuePairs(); @@ -1500,11 +1501,11 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin signalReference = SignalReference.ToString(acronym, SignalKind.Quality); // See if quality flags measurement exists for device - if (Convert.ToInt32(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM Measurement WHERE SignalReference = '{signalReference}' AND DeviceID = {deviceID}")) == 0) + if (Convert.ToInt32(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM Measurement WHERE SignalReference = '{0}' AND DeviceID = {1}", signalReference, deviceID)) == 0) { historianID = device.ConvertNullableField("HistorianID"); - company = (string)database.Connection.ExecuteScalar($"SELECT MapAcronym FROM Company WHERE ID = {device.ConvertNullableField("CompanyID") ?? 0}"); + company = (string)database.Connection.ExecuteScalar("SELECT MapAcronym FROM Company WHERE ID = {0}", device.ConvertNullableField("CompanyID") ?? 0); if (string.IsNullOrEmpty(company)) company = configFile.Settings["systemSettings"]["CompanyAcronym"].Value.TruncateRight(3); @@ -1521,7 +1522,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin } // Make sure needed device statistic measurements exist, currently statistics are only associated with phasor devices so we filter based on protocol - foreach (DataRow device in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM Device WHERE IsConcentrator = 0 AND NodeID = {nodeIDQueryString} AND ProtocolID IN ({protocolIDs})").Rows) + foreach (DataRow device in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Device WHERE IsConcentrator = 0 AND NodeID = {0} AND ProtocolID IN ({1})", nodeIDQueryString, protocolIDs).Rows) { foreach (DataRow statistic in deviceStatistics) { @@ -1530,9 +1531,8 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin acronym = oldAcronym + "!PMU"; string oldSignalReference = SignalReference.ToString(oldAcronym, SignalKind.Statistic, signalIndex); signalReference = SignalReference.ToString(acronym, SignalKind.Statistic, signalIndex); - // If the original format for device statistics is found in the database, update to new format - if (Convert.ToInt32(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM Measurement WHERE SignalReference='{oldSignalReference}' AND HistorianID={statHistorianID}")) > 0) + if (Convert.ToInt32(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM Measurement WHERE SignalReference='{0}' AND HistorianID={1}", oldSignalReference, statHistorianID)) > 0) database.Connection.ExecuteNonQuery($"UPDATE Measurement SET SignalReference='{signalReference}' WHERE SignalReference='{oldSignalReference}' AND HistorianID={statHistorianID}"); else if (!skipOptimization) break; @@ -1543,7 +1543,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin // Make sure devices associated with a concentrator do not have any extraneous input stream statistic measurements - this can happen // when a device was once a direct connect device but now is part of a concentrator... - foreach (DataRow inputStream in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM Device WHERE (IsConcentrator = 0 AND ParentID IS NOT NULL) AND NodeID = {nodeIDQueryString} AND ProtocolID IN ({protocolIDs})").Rows) + foreach (DataRow inputStream in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Device WHERE (IsConcentrator = 0 AND ParentID IS NOT NULL) AND NodeID = {0} AND ProtocolID IN ({1})", nodeIDQueryString, protocolIDs).Rows) { firstStatisticExisted = false; @@ -1556,7 +1556,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin // To reduce time required to execute these steps, only first statistic is verified to exist if (!skipOptimization && !firstStatisticExisted) { - firstStatisticExisted = Convert.ToInt32(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM Measurement WHERE SignalReference='{signalReference}'")) > 0; + firstStatisticExisted = Convert.ToInt32(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM Measurement WHERE SignalReference='{0}'", signalReference)) > 0; // If the first extraneous input statistic doesn't exist, we assume no others do as well if (!firstStatisticExisted) @@ -1574,7 +1574,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin // Determine how many changes were made to output streams, devices, and measurements - // if no changes were made, we can skip the next few steps if (trackedTables.Contains("OutputStream") && trackedTables.Contains("OutputStreamDevice") && trackedTables.Contains("OutputStreamMeasurement") && trackedTables.Contains("Measurement")) - changes = Convert.ToUInt64(database.Connection.ExecuteScalar($"SELECT COUNT(*) FROM TrackedChange WHERE (TableName = 'OutputStream' OR TableName = 'OutputStreamDevice' OR TableName = 'OutputStreamMeasurement' OR TableName = 'Measurement') AND ID > {trackingVersion}")); + changes = Convert.ToUInt64(database.Connection.ExecuteScalar("SELECT COUNT(*) FROM TrackedChange WHERE (TableName = 'OutputStream' OR TableName = 'OutputStreamDevice' OR TableName = 'OutputStreamMeasurement' OR TableName = 'Measurement') AND ID > {0}", trackingVersion)); else changes = ulong.MaxValue; } @@ -1588,14 +1588,14 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin statusMessage("Validating output stream measurements..."); // Make sure needed output stream statistic measurements exist - foreach (DataRow outputStream in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM OutputStream WHERE NodeID = {nodeIDQueryString}").Rows) + foreach (DataRow outputStream in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStream WHERE NodeID = {0}", nodeIDQueryString).Rows) { adapterID = outputStream.ConvertField("ID"); // Load devices acronyms associated with this output stream List deviceAcronyms = database.Connection.RetrieveData(database.AdapterType, - $"SELECT Acronym FROM OutputStreamDevice WHERE AdapterID = {adapterID} AND NodeID = {nodeIDQueryString}") + "SELECT Acronym FROM OutputStreamDevice WHERE AdapterID = {0} AND NodeID = {1}", adapterID, nodeIDQueryString) .AsEnumerable() .Select(row => row.Field("Acronym")) .ToList(); @@ -1607,7 +1607,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin deviceAcronyms.Sort(StringComparer.OrdinalIgnoreCase); // Validate measurements associated with this output stream - foreach (DataRow outputStreamMeasurement in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM OutputStreamMeasurement WHERE AdapterID = {adapterID} AND NodeID = {nodeIDQueryString}").Rows) + foreach (DataRow outputStreamMeasurement in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStreamMeasurement WHERE AdapterID = {0} AND NodeID = {1}", adapterID, nodeIDQueryString).Rows) { // Parse output stream measurement signal reference deviceSignalReference = new SignalReference(outputStreamMeasurement.Field("SignalReference")); @@ -1656,7 +1656,7 @@ private static void PhasorDataSourceValidation(AdoDataConnection database, strin continue; int? vendorDeviceID = measurement.ConvertNullableField("VendorDeviceID"); - string vendor = vendorDeviceID.HasValue ? (string)database.Connection.ExecuteScalar("SELECT Acronym FROM Vendor WHERE ID = " + vendorDeviceID.Value) : null; + string vendor = vendorDeviceID.HasValue ? (string)database.Connection.ExecuteScalar("SELECT Acronym FROM Vendor WHERE ID = {0}", vendorDeviceID.Value) : null; string signalAcronym = measurement.ConvertField("SignalAcronym"); try diff --git a/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerCalculationConfigurationValidation.cs b/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerCalculationConfigurationValidation.cs index 3da88cd47d6..ed4abced1a6 100644 --- a/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerCalculationConfigurationValidation.cs +++ b/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerCalculationConfigurationValidation.cs @@ -56,7 +56,7 @@ public static void ValidateDatabaseDefinitions() /// Database connection to use for checking the data operation /// True or false indicating whether the operation exists private static bool DataOperationExists(AdoDataConnection database) => - Convert.ToInt32(database.ExecuteScalar($"SELECT COUNT(*) FROM DataOperation WHERE TypeName='{typeof(PowerCalculationConfigurationValidation).FullName}' AND MethodName='ValidatePowerCalculationConfigurations'")) > 0; + Convert.ToInt32(database.ExecuteScalar("SELECT COUNT(*) FROM DataOperation WHERE TypeName='{0}' AND MethodName='ValidatePowerCalculationConfigurations'", typeof(PowerCalculationConfigurationValidation).FullName)) > 0; /// /// Creates a data operation to run the validations in this class. @@ -71,7 +71,7 @@ private static void CreateDataOperation(AdoDataConnection database) => /// Database connection to use for checking the data operation /// True or false indicating whether the operation exists private static bool AdapterInstanceExists(AdoDataConnection database) => - Convert.ToInt32(database.ExecuteScalar($"SELECT COUNT(*) FROM CustomActionAdapter WHERE TypeName='{typeof(PowerMultiCalculatorAdapter).FullName}'")) > 0; + Convert.ToInt32(database.ExecuteScalar("SELECT COUNT(*) FROM CustomActionAdapter WHERE TypeName='{0}'", typeof(PowerMultiCalculatorAdapter).FullName)) > 0; /// /// Creates a data operation to run the validations in this class. diff --git a/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerMultiCalculatorAdapter.cs b/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerMultiCalculatorAdapter.cs index 0c7b9d7552c..9e46b673225 100644 --- a/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerMultiCalculatorAdapter.cs +++ b/Source/Libraries/Adapters/PowerCalculations/PowerMultiCalculator/PowerMultiCalculatorAdapter.cs @@ -269,14 +269,14 @@ public override void Initialize() if (Settings.TryGetValue(nameof(TableName), out string tableName)) TableName = tableName; - // 0 1 2 3 4 5 - string query = "SELECT ID, CircuitDescription, VoltageAngleSignalID, VoltageMagSignalID, CurrentAngleSignalID, CurrentMagSignalID, " + - // 6 7 8 - "ActivePowerOutputSignalID, ReactivePowerOutputSignalID, ApparentPowerOutputSignalID " + - $"FROM {TableName} WHERE NodeId = {{0}} AND Enabled <> 0"; - using (AdoDataConnection database = new("systemSettings")) - using (IDataReader reader = database.ExecuteReader(query, ConfigurationFile.Current.Settings["systemSettings"]["NodeID"].ValueAs())) + using (IDataReader reader = database.ExecuteReader( + // 0 1 2 3 4 5 + "SELECT ID, CircuitDescription, VoltageAngleSignalID, VoltageMagSignalID, CurrentAngleSignalID, CurrentMagSignalID, " + + // 6 7 8 + "ActivePowerOutputSignalID, ReactivePowerOutputSignalID, ApparentPowerOutputSignalID " + + "FROM {0} WHERE NodeId = {1} AND Enabled <> 0", + TableName, ConfigurationFile.Current.Settings["systemSettings"]["NodeID"].ValueAs())) { while (reader.Read()) { diff --git a/Source/Libraries/GSF.Core/Data/DataDeleter.cs b/Source/Libraries/GSF.Core/Data/DataDeleter.cs index 5cd76211560..87d992bce4f 100644 --- a/Source/Libraries/GSF.Core/Data/DataDeleter.cs +++ b/Source/Libraries/GSF.Core/Data/DataDeleter.cs @@ -232,7 +232,9 @@ private void ExecuteDeletes(Table fromTable, Table toTable) OnOverallProgress((int)m_overallProgress, (int)m_overallTotal); // Execute source query - using (IDataReader fromReader = fromTable.Connection.ExecuteReader("SELECT " + fieldCollection.GetList(sqlEscapeFunction: fromTable.Parent.Parent.SQLEscapeName) + " FROM " + fromTable.SQLEscapedName, CommandBehavior.SequentialAccess, Timeout)) + using (IDataReader fromReader = fromTable.Connection.ExecuteReader("SELECT {0} FROM {1}", + fieldCollection.GetList(sqlEscapeFunction: fromTable.Parent.Parent.SQLEscapeName), fromTable.SQLEscapedName, + CommandBehavior.SequentialAccess, Timeout)) { // Create Sql delete stub deleteSQLStub = "DELETE FROM " + toTable.SQLEscapedName; diff --git a/Source/Libraries/GSF.Core/Data/DataInserter.cs b/Source/Libraries/GSF.Core/Data/DataInserter.cs index 2b41a2f80c2..6e607631b14 100644 --- a/Source/Libraries/GSF.Core/Data/DataInserter.cs +++ b/Source/Libraries/GSF.Core/Data/DataInserter.cs @@ -822,7 +822,7 @@ private void InsertDestinationRecord(Table toTable, Fields fieldCollection, stri // Added check to preserve ID number for auto-inc fields if (!usingIdentityInsert && !skipKeyValuePreservation && m_preserveAutoIncValues && (object)autoIncField != null) { - int toTableRowCount = int.Parse(Common.ToNonNullString(toTable.Connection.ExecuteScalar("SELECT MAX(" + autoIncField.SQLEscapedName + ") FROM " + toTable.SQLEscapedName, Timeout), "0")) + 1; + int toTableRowCount = int.Parse(Common.ToNonNullString(toTable.Connection.ExecuteScalar("SELECT MAX({0}) FROM {1}", autoIncField.SQLEscapedName, toTable.SQLEscapedName, Timeout), "0")) + 1; int sourceTablePrimaryFieldValue = int.Parse(Common.ToNonNullString(autoIncField.Value, "0")); int synchronizations = 0; @@ -884,7 +884,7 @@ private void InsertOrUpdate(Table toTable, StringBuilder insertSQL, StringBuilde try { // If record already exists due to triggers or other means we must update it instead of inserting it - if (int.Parse(Common.ToNonNullString(toTable.Connection.ExecuteScalar(countSQL.ToString(), Timeout), "0")) > 0) + if (int.Parse(Common.ToNonNullString(toTable.Connection.ExecuteScalar("{0}", countSQL.ToString(), Timeout), "0")) > 0) { // Add where criteria to SQL update statement updateSQL.Append(whereSQL); diff --git a/Source/Libraries/GSF.Core/Data/DataUpdater.cs b/Source/Libraries/GSF.Core/Data/DataUpdater.cs index e4e38df6119..37f2e74ae37 100644 --- a/Source/Libraries/GSF.Core/Data/DataUpdater.cs +++ b/Source/Libraries/GSF.Core/Data/DataUpdater.cs @@ -233,7 +233,9 @@ private void ExecuteUpdates(Table fromTable, Table toTable) OnOverallProgress((int)m_overallProgress, (int)m_overallTotal); // Execute source query - using (IDataReader fromReader = fromTable.Connection.ExecuteReader("SELECT " + fieldsCollection.GetList(sqlEscapeFunction: fromTable.Parent.Parent.SQLEscapeName) + " FROM " + fromTable.SQLEscapedName, CommandBehavior.SequentialAccess, Timeout)) + using (IDataReader fromReader = fromTable.Connection.ExecuteReader("SELECT {0} FROM {1}", + fieldsCollection.GetList(sqlEscapeFunction: fromTable.Parent.Parent.SQLEscapeName), + fromTable.SQLEscapedName, CommandBehavior.SequentialAccess, Timeout)) { // Create Sql update stub updateSQLStub = "UPDATE " + toTable.SQLEscapedName + " SET "; diff --git a/Source/Libraries/GSF.Core/Data/Schema.cs b/Source/Libraries/GSF.Core/Data/Schema.cs index 7efee07a5f9..b0a088d1afa 100644 --- a/Source/Libraries/GSF.Core/Data/Schema.cs +++ b/Source/Libraries/GSF.Core/Data/Schema.cs @@ -2780,30 +2780,33 @@ public void Analyze() try { // Make sure table exists - m_schemaConnection.ExecuteScalar("SELECT COUNT(*) FROM " + table.SQLEscapedName); + m_schemaConnection.ExecuteScalar("SELECT COUNT(*) FROM {0}", table.SQLEscapedName); List fieldsToRemove = new List(); string testFieldSQL; + string sqlEscapedName = table.SQLEscapedName; + string sqlAutoIncEscapedName = table.AutoIncField.SQLEscapedName; try { // If table has an auto-inc field, this will typically be indexed and will allow for a faster field check than a count if (table.HasAutoIncField) - testFieldSQL = "SELECT {0} FROM " + table.SQLEscapedName + " WHERE " + table.AutoIncField.SQLEscapedName + " < 0"; + testFieldSQL = "SELECT {0} FROM " + sqlEscapedName + " WHERE " + sqlAutoIncEscapedName + " < 0"; else - testFieldSQL = "SELECT COUNT({0}) FROM " + table.SQLEscapedName; + testFieldSQL = "SELECT COUNT({0}) FROM " + sqlEscapedName; } catch { - testFieldSQL = "SELECT COUNT({0}) FROM " + table.SQLEscapedName; + testFieldSQL = "SELECT COUNT({0}) FROM " + sqlEscapedName; } foreach (Field field in table.Fields) { try { + string fieldEscapedName = field.SQLEscapedName; // Make sure field exists - m_schemaConnection.ExecuteScalar(string.Format(testFieldSQL, field.SQLEscapedName)); + m_schemaConnection.ExecuteScalar(string.Format(testFieldSQL, fieldEscapedName)); } catch { diff --git a/Source/Libraries/GSF.Core/ErrorManagement/ErrorLogger.cs b/Source/Libraries/GSF.Core/ErrorManagement/ErrorLogger.cs index 157c435e4ec..2282f4d4399 100644 --- a/Source/Libraries/GSF.Core/ErrorManagement/ErrorLogger.cs +++ b/Source/Libraries/GSF.Core/ErrorManagement/ErrorLogger.cs @@ -1544,8 +1544,8 @@ private void m_tableSizeCurtailmentTimer_Elapsed(object sender, System.Timers.El command.Transaction = transaction; // Get min and max IDs from error log - int minID = Convert.ToInt32(command.ExecuteScalar(string.Format("SELECT MIN(ID) FROM ErrorLog"))); - int maxID = Convert.ToInt32(command.ExecuteScalar(string.Format("SELECT MAX(ID) FROM ErrorLog"))); + int minID = Convert.ToInt32(command.ExecuteScalar("SELECT MIN(ID) FROM ErrorLog")); + int maxID = Convert.ToInt32(command.ExecuteScalar("SELECT MAX(ID) FROM ErrorLog")); int errorLogSize = maxID - minID; // Roughly, assuming no manual deletions // When exception log is larger than desired size - delete roughly 25% of the records, diff --git a/Source/Libraries/GSF.Historian/MetadataProviders/AdoMetadataProvider.cs b/Source/Libraries/GSF.Historian/MetadataProviders/AdoMetadataProvider.cs index 82d17d002fd..7ad20090bb3 100755 --- a/Source/Libraries/GSF.Historian/MetadataProviders/AdoMetadataProvider.cs +++ b/Source/Libraries/GSF.Historian/MetadataProviders/AdoMetadataProvider.cs @@ -252,7 +252,7 @@ protected override void RefreshMetadata() // Update existing metadata MetadataUpdater metadataUpdater = new MetadataUpdater(Metadata); - metadataUpdater.UpdateMetadata(connection.ExecuteReader(m_selectString)); + metadataUpdater.UpdateMetadata(connection.ExecuteReader("{0}", m_selectString)); } finally { diff --git a/Source/Libraries/GSF.Historian/MetadataProviders/OleDbMetadataProvider.cs b/Source/Libraries/GSF.Historian/MetadataProviders/OleDbMetadataProvider.cs index b7a0ab580ab..2e61cf6cb9a 100755 --- a/Source/Libraries/GSF.Historian/MetadataProviders/OleDbMetadataProvider.cs +++ b/Source/Libraries/GSF.Historian/MetadataProviders/OleDbMetadataProvider.cs @@ -157,7 +157,7 @@ protected override void RefreshMetadata() // Update existing metadata. MetadataUpdater metadataUpdater = new MetadataUpdater(Metadata); - metadataUpdater.UpdateMetadata(connection.ExecuteReader(m_selectString)); + metadataUpdater.UpdateMetadata(connection.ExecuteReader("{0}", m_selectString)); } finally { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/CalculatedMeasurement.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/CalculatedMeasurement.cs index 401ec96a778..d3f0f959c17 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/CalculatedMeasurement.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/CalculatedMeasurement.cs @@ -490,7 +490,7 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember if (!string.IsNullOrEmpty(sortMember)) sortClause = $"ORDER BY {sortMember} {sortDirection}"; - DataTable calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID From CalculatedMeasurementDetail {sortClause}"); + DataTable calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From CalculatedMeasurementDetail {0}", sortClause); foreach (DataRow row in calculatedMeasurementTable.Rows) { @@ -531,12 +531,11 @@ public static ObservableCollection Load(AdoDataConnection { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => $"{str1},{str2}"); - query = string.Format("SELECT NodeID, ID, Acronym, Name, AssemblyName, " + + query = database.ParameterizedQueryString("SELECT NodeID, ID, Acronym, Name, AssemblyName, " + "TypeName, ConnectionString, ConfigSection, InputMeasurements, OutputMeasurements, MinimumMeasurementsToUse, FramesPerSecond, LagTime, " + "LeadTime, UseLocalClockAsRealTime, AllowSortsByArrival, LoadOrder, Enabled, IgnoreBadTimeStamps, TimeResolution, AllowPreemptivePublishing, " + - "DownSamplingMethod, NodeName, PerformTimeReasonabilityCheck From CalculatedMeasurementDetail WHERE ID IN ({0}) AND NodeID = '{1}'", commaSeparatedKeys, database.CurrentNodeID()); - - calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, query); + "DownSamplingMethod, NodeName, PerformTimeReasonabilityCheck From CalculatedMeasurementDetail WHERE ID IN ({0}) AND NodeID = '{1}'", "commaSeparatedKeys", "database.CurrentNodeID()"); + calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, query, commaSeparatedKeys, database.CurrentNodeID()); calculatedMeasurementList = new CalculatedMeasurement[calculatedMeasurementTable.Rows.Count]; foreach (DataRow row in calculatedMeasurementTable.Rows) diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Device.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Device.cs index bb42125cb69..cdafba30a7b 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Device.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Device.cs @@ -817,36 +817,36 @@ public static IList LoadKeys(AdoDataConnection database, int parentID = 0, { if (string.IsNullOrEmpty(searchText)) { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} AND ParentID = {{1}} {sortClause}", "nodeID", "parentID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} AND ParentID = {1} {2}", "nodeID", "parentID", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID, sortClause); } else if (!database.IsJetEngine) { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} AND ParentID = {{1}} AND ({searchText}) {sortClause}", "nodeID", "parentID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID, searchParam); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} AND ParentID = {1} AND ({2}) {3}", "nodeID", "parentID", "searchText", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID, searchParam, searchText, sortClause); } else { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} AND ParentID = {{1}} AND ({searchText}) {sortClause}", "nodeID", "parentID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} AND ParentID = {1} AND ({2}) {3}", "nodeID", "parentID", "searchText", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), parentID, searchText, sortClause); } } else { if (string.IsNullOrEmpty(searchText)) { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} {sortClause}", "nodeID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} {1}", "nodeID", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), sortClause); } else if (!database.IsJetEngine) { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} AND ({searchQuery}) {sortClause}", "nodeID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), searchParam); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} AND ({1}) {2}", "nodeID", "searchQuery", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), searchParam, searchQuery, sortClause); } else { - query = database.ParameterizedQueryString($"SELECT ID From DeviceDetail WHERE NodeID = {{0}} AND ({searchQuery}) {sortClause}", "nodeID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + query = database.ParameterizedQueryString("SELECT ID From DeviceDetail WHERE NodeID = {0} AND ({1}) {2}", "nodeID", "searchQuery", "sortClause"); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), searchQuery, sortClause); } } @@ -881,8 +881,8 @@ public static ObservableCollection Load(AdoDataConnection database, ILis if (keys is not null && keys.Count > 0) { string commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => $"{str1},{str2}"); - string query = $"SELECT * FROM DeviceDetail WHERE ID IN ({commaSeparatedKeys})"; - DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + string query = database.ParameterizedQueryString("SELECT * FROM DeviceDetail WHERE ID IN ({0})", "commaSeparatedKeys"); + DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, commaSeparatedKeys); deviceList = new Device[deviceTable.Rows.Count]; foreach (DataRow row in deviceTable.Rows) @@ -1452,7 +1452,7 @@ public static Device GetDevice(AdoDataConnection database, string whereClause) try { createdConnection = CreateConnection(ref database); - DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM DeviceDetail {whereClause}"); + DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM DeviceDetail {0}", whereClause); if (deviceTable.Rows.Count == 0) return null; @@ -1537,7 +1537,7 @@ public static ObservableCollection GetDevices(AdoDataConnection database try { createdConnection = CreateConnection(ref database); - DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM DeviceDetail {whereClause}"); + DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM DeviceDetail {0}", whereClause); ObservableCollection deviceList = new(); if (deviceTable.Rows.Count == 0) @@ -1696,9 +1696,10 @@ public static ObservableCollection GetNewDevicesForOutputStream(AdoDataC // Note that OleDB does not support parameterized sub-query. if (database.DatabaseType == DatabaseType.Access) { - query = database.ParameterizedQueryString($"SELECT * FROM DeviceDetail WHERE NodeID = {{0}} AND IsConcentrator = {{1}} AND Acronym NOT IN (SELECT Acronym FROM OutputStreamDevice WHERE AdapterID = {outputStreamID}) ORDER BY Acronym", "nodeID", "isConcentrator"); + query = database.ParameterizedQueryString("SELECT * FROM DeviceDetail WHERE NodeID = {0} AND IsConcentrator = {1} " + + "AND Acronym NOT IN (SELECT Acronym FROM OutputStreamDevice WHERE AdapterID = {2}) ORDER BY Acronym", "nodeID", "isConcentrator", "outputStreamID"); - deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), database.Bool(false)); + deviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID(), database.Bool(false), outputStreamID); } else { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStream.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStream.cs index f712fd15928..ba082841e44 100644 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStream.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStream.cs @@ -829,13 +829,13 @@ public static IList LoadKeys(AdoDataConnection database, bool enabledOnly, if (enabledOnly) { - query = database.ParameterizedQueryString($"SELECT ID FROM OutputStreamDetail WHERE NodeID = {{0}} AND Enabled = {{1}} {sortClause}", "nodeID", "enabled"); - outputStreamTable = database.Connection.RetrieveData(database.AdapterType, query, database.CurrentNodeID(), database.Bool(true)); + query = database.ParameterizedQueryString("SELECT ID FROM OutputStreamDetail WHERE NodeID = {0} AND Enabled = {1} {2}", "nodeID", "enabled", "sortClause"); + outputStreamTable = database.Connection.RetrieveData(database.AdapterType, query, database.CurrentNodeID(), database.Bool(true), sortClause); } else { - query = database.ParameterizedQueryString($"SELECT * FROM OutputStreamDetail WHERE NodeID = {{0}} {sortClause}", "nodeID"); - outputStreamTable = database.Connection.RetrieveData(database.AdapterType, query, database.CurrentNodeID()); + query = database.ParameterizedQueryString("SELECT * FROM OutputStreamDetail WHERE NodeID = {0} {1}", "nodeID", "sortClause"); + outputStreamTable = database.Connection.RetrieveData(database.AdapterType, query, database.CurrentNodeID(), sortClause); } foreach (DataRow row in outputStreamTable.Rows) @@ -871,8 +871,7 @@ public static ObservableCollection Load(AdoDataConnection database if (keys is not null && keys.Count > 0) { string commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - string query = $"SELECT * FROM OutputStreamDetail WHERE ID IN ({commaSeparatedKeys})"; - DataTable outputStreamTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + DataTable outputStreamTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStreamDetail WHERE ID IN ({0})", DefaultTimeout, commaSeparatedKeys); outputStreamList = new ObservableCollection( from item in outputStreamTable.AsEnumerable() @@ -1041,7 +1040,7 @@ public static string Save(AdoDataConnection database, OutputStream outputStream, if (qualityType is not null) { - IList keys = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID FROM OutputStreamMeasurement WHERE AdapterID = {outputStream.ID}") + IList keys = database.Connection.RetrieveData(database.AdapterType, "SELECT ID FROM OutputStreamMeasurement WHERE AdapterID = {0}", outputStream.ID) .Select().Select(row => row.ConvertField("ID")).ToList(); foreach (OutputStreamMeasurement measurement in OutputStreamMeasurement.Load(database, keys)) @@ -1165,7 +1164,7 @@ public static OutputStream GetOutputStream(AdoDataConnection database, string wh try { createdConnection = CreateConnection(ref database); - DataTable outputStreamTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM OutputStreamDetail {whereClause}"); + DataTable outputStreamTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStreamDetail {0}", whereClause); if (outputStreamTable.Rows.Count == 0) return null; diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevice.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevice.cs index 17afc563b53..2df2d7522c6 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevice.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevice.cs @@ -359,12 +359,12 @@ public static ObservableCollection Load(AdoDataConnection da { string commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => $"{str1},{str2}"); - string query = $"SELECT NodeID, AdapterID, ID, IDCode, Acronym, BpaAcronym, Name, PhasorDataFormat, FrequencyDataFormat, AnalogDataFormat, CoordinateFormat, LoadOrder, Enabled, Virtual FROM OutputStreamDeviceDetail WHERE ID IN ({commaSeparatedKeys})"; + string query = "SELECT NodeID, AdapterID, ID, IDCode, Acronym, BpaAcronym, Name, PhasorDataFormat, FrequencyDataFormat, AnalogDataFormat, CoordinateFormat, LoadOrder, Enabled, Virtual FROM OutputStreamDeviceDetail WHERE ID IN ({0})"; if (database.IsMySQL) - query = $"SELECT NodeID, AdapterID, ID, IDCode, Acronym, BpaAcronym, Name, PhasorDataFormat, FrequencyDataFormat, AnalogDataFormat, CoordinateFormat, LoadOrder, Enabled, `Virtual` FROM OutputStreamDeviceDetail WHERE ID IN ({commaSeparatedKeys})"; + query = "SELECT NodeID, AdapterID, ID, IDCode, Acronym, BpaAcronym, Name, PhasorDataFormat, FrequencyDataFormat, AnalogDataFormat, CoordinateFormat, LoadOrder, Enabled, `Virtual` FROM OutputStreamDeviceDetail WHERE ID IN ({0})"; - DataTable outputStreamDeviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + DataTable outputStreamDeviceTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, commaSeparatedKeys); outputStreamDeviceList = new OutputStreamDevice[outputStreamDeviceTable.Rows.Count]; foreach (DataRow row in outputStreamDeviceTable.Rows) @@ -698,7 +698,7 @@ public static OutputStreamDevice GetOutputStreamDevice(AdoDataConnection databas try { createdConnection = CreateConnection(ref database); - DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM OutputStreamDeviceDetail {whereClause}"); + DataTable deviceTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStreamDeviceDetail {0}", whereClause); if (deviceTable.Rows.Count == 0) return null; @@ -748,7 +748,7 @@ public static ObservableCollection GetOutputStreamDevices(Ad createdConnection = CreateConnection(ref database); ObservableCollection outputStreamDeviceList = new(); - DataTable outputStreamDeviceTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM OutputStreamDeviceDetail {whereClause}"); + DataTable outputStreamDeviceTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM OutputStreamDeviceDetail {0}", whereClause); foreach (DataRow row in outputStreamDeviceTable.Rows) { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceAnalog.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceAnalog.cs index 0b45b393303..28d872c4373 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceAnalog.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceAnalog.cs @@ -220,7 +220,7 @@ public static IList LoadKeys(AdoDataConnection database, int outputStreamDe if (!string.IsNullOrEmpty(sortMember)) sortClause = $"ORDER BY {sortMember} {sortDirection}"; - DataTable outputStreamDeviceAnalogTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID FROM OutputStreamDeviceAnalog WHERE OutputStreamDeviceID = {outputStreamDeviceID} {sortClause}"); + DataTable outputStreamDeviceAnalogTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID FROM OutputStreamDeviceAnalog WHERE OutputStreamDeviceID = {0} {1}", outputStreamDeviceID, sortClause); foreach (DataRow row in outputStreamDeviceAnalogTable.Rows) outputStreamDeviceAnalogList.Add((row.ConvertField("ID"))); @@ -253,8 +253,7 @@ public static ObservableCollection Load(AdoDataConnect if (keys is not null && keys.Count > 0) { string commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - string query = database.ParameterizedQueryString($"SELECT NodeID, OutputStreamDeviceID, ID, Label, Type, ScalingValue, LoadOrder FROM OutputStreamDeviceAnalog WHERE ID IN ({commaSeparatedKeys})"); - DataTable outputStreamDeviceAnalogTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + DataTable outputStreamDeviceAnalogTable = database.Connection.RetrieveData(database.AdapterType, "SELECT NodeID, OutputStreamDeviceID, ID, Label, Type, ScalingValue, LoadOrder FROM OutputStreamDeviceAnalog WHERE ID IN ({0})", DefaultTimeout, commaSeparatedKeys); outputStreamDeviceAnalogList = new OutputStreamDeviceAnalog[outputStreamDeviceAnalogTable.Rows.Count]; foreach (DataRow row in outputStreamDeviceAnalogTable.Rows) @@ -502,8 +501,8 @@ private static void GetDeleteMeasurementDetails(AdoDataConnection database, int string deviceName = outputDeviceRecord.Field("Acronym"); adapterID = outputDeviceRecord.ConvertField("AdapterID"); - string analogPointTag = database.Connection.ExecuteScalar(string.Format(measurementDetailFormat, deviceName, labelName)).ToNonNullString(); - analogSignalReference = database.Connection.ExecuteScalar(string.Format(outputMeasurementDetailFormat, analogPointTag)).ToNonNullString(); + string analogPointTag = database.Connection.ExecuteScalar(measurementDetailFormat, deviceName, labelName).ToNonNullString(); + analogSignalReference = database.Connection.ExecuteScalar(outputMeasurementDetailFormat, analogPointTag).ToNonNullString(); } catch (Exception ex) { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceDigital.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceDigital.cs index 632a1798d76..6c97d38d8ce 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceDigital.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDeviceDigital.cs @@ -232,7 +232,7 @@ public static IList LoadKeys(AdoDataConnection database, int outputStreamDe if (!string.IsNullOrEmpty(sortMember)) sortClause = $"ORDER BY {sortMember} {sortDirection}"; - DataTable outputStreamDeviceDigitalTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID From OutputStreamDeviceDigital WHERE OutputStreamDeviceID = {outputStreamDeviceID} {sortClause}"); + DataTable outputStreamDeviceDigitalTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From OutputStreamDeviceDigital WHERE OutputStreamDeviceID = {0} {1}", outputStreamDeviceID, sortClause); foreach (DataRow row in outputStreamDeviceDigitalTable.Rows) { @@ -272,9 +272,10 @@ public static ObservableCollection Load(AdoDataConnec if (keys is not null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - query = database.ParameterizedQueryString($"SELECT NodeID, OutputStreamDeviceID, ID, Label, MaskValue, LoadOrder FROM OutputStreamDeviceDigital WHERE ID IN ({commaSeparatedKeys})"); - outputStreamDeviceDigitalTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + outputStreamDeviceDigitalTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT NodeID, OutputStreamDeviceID, ID, Label, MaskValue, LoadOrder FROM OutputStreamDeviceDigital " + + "WHERE ID IN ({0})", DefaultTimeout, commaSeparatedKeys); outputStreamDeviceDigitalList = new OutputStreamDeviceDigital[outputStreamDeviceDigitalTable.Rows.Count]; foreach (DataRow row in outputStreamDeviceDigitalTable.Rows) @@ -515,8 +516,8 @@ private static void GetDeleteMeasurementDetails(AdoDataConnection database, int string deviceName = outputDeviceRecord.Field("Acronym"); adapterID = outputDeviceRecord.ConvertField("AdapterID"); - string digitalPointTag = database.Connection.ExecuteScalar(string.Format(measurementDetailFormat, deviceName, labelName)).ToNonNullString(); - digitalSignalReference = database.Connection.ExecuteScalar(string.Format(outputMeasurementDetailFormat, digitalPointTag)).ToNonNullString(); + string digitalPointTag = database.Connection.ExecuteScalar(measurementDetailFormat, deviceName, labelName).ToNonNullString(); + digitalSignalReference = database.Connection.ExecuteScalar(outputMeasurementDetailFormat, digitalPointTag).ToNonNullString(); } catch (Exception ex) { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevicePhasor.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevicePhasor.cs index 517759bf983..734219c42d3 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevicePhasor.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamDevicePhasor.cs @@ -243,7 +243,7 @@ public static IList LoadKeys(AdoDataConnection database, int outputStreamDe if (!string.IsNullOrEmpty(sortMember)) sortClause = $"ORDER BY {sortMember} {sortDirection}"; - DataTable OutputStreamDevicePhasorTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID FROM OutputStreamDevicePhasor WHERE OutputStreamDeviceID = {outputStreamDeviceID} {sortClause}"); + DataTable OutputStreamDevicePhasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID FROM OutputStreamDevicePhasor WHERE OutputStreamDeviceID = {0} {1}", outputStreamDeviceID, sortClause); foreach (DataRow row in OutputStreamDevicePhasorTable.Rows) outputStreamDevicePhasorList.Add((row.ConvertField("ID"))); @@ -276,9 +276,8 @@ public static ObservableCollection Load(AdoDataConnect if (keys is not null && keys.Count > 0) { string commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - string query = database.ParameterizedQueryString($"SELECT NodeID, OutputStreamDeviceID, ID, Label, Type, Phase, ScalingValue, LoadOrder FROM OutputStreamDevicePhasor WHERE ID IN ({commaSeparatedKeys})"); - DataTable outputStreamDevicePhasorTable = database.Connection.RetrieveData(database.AdapterType, query); + DataTable outputStreamDevicePhasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT NodeID, OutputStreamDeviceID, ID, Label, Type, Phase, ScalingValue, LoadOrder FROM OutputStreamDevicePhasor WHERE ID IN ({0})", commaSeparatedKeys); outputStreamDevicePhasorList = new OutputStreamDevicePhasor[outputStreamDevicePhasorTable.Rows.Count]; foreach (DataRow row in outputStreamDevicePhasorTable.Rows) @@ -541,11 +540,11 @@ private static void GetDeleteMeasurementDetails(AdoDataConnection database, int string deviceName = outputDeviceRecord.Field("Acronym"); adapterID = outputDeviceRecord.ConvertField("AdapterID"); - string anglePointTag = database.Connection.ExecuteScalar(string.Format(measurementDetailFormat, deviceName, labelName, "PA")).ToNonNullString(); - angleSignalReference = database.Connection.ExecuteScalar(string.Format(outputMeasurementDetailFormat, anglePointTag)).ToNonNullString(); + string anglePointTag = database.Connection.ExecuteScalar(measurementDetailFormat, deviceName, labelName, "PA").ToNonNullString(); + angleSignalReference = database.Connection.ExecuteScalar(outputMeasurementDetailFormat, anglePointTag).ToNonNullString(); - string magnitudePointTag = database.Connection.ExecuteScalar(string.Format(measurementDetailFormat, deviceName, labelName, "PM")).ToNonNullString(); - magnitudeSignalReference = database.Connection.ExecuteScalar(string.Format(outputMeasurementDetailFormat, magnitudePointTag)).ToNonNullString(); + string magnitudePointTag = database.Connection.ExecuteScalar(measurementDetailFormat, deviceName, labelName, "PM").ToNonNullString(); + magnitudeSignalReference = database.Connection.ExecuteScalar(outputMeasurementDetailFormat, magnitudePointTag).ToNonNullString(); } catch (Exception ex) { diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamMeasurement.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamMeasurement.cs index c2620bd3e4f..540a9b94e86 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamMeasurement.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/OutputStreamMeasurement.cs @@ -218,10 +218,10 @@ public static IList LoadKeys(AdoDataConnection database, int outputStreamID string sortClause = string.Empty; + DataTable outputStreamMeasurementTable; if (!string.IsNullOrEmpty(sortMember)) - sortClause = $"ORDER BY {sortMember} {sortDirection}"; - - DataTable outputStreamMeasurementTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT ID From OutputStreamMeasurementDetail where AdapterID = {outputStreamID} {sortClause}"); + outputStreamMeasurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From OutputStreamMeasurementDetail where AdapterID = {0} ORDER BY {1} {2}", outputStreamID, sortMember, sortDirection); + else outputStreamMeasurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From OutputStreamMeasurementDetail where AdapterID = {0}", outputStreamID); foreach (DataRow row in outputStreamMeasurementTable.Rows) { @@ -261,9 +261,10 @@ public static ObservableCollection Load(AdoDataConnecti if (keys is not null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - query = $"SELECT NodeID, AdapterID, ID, HistorianID, PointID, SignalReference, SourcePointTag, HistorianAcronym FROM OutputStreamMeasurementDetail WHERE ID IN ({commaSeparatedKeys})"; - outputStreamMeasurementTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + outputStreamMeasurementTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT NodeID, AdapterID, ID, HistorianID, PointID, SignalReference, SourcePointTag, HistorianAcronym " + + "FROM OutputStreamMeasurementDetail WHERE ID IN ({0})", DefaultTimeout, commaSeparatedKeys); outputStreamMeasurementList = new OutputStreamMeasurement[outputStreamMeasurementTable.Rows.Count]; foreach (DataRow row in outputStreamMeasurementTable.Rows) diff --git a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Phasor.cs b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Phasor.cs index 96855564e71..f2029c786c5 100755 --- a/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Phasor.cs +++ b/Source/Libraries/GSF.PhasorProtocols/UI/DataModels/Phasor.cs @@ -282,13 +282,10 @@ public static IList LoadKeys(AdoDataConnection database, int deviceID, stri IList phasorList = new List(); - string sortClause = string.Empty; - + DataTable phasorTable; if (!string.IsNullOrEmpty(sortMember)) - sortClause = $"ORDER BY {sortMember} {sortDirection}"; - - string query = database.ParameterizedQueryString($"SELECT ID From PhasorDetail WHERE DeviceID = {{0}} {sortClause}", "deviceID"); - DataTable phasorTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, deviceID); + phasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From PhasorDetail WHERE DeviceID = {0} ORDER BY {1} {2}", DefaultTimeout, deviceID, sortMember, sortDirection); + else phasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From PhasorDetail WHERE DeviceID = {0}", DefaultTimeout, deviceID); foreach (DataRow row in phasorTable.Rows) phasorList.Add(row.ConvertField("ID")); @@ -316,7 +313,6 @@ public static ObservableCollection Load(AdoDataConnection database, ILis { createdConnection = CreateConnection(ref database); - string query; string commaSeparatedKeys; Phasor[] phasorList = null; @@ -324,9 +320,7 @@ public static ObservableCollection Load(AdoDataConnection database, ILis if (keys is not null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => $"{key}").Aggregate((str1, str2) => $"{str1},{str2}"); - query = $"SELECT ID, DeviceID, Label, Type, Phase, BaseKV, DestinationPhasorID, SourceIndex, CreatedBy, CreatedOn, UpdatedBy, UpdatedOn FROM Phasor WHERE ID IN ({commaSeparatedKeys})"; - - DataTable phasorTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout); + DataTable phasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID, DeviceID, Label, Type, Phase, BaseKV, DestinationPhasorID, SourceIndex, CreatedBy, CreatedOn, UpdatedBy, UpdatedOn FROM Phasor WHERE ID IN ({0})", DefaultTimeout, commaSeparatedKeys); phasorList = new Phasor[phasorTable.Rows.Count]; foreach (DataRow row in phasorTable.Rows) @@ -573,7 +567,7 @@ public static Phasor GetPhasor(AdoDataConnection database, string whereClause) try { createdConnection = CreateConnection(ref database); - DataTable phasorTable = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM PhasorDetail {whereClause}"); + DataTable phasorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM PhasorDetail {0}", whereClause); if (phasorTable.Rows.Count == 0) return null; diff --git a/Source/Libraries/GSF.Security/AdoSecurityProvider.cs b/Source/Libraries/GSF.Security/AdoSecurityProvider.cs index 65a43b7eb08..c0492dd7cab 100755 --- a/Source/Libraries/GSF.Security/AdoSecurityProvider.cs +++ b/Source/Libraries/GSF.Security/AdoSecurityProvider.cs @@ -1515,9 +1515,12 @@ private static void UpdatePrimaryKey(DataTable table, string columnName) private static void AddSecurityContextTable(IDbConnection connection, DataSet securityContext, string tableName, Guid nodeID) { - string tableQuery = $"SELECT * FROM {tableName}{(nodeID == default ? "" : $" WHERE NodeID = '{nodeID}'")}"; - using IDataReader reader = connection.ExecuteReader(tableQuery); - securityContext.Tables.Add(tableName).Load(reader); + using (IDataReader reader = nodeID == default + ? connection.ExecuteReader("SELECT * FROM {0}", tableName) + : connection.ExecuteReader("SELECT * FROM {0} WHERE NodeID = '{1}'", tableName, nodeID)) + { + securityContext.Tables.Add(tableName).Load(reader); + } } private static string EncodeEscapeSequences(string value) => diff --git a/Source/Libraries/GSF.TimeSeries/Configuration/DatabaseConfigurationLoader.cs b/Source/Libraries/GSF.TimeSeries/Configuration/DatabaseConfigurationLoader.cs index 7dcca5e97d5..d02066369c0 100755 --- a/Source/Libraries/GSF.TimeSeries/Configuration/DatabaseConfigurationLoader.cs +++ b/Source/Libraries/GSF.TimeSeries/Configuration/DatabaseConfigurationLoader.cs @@ -330,7 +330,7 @@ public override void Augment(DataSet configuration) try { - database.Connection.ExecuteNonQuery($"DELETE FROM TrackedChange WHERE ID <= {latestVersion}"); + database.Connection.ExecuteNonQuery("DELETE FROM TrackedChange WHERE ID <= {0}",latestVersion); } catch (Exception ex) { @@ -365,7 +365,7 @@ private void ExecuteDataOperations(ulong trackingVersion = ulong.MinValue) { string assemblyName = "", typeName = "", methodName = ""; - foreach (DataRow row in database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM DataOperation WHERE (NodeID IS NULL OR NodeID={NodeIDQueryString}) AND Enabled <> 0 ORDER BY LoadOrder").Rows) + foreach (DataRow row in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM DataOperation WHERE (NodeID IS NULL OR NodeID={0}) AND Enabled <> 0 ORDER BY LoadOrder", NodeIDQueryString).Rows) { try { @@ -410,7 +410,7 @@ private DataTable LoadTable(DataRow entityRow) { // Load configuration entity data filtered by node ID Ticks operationStartTime = DateTime.UtcNow.Ticks; - DataTable source = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM {entityRow["SourceName"]} WHERE NodeID={NodeIDQueryString}"); + DataTable source = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM {0} WHERE NodeID={1}", entityRow["SourceName"], NodeIDQueryString); Time operationElapsedTime = (DateTime.UtcNow.Ticks - operationStartTime).ToSeconds(); // Update table name as defined in configuration entity @@ -491,8 +491,7 @@ private ulong GetLatestVersion(ulong currentVersion) { try { - string query = $"SELECT CASE WHEN COUNT(ID) = 0 THEN {currentVersion} ELSE MAX(ID) END FROM TrackedChange"; - version = Convert.ToUInt64(database.Connection.ExecuteScalar(query)); + version = Convert.ToUInt64(database.Connection.ExecuteScalar("SELECT CASE WHEN COUNT(ID) = 0 THEN {0} ELSE MAX(ID) END FROM TrackedChange", currentVersion)); } catch { @@ -511,8 +510,7 @@ private bool TrackedChangesAreValid(ulong currentVersion) { try { - string query = $"SELECT COUNT(ID) FROM TrackedChange WHERE ID < {currentVersion}"; - changesAreValid = Convert.ToInt32(database.Connection.ExecuteScalar(query)) == 0; + changesAreValid = Convert.ToInt32(database.Connection.ExecuteScalar("SELECT COUNT(ID) FROM TrackedChange WHERE ID < {0}", currentVersion)) == 0; } catch { @@ -526,7 +524,7 @@ private bool TrackedChangesAreValid(ulong currentVersion) private DataTable GetTrackedChanges(ulong currentVersion) { DataTable table = null; - Execute(database => table = database.Connection.RetrieveData(database.AdapterType, $"SELECT * FROM TrackedChange WHERE ID > {currentVersion}")); + Execute(database => table = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM TrackedChange WHERE ID > {0}", currentVersion)); return table; } @@ -536,8 +534,8 @@ private DataTable GetChangedRecords(string tableName, string primaryKeyColumn, u Execute(database => { - string query = $"SELECT * FROM {tableName} WHERE {primaryKeyColumn} IN (SELECT PrimaryKeyValue FROM TrackedChange WHERE TableName = '{tableName}' AND ID > {currentVersion}) AND NodeID = {NodeIDQueryString}"; - changes = database.Connection.RetrieveData(database.AdapterType, query); + changes = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM {0} WHERE {1} IN " + + "(SELECT PrimaryKeyValue FROM TrackedChange WHERE TableName = '{0}' AND ID > {2}) AND NodeID = {3}", tableName, primaryKeyColumn, currentVersion, NodeIDQueryString); }); return changes; diff --git a/Source/Libraries/GSF.TimeSeries/MeasurementKey.cs b/Source/Libraries/GSF.TimeSeries/MeasurementKey.cs index 2405d4e2756..58d41fbaeb4 100755 --- a/Source/Libraries/GSF.TimeSeries/MeasurementKey.cs +++ b/Source/Libraries/GSF.TimeSeries/MeasurementKey.cs @@ -459,7 +459,7 @@ public static bool TryParse(string value, out MeasurementKey key) public static void EstablishDefaultCache(IDbConnection connection, Type adapterType, string measurementTable = "ActiveMeasurement") { // Establish default measurement key cache - foreach (DataRow measurement in connection.RetrieveData(adapterType, $"SELECT ID, SignalID FROM {measurementTable}").Rows) + foreach (DataRow measurement in connection.RetrieveData(adapterType, "SELECT ID, SignalID FROM {0}", measurementTable).Rows) { if (TrySplit(measurement[nameof(ID)].ToString(), out string source, out ulong id)) CreateOrUpdate(measurement[nameof(SignalID)].ToNonNullString(Guid.Empty.ToString()).ConvertToType(), source, id); diff --git a/Source/Libraries/GSF.TimeSeries/Statistics/StatisticsEngine.cs b/Source/Libraries/GSF.TimeSeries/Statistics/StatisticsEngine.cs index 722bc0ae884..66e511c698e 100755 --- a/Source/Libraries/GSF.TimeSeries/Statistics/StatisticsEngine.cs +++ b/Source/Libraries/GSF.TimeSeries/Statistics/StatisticsEngine.cs @@ -665,7 +665,8 @@ private void UpdateStatisticMeasurements() // Get the statistic measurements from the database which have already been defined for this source string args = string.Join(",", signalReferences.Select((_, index) => $"{{{index}}}")); - List statisticMeasurements = helper.RetrieveData(string.Format(StatisticMeasurementSelectFormat, args), signalReferences.ToArray()).Select().ToList(); + string sql = database.ParameterizedQueryString(StatisticMeasurementSelectFormat, "args"); + List statisticMeasurements = helper.RetrieveData(sql, args, signalReferences.ToArray()).Select().ToList(); // If the number of statistics for the source category matches // the number of statistic measurements for the source, assume @@ -995,7 +996,7 @@ private string GetSystemName() using AdoDataConnection database = new("systemSettings"); - return database.Connection.ExecuteScalar($"SELECT Name FROM Node WHERE ID = '{database.Guid(GetNodeID())}'").ToNonNullString().ToUpper(); + return database.Connection.ExecuteScalar("SELECT Name FROM Node WHERE ID = '{0}'", database.Guid(GetNodeID())).ToNonNullString().ToUpper(); } private void RestartReloadStatisticsTimer() diff --git a/Source/Libraries/GSF.TimeSeries/TimeSeriesStartupOperations.cs b/Source/Libraries/GSF.TimeSeries/TimeSeriesStartupOperations.cs index abc3685448b..a706d4aaec6 100755 --- a/Source/Libraries/GSF.TimeSeries/TimeSeriesStartupOperations.cs +++ b/Source/Libraries/GSF.TimeSeries/TimeSeriesStartupOperations.cs @@ -247,11 +247,11 @@ private static void ValidateDataPublishers(AdoDataConnection database, string no sttpsDataPublisherEnabled = value.ParseBoolean(); } - int internalDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(DataPublisherCountFormat, "INTERNAL", nodeIDQueryString))); - int externalDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(DataPublisherCountFormat, "EXTERNAL", nodeIDQueryString))); - int tlsDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(DataPublisherCountFormat, "TLS", nodeIDQueryString))); - int sttpDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(DataPublisherCountFormat, "STTP", nodeIDQueryString))); - int sttpsDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(DataPublisherCountFormat, "STTPS", nodeIDQueryString))); + int internalDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(DataPublisherCountFormat, "INTERNAL", nodeIDQueryString)); + int externalDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(DataPublisherCountFormat, "EXTERNAL", nodeIDQueryString)); + int tlsDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(DataPublisherCountFormat, "TLS", nodeIDQueryString)); + int sttpDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(DataPublisherCountFormat, "STTP", nodeIDQueryString)); + int sttpsDataPublisherCount = Convert.ToInt32(database.Connection.ExecuteScalar(DataPublisherCountFormat, "STTPS", nodeIDQueryString)); if (internalDataPublisherCount == 0) database.Connection.ExecuteNonQuery(string.Format(GEPDataPublisherInsertFormat, nodeIDQueryString, "INTERNAL", "None", "cacheMeasurementKeys={FILTER ActiveMeasurements WHERE SignalType = ''STAT''}", internalDataPublisherEnabled ? 1 : 0)); @@ -684,8 +684,8 @@ private static void ValidateStatistics(AdoDataConnection database, string nodeID int statConfigEntityCount = Convert.ToInt32(database.Connection.ExecuteScalar(StatConfigEntityCountFormat)); int statSignalTypeCount = Convert.ToInt32(database.Connection.ExecuteScalar(StatSignalTypeCountFormat)); - int statHistorianCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(StatHistorianCountFormat, nodeIDQueryString))); - int statEngineCount = Convert.ToInt32(database.Connection.ExecuteScalar(string.Format(StatEngineCountFormat, nodeIDQueryString))); + int statHistorianCount = Convert.ToInt32(database.Connection.ExecuteScalar(StatHistorianCountFormat, nodeIDQueryString)); + int statEngineCount = Convert.ToInt32(database.Connection.ExecuteScalar(StatEngineCountFormat, nodeIDQueryString)); int systemStatCount = Convert.ToInt32(database.Connection.ExecuteScalar(SystemStatCountFormat)); int deviceStatCount = Convert.ToInt32(database.Connection.ExecuteScalar(DeviceStatCountFormat)); int subscriberStatCount = Convert.ToInt32(database.Connection.ExecuteScalar(SubscriberStatCountFormat)); diff --git a/Source/Libraries/GSF.TimeSeries/Transport/DataPublisher.cs b/Source/Libraries/GSF.TimeSeries/Transport/DataPublisher.cs index ec9d96534c9..17fc626d8d9 100755 --- a/Source/Libraries/GSF.TimeSeries/Transport/DataPublisher.cs +++ b/Source/Libraries/GSF.TimeSeries/Transport/DataPublisher.cs @@ -3069,7 +3069,7 @@ protected virtual DataSet AquireMetadata(ClientConnection connection, Dictionary DataSet metadata = new(); // Initialize active node ID - Guid nodeID = Guid.Parse(dbConnection.ExecuteScalar($"SELECT NodeID FROM IaonActionAdapter WHERE ID = {ID}").ToString()); + Guid nodeID = Guid.Parse(dbConnection.ExecuteScalar("SELECT NodeID FROM IaonActionAdapter WHERE ID = {0}", ID).ToString()); // Determine whether we're sending internal and external meta-data bool sendExternalMetadata = connection.OperationalModes.HasFlag(OperationalModes.ReceiveExternalMetadata); diff --git a/Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs b/Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs index 54182c0c7b6..63466866c8b 100755 --- a/Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs +++ b/Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs @@ -3456,7 +3456,7 @@ protected virtual void SynchronizeMetadata() command.Transaction = transaction; // Query the actual record ID based on the known run-time ID for this subscriber device - object sourceID = command.ExecuteScalar($"SELECT SourceID FROM Runtime WHERE ID = {ID} AND SourceTable='Device'", MetadataSynchronizationTimeout); + object sourceID = command.ExecuteScalar("SELECT SourceID FROM Runtime WHERE ID = {0} AND SourceTable='Device'", MetadataSynchronizationTimeout, ID); if (sourceID is null || sourceID == DBNull.Value) return; @@ -3464,15 +3464,15 @@ protected virtual void SynchronizeMetadata() int parentID = Convert.ToInt32(sourceID); // Validate that the subscriber device is marked as a concentrator (we are about to associate children devices with it) - if (!command.ExecuteScalar($"SELECT IsConcentrator FROM Device WHERE ID = {parentID}", MetadataSynchronizationTimeout).ToString().ParseBoolean()) - command.ExecuteNonQuery($"UPDATE Device SET IsConcentrator = 1 WHERE ID = {parentID}", MetadataSynchronizationTimeout); + if (!command.ExecuteScalar("SELECT IsConcentrator FROM Device WHERE ID = {0}", MetadataSynchronizationTimeout, parentID).ToString().ParseBoolean()) + command.ExecuteNonQuery("UPDATE Device SET IsConcentrator = 1 WHERE ID = {0}", MetadataSynchronizationTimeout, parentID); // Get any historian associated with the subscriber device - object historianID = command.ExecuteScalar($"SELECT HistorianID FROM Device WHERE ID = {parentID}", MetadataSynchronizationTimeout); + object historianID = command.ExecuteScalar("SELECT HistorianID FROM Device WHERE ID = {0}", MetadataSynchronizationTimeout, parentID); // Determine the active node ID - we cache this since this value won't change for the lifetime of this class if (m_nodeID == Guid.Empty) - m_nodeID = Guid.Parse(command.ExecuteScalar($"SELECT NodeID FROM IaonInputAdapter WHERE ID = {(int)ID}", MetadataSynchronizationTimeout).ToString()); + m_nodeID = Guid.Parse(command.ExecuteScalar("SELECT NodeID FROM IaonInputAdapter WHERE ID = {0}", MetadataSynchronizationTimeout, ID).ToString()); // Determine the protocol record auto-inc ID value for the gateway transport protocol (GEP) - this value is also cached since it shouldn't change for the lifetime of this class if (m_gatewayProtocolID == 0) diff --git a/Source/Libraries/GSF.TimeSeries/Transport/UI/WPF/ViewModels/Subscribers.cs b/Source/Libraries/GSF.TimeSeries/Transport/UI/WPF/ViewModels/Subscribers.cs index 0ee1a8143dc..e6b495cf73c 100755 --- a/Source/Libraries/GSF.TimeSeries/Transport/UI/WPF/ViewModels/Subscribers.cs +++ b/Source/Libraries/GSF.TimeSeries/Transport/UI/WPF/ViewModels/Subscribers.cs @@ -714,8 +714,6 @@ private void LoadPermissionsDataSet() }; DataTable dataTable; - string queryFormat; - string parameterizedQuery; m_subscriberPermissionsDataSet = new DataSet(); @@ -723,9 +721,7 @@ private void LoadPermissionsDataSet() { foreach (KeyValuePair definition in dataTableDefinitions) { - queryFormat = string.Format("SELECT * FROM {0} WHERE NodeID = {{0}}", definition.Key); - parameterizedQuery = database.ParameterizedQueryString(queryFormat, "nodeID"); - dataTable = database.Connection.RetrieveData(database.AdapterType, parameterizedQuery, DataExtensions.DefaultTimeoutDuration, database.CurrentNodeID()); + dataTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM {0} WHERE NodeID = {1}", DataExtensions.DefaultTimeoutDuration, definition.Key, database.CurrentNodeID()); dataTable.TableName = definition.Value; dataTable.DataSet.Tables.Remove(dataTable); m_subscriberPermissionsDataSet.Tables.Add(dataTable); diff --git a/Source/Libraries/GSF.TimeSeries/UI/AuthorizedMeasurementsQuery.cs b/Source/Libraries/GSF.TimeSeries/UI/AuthorizedMeasurementsQuery.cs index b813ba42b50..8751bfc7ea4 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/AuthorizedMeasurementsQuery.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/AuthorizedMeasurementsQuery.cs @@ -214,8 +214,9 @@ private void ExecuteAuthorizationQuery() database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory); string guidPrefix = database.DatabaseType == DatabaseType.Access ? "{" : "'"; string guidSuffix = database.DatabaseType == DatabaseType.Access ? "}" : "'"; - string query = string.Format("SELECT DISTINCT DeviceID FROM ActiveMeasurement WHERE ProtocolType = 'Measurement' AND SignalID IN ({0})", sourceMeasurements.Select(signalID => guidPrefix + signalID.ToString() + guidSuffix).ToDelimitedString(", ")); - DataTable measurementDevices = database.Connection.RetrieveData(database.AdapterType, query); + DataTable measurementDevices = database.Connection.RetrieveData(database.AdapterType, "SELECT DISTINCT DeviceID " + + "FROM ActiveMeasurement WHERE ProtocolType = 'Measurement' AND SignalID IN ({0})", + sourceMeasurements.Select(signalID => guidPrefix + signalID.ToString() + guidSuffix).ToDelimitedString(", ")); foreach (DataRow row in measurementDevices.Rows) { diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Adapter.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Adapter.cs index 930a09e9187..7882a91b561 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Adapter.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Adapter.cs @@ -38,6 +38,7 @@ using System.ComponentModel.DataAnnotations; using System.Data; using System.Linq; +using System.Windows.Controls.Primitives; using GSF.ComponentModel.DataAnnotations; using GSF.Data; @@ -379,14 +380,13 @@ public static IList LoadIDs(AdoDataConnection database, AdapterType adapter IList adapterList = new List(); string sortClause = string.Empty; DataTable adapterTable; - string query; if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - - query = database.ParameterizedQueryString(string.Format("SELECT ID FROM {0} WHERE NodeID = {{0}} {1}", viewName, sortClause), "nodeID"); - - adapterTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM {0} WHERE NodeID = {1} ORDER BY {2} {3}", + DefaultTimeout, viewName, database.CurrentNodeID(), sortMember, sortDirection); + else adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM {0} WHERE NodeID = {1}", DefaultTimeout, viewName, database.CurrentNodeID()); foreach (DataRow row in adapterTable.Rows) { @@ -428,7 +428,6 @@ public static ObservableCollection Load(AdoDataConnection database, Ada else viewName = "CustomOutputAdapterDetail"; - string query; string commaSeparatedKeys; Adapter[] adapterList = null; @@ -438,10 +437,11 @@ public static ObservableCollection Load(AdoDataConnection database, Ada if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => "" + key.ToString() + "").Aggregate((str1, str2) => str1 + "," + str2); - query = database.ParameterizedQueryString(string.Format("SELECT NodeID, ID, AdapterName, AssemblyName, TypeName, ConnectionString, " + - "LoadOrder, Enabled, NodeName FROM {0} WHERE NodeID = {{0}} AND ID IN ({1})", viewName, commaSeparatedKeys), "nodeID"); - adapterTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT NodeID, ID, AdapterName, AssemblyName, TypeName, ConnectionString, " + + "LoadOrder, Enabled, NodeName FROM {0} WHERE NodeID = {2} AND ID IN ({1})", + DefaultTimeout, viewName, commaSeparatedKeys, database.CurrentNodeID()); adapterList = new Adapter[adapterTable.Rows.Count]; foreach (DataRow row in adapterTable.Rows) @@ -503,8 +503,8 @@ public static Dictionary GetLookupList(AdoDataConnection database, else tableName = "CustomOutputAdapter"; - string query = database.ParameterizedQueryString("SELECT ID, Name FROM " + tableName + " WHERE Enabled = {0} ORDER BY LoadOrder", "enabled"); - DataTable adapterTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.Bool(true)); + DataTable adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID, Name FROM {0} WHERE Enabled = {1} ORDER BY LoadOrder", "enabled", DefaultTimeout, tableName, database.Bool(true)); foreach (DataRow row in adapterTable.Rows) adapterList[row.ConvertField("ID")] = row.Field("Name"); diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Alarm.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Alarm.cs index 4bd03d8836b..5b0dd3402df 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Alarm.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Alarm.cs @@ -523,14 +523,11 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember IList alarmList = new List(); string sortClause = string.Empty; DataTable adapterTable; - string query; - - if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - query = database.ParameterizedQueryString(string.Format("SELECT ID FROM Alarm WHERE NodeID = {{0}} {0}", sortClause), "nodeID"); - - adapterTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + if (!string.IsNullOrEmpty(sortMember)) adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM Alarm WHERE NodeID = {0} ORDER BY {1} {2}", DefaultTimeout, database.CurrentNodeID(), sortMember, sortDirection); + else adapterTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM Alarm WHERE NodeID = {0}", DefaultTimeout, database.CurrentNodeID()); foreach (DataRow row in adapterTable.Rows) { @@ -571,10 +568,10 @@ public static ObservableCollection Load(AdoDataConnection database, IList if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => "" + key.ToString() + "").Aggregate((str1, str2) => str1 + "," + str2); - query = database.ParameterizedQueryString(string.Format("SELECT NodeID, TagName, ID, SignalID, AssociatedMeasurementID, Description, Severity, Operation, " + - "SetPoint, Tolerance, Delay, Hysteresis, LoadOrder, Enabled FROM Alarm WHERE NodeID = {{0}} AND ID IN ({0})", commaSeparatedKeys), "nodeID"); - - alarmTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + alarmTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT NodeID, TagName, ID, SignalID, AssociatedMeasurementID, Description, Severity, Operation, " + + "SetPoint, Tolerance, Delay, Hysteresis, LoadOrder, Enabled FROM Alarm WHERE NodeID = {0} AND ID IN ({1})", + DefaultTimeout, database.CurrentNodeID(), commaSeparatedKeys); alarmList = new Alarm[alarmTable.Rows.Count]; foreach (DataRow row in alarmTable.Rows) @@ -625,7 +622,7 @@ public static Alarm GetAlarm(AdoDataConnection database, string whereClause) try { createdConnection = CreateConnection(ref database); - DataTable alarmTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Alarm " + whereClause); + DataTable alarmTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM Alarm {0}", whereClause); if (alarmTable.Rows.Count == 0) return null; diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Company.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Company.cs index 8a3a2249799..e163013c906 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Company.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Company.cs @@ -304,8 +304,8 @@ public static ObservableCollection Load(AdoDataConnection database, ILi if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => str1 + "," + str2); - query = string.Format("SELECT ID, Acronym, MapAcronym, Name, URL, LoadOrder FROM Company WHERE ID IN ({0})", commaSeparatedKeys); - companyTable = database.Connection.RetrieveData(database.AdapterType, query); + query = database.ParameterizedQueryString("SELECT ID, Acronym, MapAcronym, Name, URL, LoadOrder FROM Company WHERE ID IN ({0})", "commaSeparatedKeys"); + companyTable = database.Connection.RetrieveData(database.AdapterType, query, commaSeparatedKeys); companyList = new Company[companyTable.Rows.Count]; foreach (DataRow row in companyTable.Rows) diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/ErrorLog.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/ErrorLog.cs index 76bdaa793e6..c7a52942b1d 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/ErrorLog.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/ErrorLog.cs @@ -179,10 +179,9 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember string sortClause = string.Empty; DataTable ErrorLogTable; - if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - - ErrorLogTable = database.Connection.RetrieveData(database.AdapterType, string.Format("SELECT ID FROM ErrorLog {0} ", sortClause)); + if (!string.IsNullOrEmpty(sortMember)) + ErrorLogTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID FROM ErrorLog ORDER BY {0} {1}", sortMember, sortDirection); + else ErrorLogTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID FROM ErrorLog"); foreach (DataRow row in ErrorLogTable.Rows) { @@ -222,8 +221,8 @@ public static ObservableCollection Load(AdoDataConnection database, IL if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => "" + key.ToString() + "").Aggregate((str1, str2) => str1 + "," + str2); - query = string.Format("SELECT ID, Source, Type, Message, Detail, CreatedOn FROM ErrorLog WHERE ID IN ({0})", commaSeparatedKeys); - errorLogTable = database.Connection.RetrieveData(database.AdapterType, query); + query = database.ParameterizedQueryString("SELECT ID, Source, Type, Message, Detail, CreatedOn FROM ErrorLog WHERE ID IN ({0})", "commaSeparatedKeys"); + errorLogTable = database.Connection.RetrieveData(database.AdapterType, query, commaSeparatedKeys); errorLogList = new ErrorLog[errorLogTable.Rows.Count]; foreach (DataRow row in errorLogTable.Rows) diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Historian.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Historian.cs index 1c7a7cfa15a..aa698c7c574 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Historian.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Historian.cs @@ -380,13 +380,12 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember IList historianList = new List(); string sortClause = string.Empty; DataTable historianTable; - string query; if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - - query = database.ParameterizedQueryString(string.Format("SELECT ID FROM HistorianDetail WHERE NodeID = {{0}} {0}", sortClause), "nodeID"); - historianTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + historianTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM HistorianDetail WHERE NodeID = {0} ORDER BY {1} {2}", database.CurrentNodeID(), sortMember, sortDirection); + else historianTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID FROM HistorianDetail WHERE NodeID = {0}", DefaultTimeout, database.CurrentNodeID()); foreach (DataRow row in historianTable.Rows) { @@ -416,7 +415,6 @@ public static ObservableCollection Load(AdoDataConnection database, I { createdConnection = CreateConnection(ref database); - string query; string commaSeparatedKeys; Historian[] historianList = null; @@ -426,11 +424,11 @@ public static ObservableCollection Load(AdoDataConnection database, I if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => str1 + "," + str2); - query = database.ParameterizedQueryString(string.Format("SELECT NodeID, ID, Acronym, Name, AssemblyName, TypeName, " + - "ConnectionString, IsLocal, Description, LoadOrder, Enabled, MeasurementReportingInterval, NodeName" + - " FROM HistorianDetail WHERE NodeID = {{0}} AND ID IN ({0})", commaSeparatedKeys), "nodeID"); - historianTable = database.Connection.RetrieveData(database.AdapterType, query, DefaultTimeout, database.CurrentNodeID()); + historianTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT NodeID, ID, Acronym, Name, AssemblyName, TypeName, " + + "ConnectionString, IsLocal, Description, LoadOrder, Enabled, MeasurementReportingInterval, NodeName" + + " FROM HistorianDetail WHERE NodeID = {0} AND ID IN ({1})", DefaultTimeout, database.CurrentNodeID(), commaSeparatedKeys); historianList = new Historian[historianTable.Rows.Count]; foreach (DataRow row in historianTable.Rows) @@ -603,7 +601,7 @@ public static Historian GetHistorian(AdoDataConnection database, string whereCla try { createdConnection = CreateConnection(ref database); - DataTable historianTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM HistorianDetail " + whereClause); + DataTable historianTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM HistorianDetail {0}", whereClause); if (historianTable.Rows.Count == 0) return null; diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Measurement.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Measurement.cs index da712c85745..9efd1f7e40c 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Measurement.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Measurement.cs @@ -592,18 +592,26 @@ public static List LoadSignalIDs(AdoDataConnection database, string filter List signalIDList = new List(); DataTable measurementTable; - string query; - string sortClause = string.Empty; - - if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - - if (!string.IsNullOrEmpty(filterExpression)) - query = string.Format("SELECT SignalID FROM MeasurementDetail WHERE ({0}) {1}", filterExpression, sortClause); + if (!string.IsNullOrEmpty(filterExpression) && !string.IsNullOrEmpty(sortMember)) + { + measurementTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT SignalID FROM MeasurementDetail WHERE ({0}) ORDER BY {1} {2}", filterExpression, sortMember, sortDirection); + } + else if (!string.IsNullOrEmpty(filterExpression) && string.IsNullOrEmpty(sortMember)) + { + measurementTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT SignalID FROM MeasurementDetail WHERE ({0})", filterExpression); + } + else if (!string.IsNullOrEmpty(sortMember)) + { + measurementTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT SignalID FROM MeasurementDetail ORDER BY {0} {1}", sortMember, sortDirection); + } else - query = string.Format("SELECT SignalID FROM MeasurementDetail {0}", sortClause); - - measurementTable = database.Connection.RetrieveData(database.AdapterType, query); + { + measurementTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT SignalID FROM MeasurementDetail"); + } foreach (DataRow row in measurementTable.Rows) { @@ -643,8 +651,8 @@ public static ObservableCollection LoadFromKeys(AdoDataConnection d if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => "'" + key.ToString() + "'").Aggregate((str1, str2) => str1 + "," + str2); - query = string.Format("SELECT * FROM MeasurementDetail WHERE SignalID IN ({0})", commaSeparatedKeys); - measurementTable = database.Connection.RetrieveData(database.AdapterType, query); + query = database.ParameterizedQueryString("SELECT * FROM MeasurementDetail WHERE SignalID IN ({0})", "commaSeparatedKeys"); + measurementTable = database.Connection.RetrieveData(database.AdapterType, query, commaSeparatedKeys); measurementList = new Measurement[measurementTable.Rows.Count]; foreach (DataRow row in measurementTable.Rows) @@ -1203,7 +1211,7 @@ public static Measurement GetMeasurement(AdoDataConnection database, string wher try { createdConnection = CreateConnection(ref database); - measurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM MeasurementDetail " + whereClause); + measurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM MeasurementDetail {0}", whereClause); if (measurementTable.Rows.Count == 0) return null; @@ -1261,7 +1269,7 @@ public static ObservableCollection GetMeasurements(AdoDataConnectio { createdConnection = CreateConnection(ref database); ObservableCollection measurementList = new ObservableCollection(); - DataTable measurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM MeasurementDetail " + whereClause); + DataTable measurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM MeasurementDetail {0}", whereClause); foreach (DataRow row in measurementTable.Rows) { measurementList.Add(new Measurement diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Node.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Node.cs index 1871232f6f6..02053e8e2ef 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Node.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Node.cs @@ -466,9 +466,9 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember DataTable nodeTable; if (!string.IsNullOrEmpty(sortMember)) - sortClause = $"ORDER BY {sortMember} {sortDirection}"; - - nodeTable = database.Connection.RetrieveData(database.AdapterType, $"Select ID From NodeDetail {sortClause}"); + nodeTable = database.Connection.RetrieveData(database.AdapterType, + "Select ID From NodeDetail ORDER BY {0} {1}", sortMember, sortDirection); + else nodeTable = database.Connection.RetrieveData(database.AdapterType, "Select ID From NodeDetail"); foreach (DataRow row in nodeTable.Rows) @@ -499,7 +499,6 @@ public static ObservableCollection Load(AdoDataConnection database, IList< { createdConnection = CreateConnection(ref database); - string query; string commaSeparatedKeys; Node[] nodeList = null; @@ -509,9 +508,10 @@ public static ObservableCollection Load(AdoDataConnection database, IList< if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => "'" + key.ToString() + "'").Aggregate((str1, str2) => str1 + "," + str2); - query = "Select ID, Name, CompanyID, Longitude, Latitude, Description, ImagePath, Settings, MenuData, " + $"MenuType, Master, LoadOrder, Enabled, CompanyName From NodeDetail WHERE ID IN ({commaSeparatedKeys})"; - nodeTable = database.Connection.RetrieveData(database.AdapterType, query); + nodeTable = database.Connection.RetrieveData(database.AdapterType, + "Select ID, Name, CompanyID, Longitude, Latitude, Description, ImagePath, Settings, MenuData, " + + "MenuType, Master, LoadOrder, Enabled, CompanyName From NodeDetail WHERE ID IN ({0})", commaSeparatedKeys); nodeList = new Node[nodeTable.Rows.Count]; foreach (DataRow row in nodeTable.Rows) @@ -667,8 +667,7 @@ public static string Save(AdoDataConnection database, Node node) } else { - query = $"SELECT Name FROM NodeDetail WHERE ID IN ('{node.ID}')"; - DataTable nodeTable = database.Connection.RetrieveData(database.AdapterType, query); + DataTable nodeTable = database.Connection.RetrieveData(database.AdapterType, "SELECT Name FROM NodeDetail WHERE ID IN ('{0}')", node.ID); query = "SELECT SignalIndex FROM Statistic WHERE Source = \'System\'"; DataTable systemTable = database.Connection.RetrieveData(database.AdapterType, query); diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/UserAccount.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/UserAccount.cs index 0cdc0b0272d..cf53b6fdb92 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/UserAccount.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/UserAccount.cs @@ -342,7 +342,8 @@ public static ObservableCollection Load(AdoDataConnection database) createdConnection = CreateConnection(ref database); ObservableCollection userAccountList = new ObservableCollection(); - DataTable userAccountTable = database.Connection.RetrieveData(database.AdapterType, "SELECT * From UserAccount WHERE DefaultNodeID = '" + database.CurrentNodeID() + "' ORDER BY Name"); + DataTable userAccountTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT * From UserAccount WHERE DefaultNodeID = '{0}' ORDER BY Name", database.CurrentNodeID()); foreach (DataRow row in userAccountTable.Rows) { diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Vendor.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Vendor.cs index 172453ba04b..f3124b6911f 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/Vendor.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/Vendor.cs @@ -260,10 +260,9 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember, string sortClause = string.Empty; if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - + vendorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From VendorDetail ORDER BY {0} {1}", sortMember, sortDirection); // check the query once again , Does it have to be details or somethng else - vendorTable = database.Connection.RetrieveData(database.AdapterType, string.Format("SELECT ID From VendorDetail {0}", sortClause)); + else vendorTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID From VendorDetail"); foreach (DataRow row in vendorTable.Rows) { @@ -292,8 +291,7 @@ public static ObservableCollection Load(AdoDataConnection database, ILis try { createdConnection = CreateConnection(ref database); - - string query; + string commaSeparatedKeys; Vendor[] vendorList = null; @@ -303,8 +301,8 @@ public static ObservableCollection Load(AdoDataConnection database, ILis if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => str1 + "," + str2); - query = string.Format("SELECT ID, Acronym, Name, PhoneNumber, ContactEmail, URL FROM VendorDetail WHERE ID IN ({0})", commaSeparatedKeys); - vendorTable = database.Connection.RetrieveData(database.AdapterType, query); + vendorTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID, Acronym, Name, PhoneNumber, ContactEmail, URL FROM VendorDetail WHERE ID IN ({0})", commaSeparatedKeys); vendorList = new Vendor[vendorTable.Rows.Count]; foreach (DataRow row in vendorTable.Rows) diff --git a/Source/Libraries/GSF.TimeSeries/UI/DataModels/VendorDevice.cs b/Source/Libraries/GSF.TimeSeries/UI/DataModels/VendorDevice.cs index 38a21cd52d7..05a1ed42f76 100755 --- a/Source/Libraries/GSF.TimeSeries/UI/DataModels/VendorDevice.cs +++ b/Source/Libraries/GSF.TimeSeries/UI/DataModels/VendorDevice.cs @@ -247,10 +247,11 @@ public static IList LoadKeys(AdoDataConnection database, string sortMember, string sortClause = string.Empty; if (!string.IsNullOrEmpty(sortMember)) - sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); - + vendorDeviceTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID From VendorDeviceDetail ORDER BY {0} {1}", sortMember, sortDirection); // check the query once again , Does it have to be details or somethng else - vendorDeviceTable = database.Connection.RetrieveData(database.AdapterType, string.Format("SELECT ID From VendorDeviceDetail {0}", sortClause)); + else vendorDeviceTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT ID From VendorDeviceDetail"); foreach (DataRow row in vendorDeviceTable.Rows) { @@ -279,7 +280,6 @@ public static ObservableCollection Load(AdoDataConnection database { createdConnection = CreateConnection(ref database); - string query; string commaSeparatedKeys; VendorDevice[] vendorDeviceList = null; @@ -289,8 +289,8 @@ public static ObservableCollection Load(AdoDataConnection database if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => str1 + "," + str2); - query = string.Format("SELECT * FROM VendorDeviceDetail WHERE ID IN ({0})", commaSeparatedKeys); - vendorDeviceTable = database.Connection.RetrieveData(database.AdapterType, query); + vendorDeviceTable = database.Connection.RetrieveData(database.AdapterType, + "SELECT * FROM VendorDeviceDetail WHERE ID IN ({0})", commaSeparatedKeys); vendorDeviceList = new VendorDevice[vendorDeviceTable.Rows.Count]; foreach (DataRow row in vendorDeviceTable.Rows) diff --git a/Source/Libraries/GSF.Web/Model/ModelController.cs b/Source/Libraries/GSF.Web/Model/ModelController.cs index 12413c20422..e5314401e66 100644 --- a/Source/Libraries/GSF.Web/Model/ModelController.cs +++ b/Source/Libraries/GSF.Web/Model/ModelController.cs @@ -566,8 +566,9 @@ protected virtual IEnumerable QueryRecordsWhere(string orderBy, bool ascendin WHERE {flt} {(orderBy != null ? " ORDER BY " + orderString : "")}"; - - DataTable dataTbl = connection.RetrieveData(sql, param); + DataTable dataTbl; + if (orderBy != null) dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl WHERE {1} ORDER BY {2}", CustomView, flt, orderString, param); + else dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl WHERE {1}", CustomView, flt, param); List result = new List(); TableOperations tblOperations = new TableOperations(connection); @@ -600,8 +601,7 @@ protected virtual T QueryRecordWhere(string filterExpression, params object[] pa } whereClause = " WHERE " + whereClause; - string sql = "SELECT * FROM (" + CustomView + ") FullTbl"; - DataTable dataTbl = connection.RetrieveData(sql + whereClause, param); + DataTable dataTbl = connection.RetrieveData("SELECT * FROM (0) FullTbl{1}", CustomView, whereClause, param); TableOperations tblOperations = new TableOperations(connection); if (dataTbl.Rows.Count > 0) @@ -639,16 +639,16 @@ protected virtual IEnumerable QueryRecords(string sortBy, bool ascending) DataTable dataTbl; if (RootQueryRestriction != null) { - sql = $@" - SELECT * FROM - ({CustomView}) FullTbl - WHERE ({RootQueryRestriction.FilterExpression}) - {(sortBy != null ? " ORDER BY " + orderString : "")}"; - - dataTbl = connection.RetrieveData(sql, RootQueryRestriction.Parameters); + if (sortBy != null) dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl WHERE ({1}) ORDER BY {2}", + CustomView, RootQueryRestriction.FilterExpression, orderString, RootQueryRestriction.Parameters); + else dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl WHERE ({1})", + CustomView, RootQueryRestriction.FilterExpression, RootQueryRestriction.Parameters); } else - dataTbl = connection.RetrieveData(sql); + if (sortBy != null) dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl ORDER BY {1}", + CustomView, orderString); + else dataTbl = connection.RetrieveData("SELECT * FROM ({0}) FullTbl WHERE ({1})", + CustomView); List result = new List(); TableOperations tblOperations = new TableOperations(connection); @@ -791,10 +791,11 @@ protected virtual DataTable GetSearchResults(PostData postData, int? page = null if (SearchSettings.Condition != String.Empty) joinCondition = $"{joinCondition} AND "; joinCondition = joinCondition + $"SRC.{PrimaryKeyField} = AF.{SearchSettings.PrimaryKeyField}"; - + string sqlPivotColumns = $@" SELECT '[AFV_' + [Key] + ']' - FROM (Select DISTINCT {SearchSettings.FieldKeyField} AS [Key] FROM {SearchSettings.AdditionalFieldTable} AS AF WHERE {collumnCondition} ) AS [Fields]"; + FROM (Select DISTINCT {SearchSettings.FieldKeyField} AS [Key] + FROM {SearchSettings.AdditionalFieldTable} AS AF WHERE {collumnCondition} ) AS [Fields]"; sqlPivotColumns = string.Join(",", connection.RetrieveData(sqlPivotColumns).Select().Select(r => r[0].ToString())); string tblSelect = $@" (SELECT diff --git a/Source/Tools/CSVDataManager/MainWindow.cs b/Source/Tools/CSVDataManager/MainWindow.cs index 4860cc538f5..9966a269682 100644 --- a/Source/Tools/CSVDataManager/MainWindow.cs +++ b/Source/Tools/CSVDataManager/MainWindow.cs @@ -501,11 +501,11 @@ private void ExportSelectionToFile(Table table, Field[] fields) { writer.WriteLine(csvHeader); - object result = DBSchema.Connection.ExecuteScalar($"SELECT COUNT(*) FROM {table.SQLEscapedName}"); + object result = DBSchema.Connection.ExecuteScalar("SELECT COUNT(*) FROM {0}", table.SQLEscapedName); int count = Convert.ToInt32(result); UpdateProgressBar(ExportProgressBar, 0); - using (IDataReader reader = DBSchema.Connection.ExecuteReader($"SELECT {fieldList} FROM {table.SQLEscapedName}")) + using (IDataReader reader = DBSchema.Connection.ExecuteReader("SELECT {0} FROM {1}", fieldList, table.SQLEscapedName)) { int records = 0;