//****************************************************************************************************** // CalculatedMeasurement.cs - Gbtc // // Copyright © 2010, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://www.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 04/11/2011 - Aniket Salver // Generated original version of source code. // 04/21/2011 - Mehulbhai P Thakkar // Added static methods for database operations. // 05/02/2011 - J. Ritchie Carroll // Updated for coding consistency. // 05/03/2011 - Mehulbhai P Thakkar // Guid field related changes as well as static functions update. // 05/05/2011 - Mehulbhai P Thakkar // Added NULL value and Guid parameter handling for Save() operation. // 05/12/2011 - Aniket Salver // Modified the way Guid is retrived from the Data Base. // 05/13/2011 - Mehulbhai P Thakkar // Added regular expression validator for Acronym. // //****************************************************************************************************** using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data; using System.Linq; using GSF.ComponentModel.DataAnnotations; using GSF.Data; using GSF.TimeSeries.UI; namespace GSF.PhasorProtocols.UI.DataModels { /// /// Represents a record of information as defined in the database. /// public class CalculatedMeasurement : DataModelBase { #region [ Members ] // Fields private Guid m_nodeID; private int m_id; private string m_acronym; private string m_name; private string m_typeName; private string m_assemblyName; private string m_connectionString; private string m_configSection; private string m_outputMeasurements; private string m_inputMeasurements; private int m_minimumMeasurementsToUse; private int m_framesPerSecond; private double m_lagTime; private double m_leadTime; private bool m_useLocalClockAsRealTime; private bool m_allowSortsByArrival; private int m_loadOrder; private bool m_enabled; private bool m_ignoreBadTimeStamps; private int m_timeResolution; private bool m_allowPreemptivePublishing; private string m_downsamplingMethod; private string m_nodeName; private bool m_performTimestampReasonabilityCheck; private DateTime m_createdOn; private string m_createdBy; private DateTime m_updatedOn; private string m_updatedBy; #endregion #region [ Properties ] /// /// Gets or sets NodeID. /// [Required(ErrorMessage = "Please select a node ID.")] public Guid NodeID { get { return m_nodeID; } set { m_nodeID = value; OnPropertyChanged("NodeID"); } } /// /// Gets or sets ID. /// // Field is populated by database via auto-increment and has no screen interaction, so no validation attributes are applied public int ID { get { return m_id; } set { m_id = value; } } /// /// Gets or sets Acronym. /// [Required(ErrorMessage = "Calculated measurement acronym is a required field, please provide value.")] [StringLength(200, ErrorMessage = "Calculated measurement acronym cannot exceed 200 characters.")] [AcronymValidation] public string Acronym { get { return m_acronym; } set { m_acronym = value; OnPropertyChanged("Acronym"); } } /// /// Gets or sets Name. /// [StringLength(200, ErrorMessage = "Calculated measurement name cannot exceed 200 characters.")] public string Name { get { return m_name; } set { m_name = value; OnPropertyChanged("Name"); } } /// /// Gets or sets Acronym. /// [Required(ErrorMessage = "Calculated measurement type name is a required field, please provide value.")] public string TypeName { get { return m_typeName; } set { m_typeName = value; OnPropertyChanged("TypeName"); } } /// /// Gets or sets AssemblyName. /// [Required(ErrorMessage = "Calculated measurement assembly name is a required field, please provide value.")] public string AssemblyName { get { return m_assemblyName; } set { m_assemblyName = value; OnPropertyChanged("AssemblyName"); } } /// /// Gets or sets ConnectionString. /// // Because of database design, no validation attributes are applied. public string ConnectionString { get { return m_connectionString; } set { if ((object)value == null) m_connectionString = string.Empty; else m_connectionString = value; OnPropertyChanged("ConnectionString"); } } /// /// Gets or sets ConfigSection. /// [StringLength(200, ErrorMessage = "Config Section cannot exceed 200 characters.")] public string ConfigSection { get { return m_configSection; } set { m_configSection = value; OnPropertyChanged("ConfigSection"); } } /// /// Gets or sets OutputMeasurements. /// // Because of database design, no validation attributes are applied. public string OutputMeasurements { get { return m_outputMeasurements; } set { m_outputMeasurements = value; OnPropertyChanged("OutputMeasurements"); } } /// /// Gets or sets InputMeasurements. /// // Because of database design, no validation attributes are applied. public string InputMeasurements { get { return m_inputMeasurements; } set { m_inputMeasurements = value; OnPropertyChanged("InputMeasurements"); } } /// /// Gets or sets MinimumMeasurementsToUse. /// [Required(ErrorMessage = " Calculated measurement minimum measurements to use is a required field, please provide value.")] [DefaultValue(-1)] public int MinimumMeasurementsToUse { get { return m_minimumMeasurementsToUse; } set { m_minimumMeasurementsToUse = value; OnPropertyChanged("MinimumMeasurementsToUse"); } } /// /// Gets or sets FramesPerSecond. /// [Required(ErrorMessage = " Calculated measurement frames per second is a required field, please provide value.")] [DefaultValue(30)] public int FramesPerSecond { get { return m_framesPerSecond; } set { m_framesPerSecond = value; OnPropertyChanged("FramesPerSecond"); } } /// /// Gets or sets LagTime. /// [Required(ErrorMessage = "Calculated measurement lag time is a required field, please provide value.")] [DefaultValue(3.0D)] public double LagTime { get { return m_lagTime; } set { m_lagTime = value; OnPropertyChanged("LagTime"); } } /// /// Gets or sets LeadTime. /// [Required(ErrorMessage = "Calculated measurement lead time is a required field, please provide value.")] [DefaultValue(1.0D)] public double LeadTime { get { return m_leadTime; } set { m_leadTime = value; OnPropertyChanged("LeadTime"); } } /// /// Gets or sets UseLocalClockAsRealTime. /// [DefaultValue(false)] public bool UseLocalClockAsRealTime { get { return m_useLocalClockAsRealTime; } set { m_useLocalClockAsRealTime = value; OnPropertyChanged("UseLocalClockAsRealTime"); } } /// /// Gets or sets AllowSortsByArrival. /// [DefaultValue(true)] public bool AllowSortsByArrival { get { return m_allowSortsByArrival; } set { m_allowSortsByArrival = value; OnPropertyChanged("AllowSortsByArrival"); } } /// /// Gets or sets LoadOrder. /// [Required(ErrorMessage = "Calculated measurement load order is a required field, please provide value.")] [DefaultValue(0)] public int LoadOrder { get { return m_loadOrder; } set { m_loadOrder = value; OnPropertyChanged("LoadOrder"); } } /// /// Gets or sets Enabled /// [DefaultValue(false)] public bool Enabled { get { return m_enabled; } set { m_enabled = value; OnPropertyChanged("Enabled"); } } /// /// Gets or sets IgnoreBadTimeStamps /// [DefaultValue(false)] public bool IgnoreBadTimeStamps { get { return m_ignoreBadTimeStamps; } set { m_ignoreBadTimeStamps = value; OnPropertyChanged("IgnoreBadTimeStamps"); } } /// /// Gets or sets TimeResolution /// [Required(ErrorMessage = "Calculated measurement time resoulution is a required field, please provide value.")] [DefaultValue(10000)] public int TimeResolution { get { return m_timeResolution; } set { m_timeResolution = value; OnPropertyChanged("TimeResolution"); } } /// /// Gets or sets AllowPreemptivePublishing /// [DefaultValue(true)] public bool AllowPreemptivePublishing { get { return m_allowPreemptivePublishing; } set { m_allowPreemptivePublishing = value; OnPropertyChanged("AllowPreemptivePublishing"); } } /// /// Gets or sets DownsamplingMethod /// [StringLength(15, ErrorMessage = "Calculated measurement name cannot exceed 15 characters.")] [DefaultValue("LastReceived")] public string DownsamplingMethod { get { return m_downsamplingMethod; } set { m_downsamplingMethod = value; OnPropertyChanged("DownsamplingMethod"); } } /// /// Gets NodeName /// public string NodeName { get { return m_nodeName; } } /// /// Gets or sets PerformTimestampReasonabilityCheck /// [DefaultValue(true)] public bool PerformTimestampReasonabilityCheck { get { return m_performTimestampReasonabilityCheck; } set { m_performTimestampReasonabilityCheck = value; OnPropertyChanged("PerformTimestampReasonabilityCheck"); } } /// /// Gets or sets CreatedOn /// // Field is populated by database via trigger and has no screen interaction, so no validation attributes are applied public DateTime CreatedOn { get { return m_createdOn; } set { m_createdOn = value; } } /// /// Gets or sets CreatedBy /// // Field is populated by database via trigger and has no screen interaction, so no validation attributes are applied public string CreatedBy { get { return m_createdBy; } set { m_createdBy = value; } } /// /// Gets or sets UpdatedOn /// // Field is populated by database via trigger and has no screen interaction, so no validation attributes are applied public DateTime UpdatedOn { get { return m_updatedOn; } set { m_updatedOn = value; } } /// /// Gets or sets UpdatedBy /// // Field is populated by database via trigger and has no screen interaction, so no validation attributes are applied public string UpdatedBy { get { return m_updatedBy; } set { m_updatedBy = value; } } #endregion #region [ Static ] // Static Methods /// /// LoadKeys information as an style list. /// /// to connection to database. /// The field to sort by. /// ASC or DESC for ascending or descending respectively. /// Collection of . public static IList LoadKeys(AdoDataConnection database, string sortMember = "", string sortDirection = "") { bool createdConnection = false; try { createdConnection = CreateConnection(ref database); IList calculatedMeasurementList = new List(); DataTable calculatedMeasurementTable; string sortClause = string.Empty; if (!string.IsNullOrEmpty(sortMember)) sortClause = string.Format("ORDER BY {0} {1}", sortMember, sortDirection); calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, string.Format("SELECT ID From CalculatedMeasurementDetail {0}", sortClause)); foreach (DataRow row in calculatedMeasurementTable.Rows) { calculatedMeasurementList.Add((row.ConvertField("ID"))); } return calculatedMeasurementList; } finally { if (createdConnection && database != null) database.Dispose(); } } /// /// Loads information as an style list. /// /// to connection to database. /// Keys of the measurement to be loaded from the database /// Collection of . public static ObservableCollection Load(AdoDataConnection database, IList keys) { bool createdConnection = false; try { createdConnection = CreateConnection(ref database); string query; string commaSeparatedKeys; CalculatedMeasurement[] calculatedMeasurementList = null; DataTable calculatedMeasurementTable; int id; if ((object)keys != null && keys.Count > 0) { commaSeparatedKeys = keys.Select(key => key.ToString()).Aggregate((str1, str2) => str1 + "," + str2); query = string.Format("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); calculatedMeasurementList = new CalculatedMeasurement[calculatedMeasurementTable.Rows.Count]; foreach (DataRow row in calculatedMeasurementTable.Rows) { id = row.ConvertField("ID"); calculatedMeasurementList[keys.IndexOf(id)] = new CalculatedMeasurement() { NodeID = database.Guid(row, "NodeID"), ID = id, Acronym = row.Field("Acronym"), Name = row.Field("Name"), AssemblyName = row.Field("AssemblyName"), TypeName = row.Field("TypeName"), ConnectionString = row.Field("ConnectionString"), ConfigSection = row.Field("ConfigSection"), InputMeasurements = row.Field("InputMeasurements"), OutputMeasurements = row.Field("OutputMeasurements"), MinimumMeasurementsToUse = row.ConvertField("MinimumMeasurementsToUse"), FramesPerSecond = Convert.ToInt32(row.Field("FramesPerSecond") ?? 30), LagTime = row.ConvertField("LagTime"), LeadTime = row.ConvertField("LeadTime"), UseLocalClockAsRealTime = Convert.ToBoolean(row.Field("UseLocalClockAsRealTime")), AllowSortsByArrival = Convert.ToBoolean(row.Field("AllowSortsByArrival")), LoadOrder = row.ConvertField("LoadOrder"), Enabled = Convert.ToBoolean(row.Field("Enabled")), IgnoreBadTimeStamps = Convert.ToBoolean(row.Field("IgnoreBadTimeStamps")), TimeResolution = Convert.ToInt32(row.Field("TimeResolution")), AllowPreemptivePublishing = Convert.ToBoolean(row.Field("AllowPreemptivePublishing")), DownsamplingMethod = row.Field("DownSamplingMethod"), m_nodeName = row.Field("NodeName"), PerformTimestampReasonabilityCheck = Convert.ToBoolean(row.Field("PerformTimeReasonabilityCheck")) }; } } return new ObservableCollection(calculatedMeasurementList ?? new CalculatedMeasurement[0]); } finally { if (createdConnection && database != null) database.Dispose(); } } /// /// Gets a style list of information. /// /// to connection to database. /// Indicates if selection on UI is optional for this collection. /// containing ID and Name of companies defined in the database. public static Dictionary GetLookupList(AdoDataConnection database, bool isOptional = false) { bool createdConnection = false; try { createdConnection = CreateConnection(ref database); Dictionary calculatedMeasurementList = new(); if (isOptional) calculatedMeasurementList.Add(0, "Select CalculatedMeasurement"); DataTable calculatedMeasurementTable = database.Connection.RetrieveData(database.AdapterType, "SELECT ID, Name FROM CalculatedMeasurement ORDER BY LoadOrder"); foreach (DataRow row in calculatedMeasurementTable.Rows) calculatedMeasurementList[row.ConvertField("ID")] = row.Field("Name"); return calculatedMeasurementList; } finally { if (createdConnection && database != null) database.Dispose(); } } /// /// Saves information to database. /// /// to connection to database. /// Information about . /// String, for display use, indicating success. public static string Save(AdoDataConnection database, CalculatedMeasurement calculatedMeasurement) { bool createdConnection = false; string query; try { createdConnection = CreateConnection(ref database); if (calculatedMeasurement.ID == 0) { query = database.ParameterizedQueryString("INSERT INTO CalculatedMeasurement (NodeID, Acronym, Name, AssemblyName, TypeName, ConnectionString, " + "ConfigSection, InputMeasurements, OutputMeasurements, MinimumMeasurementsToUse, FramesPerSecond, LagTime, LeadTime, UseLocalClockAsRealTime, " + "AllowSortsByArrival, LoadOrder, Enabled, IgnoreBadTimeStamps, TimeResolution, AllowPreemptivePublishing, DownsamplingMethod, " + "PerformTimeReasonabilityCheck, UpdatedBy, UpdatedOn, CreatedBy, CreatedOn) Values ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, " + "{9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}, {23}, {24}, {25})", "nodeID", "acronym", "name", "assemblyName", "typeName", "connectionString", "configSection", "inputMeasurements", "outputMeasurements", "minimumMeasurementsToUse", "framesPerSecond", "lagTime", "leadTime", "useLocalClockAsRealTime", "allowSortsByArrival", "loadOrder", "enabled", "ignoreBadTimeStamps", "timeResolution", "allowPreemptivePublishing", "downsamplingMethod", "performTimeReasonabilityCheck", "updatedBy", "updatedOn", "createdBy", "createdOn"); database.Connection.ExecuteNonQuery(query, DefaultTimeout, database.CurrentNodeID(), calculatedMeasurement.Acronym.Replace(" ", "").ToUpper(), calculatedMeasurement.Name.ToNotNull(), calculatedMeasurement.AssemblyName, calculatedMeasurement.TypeName, calculatedMeasurement.ConnectionString.ToNotNull(), calculatedMeasurement.ConfigSection.ToNotNull(), calculatedMeasurement.InputMeasurements.ToNotNull(), calculatedMeasurement.OutputMeasurements.ToNotNull(), calculatedMeasurement.MinimumMeasurementsToUse, calculatedMeasurement.FramesPerSecond, calculatedMeasurement.LagTime, calculatedMeasurement.LeadTime, database.Bool(calculatedMeasurement.UseLocalClockAsRealTime), database.Bool(calculatedMeasurement.AllowSortsByArrival), calculatedMeasurement.LoadOrder, database.Bool(calculatedMeasurement.Enabled), database.Bool(calculatedMeasurement.IgnoreBadTimeStamps), calculatedMeasurement.TimeResolution, database.Bool(calculatedMeasurement.AllowPreemptivePublishing), calculatedMeasurement.DownsamplingMethod, database.Bool(calculatedMeasurement.PerformTimestampReasonabilityCheck), CommonFunctions.CurrentUser, database.UtcNow, CommonFunctions.CurrentUser, database.UtcNow); } else { query = database.ParameterizedQueryString("UPDATE CalculatedMeasurement SET NodeID = {0}, Acronym = {1}, Name = {2}, AssemblyName = {3}, " + "TypeName = {4}, ConnectionString = {5}, ConfigSection = {6}, InputMeasurements = {7}, OutputMeasurements = {8}, MinimumMeasurementsToUse = {9}, " + "FramesPerSecond = {10}, LagTime = {11}, LeadTime = {12}, UseLocalClockAsRealTime = {13}, AllowSortsByArrival = {14}, LoadOrder = {15}, " + "Enabled = {16}, IgnoreBadTimeStamps = {17}, TimeResolution = {18}, AllowPreemptivePublishing = {19}, DownsamplingMethod = {20}, " + "PerformTimeReasonabilityCheck = {21}, UpdatedBy = {22}, UpdatedOn = {23} WHERE ID = {24}", "nodeID", "acronym", "name", "assemblyName", "typeName", "connectionString", "configSection", "inputMeasurements", "outputMeasurements", "minimumMeasurementsToUse", "framesPerSecond", "lagTime", "leadTime", "useLocalClockAsRealTime", "allowSortsByArrival", "loadOrder", "enabled", "ignoreBadTimeStamps", "timeResolution", "allowPreemptivePublishing", "downsamplingMethod", "performTimeReasonabilityCheck", "updatedBy", "updatedOn", "id"); database.Connection.ExecuteNonQuery(query, DefaultTimeout, database.Guid(calculatedMeasurement.NodeID), calculatedMeasurement.Acronym.Replace(" ", "").ToUpper(), calculatedMeasurement.Name.ToNotNull(), calculatedMeasurement.AssemblyName, calculatedMeasurement.TypeName, calculatedMeasurement.ConnectionString.ToNotNull(), calculatedMeasurement.ConfigSection.ToNotNull(), calculatedMeasurement.InputMeasurements.ToNotNull(), calculatedMeasurement.OutputMeasurements.ToNotNull(), calculatedMeasurement.MinimumMeasurementsToUse, calculatedMeasurement.FramesPerSecond, calculatedMeasurement.LagTime, calculatedMeasurement.LeadTime, database.Bool(calculatedMeasurement.UseLocalClockAsRealTime), database.Bool(calculatedMeasurement.AllowSortsByArrival), calculatedMeasurement.LoadOrder, database.Bool(calculatedMeasurement.Enabled), database.Bool(calculatedMeasurement.IgnoreBadTimeStamps), calculatedMeasurement.TimeResolution, database.Bool(calculatedMeasurement.AllowPreemptivePublishing), calculatedMeasurement.DownsamplingMethod, database.Bool(calculatedMeasurement.PerformTimestampReasonabilityCheck), CommonFunctions.CurrentUser, database.UtcNow, calculatedMeasurement.ID); } return "Calculated measurement information saved successfully"; } finally { if (createdConnection && database != null) database.Dispose(); } } /// /// Deletes specified record from database. /// /// to connection to database. /// ID of the record to be deleted. /// String, for display use, indicating success. public static string Delete(AdoDataConnection database, int calculatedMeasurementID) { bool createdConnection = false; try { createdConnection = CreateConnection(ref database); // Setup current user context for any delete triggers CommonFunctions.SetCurrentUserContext(database); database.Connection.ExecuteNonQuery(database.ParameterizedQueryString("DELETE FROM CalculatedMeasurement WHERE ID = {0}", "calculatedMeasurementID"), DefaultTimeout, calculatedMeasurementID); CommonFunctions.SendCommandToService("ReloadConfig"); return "Calculated measurement deleted successfully"; } finally { if (createdConnection && database != null) database.Dispose(); } } #endregion } }