using System; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace DatabaseExport { public class DbOperations { public abstract class Tags { public const string Table = "tblTags"; public enum TagFields { TagId, TagText, Obsolete } public const string TAGASSIGNMENTS_TABLE = "TagAssignments"; public enum TagAssignmentFields { ObjectID, ObjectType, TagID } } public abstract class DbVersions { public enum DbVersionFields { Version, Step, Date, Remarks, UserField } } public static System.Data.SqlClient.SqlCommand GetSQLCommand() { return GetSQLCommand(false); } public static System.Data.SqlClient.SqlCommand GetSQLCommand(bool newCommand) { if (_cmd == null) { _cmd = new System.Data.SqlClient.SqlCommand(); } var currentCmd = _cmd; if (newCommand) { currentCmd = new System.Data.SqlClient.SqlCommand(); } if (currentCmd.Connection == null || currentCmd.Connection.State != ConnectionState.Open) { currentCmd.Connection = new System.Data.SqlClient.SqlConnection(Connection.GetLocalConnectionString()); currentCmd.Connection.Open(); } currentCmd.Parameters.Clear(); return currentCmd; } private static System.Data.SqlClient.SqlCommand _cmd = null; public abstract class Settings { public const string Table = "tblSettings"; public enum UserFields { PropertyId, PropertyType, PropertyValue, UserId } } /// /// tables and fields for user objects /// public abstract class Users { public const string USERS_TABLE = "DataPROUsers"; public enum UserFields { ID, UserName, DisplayName, Password, Role, LastModified, LastModifiedBy, LocalOnly } public const string UIITEMS_TABLE = "UIITEMS"; public enum UIItemFields { ID, Name } public const string USERUISETTINGS_TABLE = "UserUIItemSettings"; public enum UserUIItemSettingFields { UserId, UIItemID, Permission, Visible } } public abstract class SensorDB { public const string SensorCalibrationTable = "tblSensorCalibrations"; public const string SensorDataTable = "tblSensors"; public const string SensorModelsTable = "tblSensorModels"; public enum SensorDataFields { SerialNumber = 1, UserSerialNumber, Model, Manufacturer, Status, MeasurementUnit, OffsetToleranceLow, OffsetToleranceHigh, Id, Capacity, Comment, BridgeType, BridgeLegMode, Shunt, Invert, UserValue1, UserValue2, UserValue3, FilterClass, BridgeResistance, IsoCode, CheckOffset, SupportedExcitation, InitialEU, CalInterval, CalibrationSignal, InternalShuntResistance, ExternalShuntResistance, UniPolar, RangeLow, RangeAve, RangeHigh, Created, TimesUsed, SensorCategory, BypassFilter, CouplingMode, Version, LastModified, ModifiedBy, LocalOnly, AxisNumber, NumberOfAxes, UserTags, DoNotUse, Broken } public enum SensorModelFields { Model, Manufacturer, UserPartNumber, Capacity, OffsetToleranceLow, OffsetToleranceHigh, MeasurementUnit, Bridge, Shunt, BridgeResistance, FilterClass, UniPolar, IgnoreRange, CouplingMode, Version, RangeLow, RangeAve, RangeHigh, LastModified, ModifiedBy, LocalOnly, NumberOfAxes, CalInterval, AxisNumber, Polarity, Invert, CheckOffset, CalibrationRecord, ISOCode, SupportedExcitation } public enum SensorCalibrationFields { SerialNumber, CalibrationDate, Username, LocalOnly, NonLinear, CalibrationRecords, ModifyDate, IsProportional, RemoveOffset, ZeroMethod, CertificationDocuments, InitialOffset } } public class DbTypeAttr : Attribute { public string DbType { get; private set; } internal DbTypeAttr(string attr) { DbType = attr; } public static string GetDbType(object o) { if (o != null) { System.Reflection.MemberInfo[] mi = o.GetType().GetMember(o.ToString()); if (mi != null && mi.Length > 0) { if (GetCustomAttribute(mi[0], typeof(DbTypeAttr)) is DbTypeAttr attr) { return attr.DbType; } } } return null; } } public abstract class CalculatedChannels { public const string Table = "tblCalculatedChannels"; public enum Fields { [DbTypeAttr("INTEGER PRIMARY KEY NOT NULL")] Id, [DbTypeAttr("INTEGER")] Operation, [DbTypeAttr("NVARCHAR(255)")] CalculatedChannelValueCode, [DbTypeAttr("BLOB")] InputChannelIds, [DbTypeAttr("NVARCHAR(255)")] CFCForInputChannels, [DbTypeAttr("NVARCHAR(255)")] CFCForOutput, [DbTypeAttr("NVARCHAR(255)")] TestSetupName, [DbTypeAttr("NVARCHAR(255)")] CCName } } public abstract class LevelTriggers { public const string Table = "tblLevelTriggers"; public enum Fields { [DbTypeAttr("NVARCHAR(255) NOT NULL")] TestSetupName, [DbTypeAttr("NVARCHAR(255) NOT NULL")] GroupSerialNumber, [DbTypeAttr("NVARCHAR(255) NOT NULL")] TestObjectChannelId, [DbTypeAttr("NVARCHAR(255) NOT NULL")] HardwareChannelId, [DbTypeAttr("NVARCHAR(255) NOT NULL")] SensorSerialNumber, [DbTypeAttr("BIT NOT NULL")] GreaterThanEnabled, [DbTypeAttr("FLOAT NOT NULL")] GreaterThanEU, [DbTypeAttr("BIT NOT NULL")] LessThanEnabled, [DbTypeAttr("FLOAT NOT NULL")] LessThanEU, [DbTypeAttr("FLOAT NULL")] InsideUpperEU, [DbTypeAttr("FLOAT NULL")] InsideLowerEU, [DbTypeAttr("FLOAT NULL")] OutsideUpperEU, [DbTypeAttr("FLOAT NULL")] OutsideLowerEU, [DbTypeAttr("BIT NULL")] TriggerInside, [DbTypeAttr("BIT NULL")] TriggerOutside }; } public abstract class TestSetups { public const string HardwareTable = "tblTestSetupHardware"; public enum HardwareFields { TestSetupName, HardwareId, AddOrRemove //0=remove,1=add } public const string DASSettingsTable = "tblTestSetupDASSettings"; public const string ChannelSettingsTable = "tblTestChannelSettings"; public enum ChannelSettingFields { TestName, TestObjectName, ChannelId, Setting, SensorSerial } public const string TestSetupsTable = "tblTestSetups"; public enum Fields { SetupName, SetupDescription, AutomaticTestProgression, AutomaticProgressionDelayMS, InvertTrigger, InvertStart, ViewDiagnostics, VerifyChannels, AutoVerifyChannels, VerifyChannelsDelayMS, RecordingMode, SamplesPerSecond, PreTriggerSeconds, PostTriggerSeconds, StrictDiagnostics, RequireConfirmationOnErrors, ROIDownload, ViewROIDownload, DownloadAll, ViewRealtime, RealtimePlotCount, ROIStart, ROIEnd, ViewDownloadAll, Export, ExportFormat, LabDetails, UseLabDetails, CustomerDetails, UseCustomerDetails, AllowMissingSensors, AllowSensorIdToBlankChannel, LocalOnly, LastModified, LastModifiedBy, TurnOffExcitation, TriggerCheckRealtime, TriggerCheckStep, PostTestDiagnostics, ExportFolder, DownloadFolder, CommonStatusLine, SameAsDownloadFolder, UploadData, UploadDataFolder, Settings, WarnOnBatteryFail, Dirty, Complete, ErrorMessage, TestEngineerDetails, UseTestEngineerDetails, UserTags, DoAutoArm, DoStreaming, CheckoutMode, QuitTestWithoutWarning, SuppressMissingSensorsWarning, ISFFile, NotAllChannelsRealTime, NotAllChannelsViewer } public const string TestSetupObjectsTable = "tblTestSetupObjects"; public enum TestSetupObjectFields { TestObjectSerialNumber, TestSetupName, TargetSampleRate, ExcitationWarmupTimeMS, LocalOnly, TestObjectType, TestObjectPosition } public const string TestObjectMetaDataTable = "tblTestSetupObjectMetaData"; public enum TestObjectMetaDataFields { TestObject, SetupName, PropName, PropValue, Optional, Version } public const string TestObjectTemplatesTable = "tblTestObjectTemplates"; public enum TestObjectTemplatesFields { TemplateName, Icon, Description, LocalOnly, Version, LastModifiedBy, CRC32, TestObject, LastModified, ParentTemplate, SysBuilt } public const string TestObjectsTable = "tblTestObjects"; public enum TestObjectsFields { SerialNumber, LastModifiedBy, LastModified, Template, LocalOnly, ParentObject, SysBuilt, Embedded, OriginalTemplate, OriginalSerialNumber } public const string TestGraphsTable = "tblTestGraphs"; public enum GraphFields { GraphName, GraphDescription, TemplateName, Channels, UseDomainMin, DomainMin, UseDomainMax, DomainMax, UseRangeMin, RangeMin, UseRangeMax, RangeMax, Thresholds, LocalOnly } public enum TestSetupDASSettingsFields { DASSerialNumber, TestSetupName, TargetSampleRate, ExcitationWarmupTimeMS, AAFilterRate, PreTriggerSeconds, PostTriggerSeconds, StatusLineCheck, BatteryCheck, InputVoltageMin, InputVoltageMax, BatteryVoltageMin, BatteryVoltageMax, LocalOnly } } public abstract class TestObjectChannelSettings { public const string TableName = "tblTestObjectChannelSettings"; public enum Fields { TestObjectSerial, ChannelId, Setting, SensorSerial } } public abstract class DigitalOutputSettings { public const string Table = "tblTOMDigitalChannels"; public enum Fields { ChannelDescription, DelayMS, DurationMS, OutputMode, LimitDuration, LastModified, LastModifiedBy, Version, LocalOnly, DurationMSFloat, UserTags } } public abstract class Squib { public const string Table = "tblTOMSquibChannels"; public enum Fields { SquibDescription, BypassCurrentFilter, BypassVoltageFilter, DelayMS, DurationMS, FireMode, ISOCode, MeasurementType, SquibOutputCurrent, SquibToleranceLow, SquibToleranceHigh, LimitDuration, ArticleId, LocalOnly, Version, LastModified, LastModifiedBy, UserValue1, UserValue2, UserValue3, UserTags } } public class MMETables { public const string MyType = "MyType"; //This was exported in all versions up to 1.3.496 and was replaced by "CustomChannelType" public const string CustomChannelType = "CustomChannelType"; //This was exported in versions from 1.3.498 - 1.3.515 and was replaced by "TYPE" public const string Id = "Id"; //This was exported in all versions up to 1.3.515 and was replaced by "ID" public const string MMEPossibleChannelsTable = "tblMMEPossibleChannels"; public enum MMEPossibleChannelsFields { ID, TYPE, [CustomChannelFieldSizeAttribute(50)] TEST_OBJECT, [CustomChannelFieldSizeAttribute(50)] POSITION, [CustomChannelFieldSizeAttribute(50)] TRANS_MAIN_LOC, [CustomChannelFieldSizeAttribute(50)] FINE_LOC_1, [CustomChannelFieldSizeAttribute(50)] FINE_LOC_2, [CustomChannelFieldSizeAttribute(50)] FINE_LOC_3, [CustomChannelFieldSizeAttribute(50)] PHYSICAL_DIMENSION, [CustomChannelFieldSizeAttribute(50)] DIRECTION, [CustomChannelFieldSizeAttribute(50)] DEFAULT_FILTER_CLASS, [CustomChannelFieldSizeAttribute(100)] TEXT_L1, [CustomChannelFieldSizeAttribute(100)] TEXT_L2, VERSION, DATE, [CustomChannelFieldSizeAttribute(50)] REMARKS, EXPIRED, [CustomChannelFieldSizeAttribute(50)] SORTKEY, [CustomChannelFieldSizeAttribute(50)] PICTURE_SHORTNAME, [CustomChannelFieldSizeAttribute(50)] LAST_CHANGE, [CustomChannelFieldSizeAttribute(50)] LAST_CHANGE_TEXT, [CustomChannelFieldSizeAttribute(50)] HISTORY } public const string MMEDirectionsTable = "tblMMEDirections"; public enum MMEDirectionsFields { s_GUID, DIRECTION, TEXT_L1, TEXT_L2, DATE, VERSION, EXPIRED, REMARKS, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY, SORTKEY } public const string MMEFilterClassesTable = "tblMMEFilterClasses"; public enum MMEFilterClassesFields { s_GUID, FILTER_CLASS, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEFineLocations1Table = "tblMMEFineLocations1"; public enum MMEFineLocations1Fields { s_GUID, FINE_LOC_1, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEFineLocations2Table = "tblMMEFineLocations2"; public enum MMEFineLocations2Fields { s_GUID, FINE_LOC_2, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEFineLocations3Table = "tblMMEFineLocations3"; public enum MMEFineLocations3Fields { s_GUID, FINE_LOC_3, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, PICTURE_SHORTNAME, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEPhysicalDimensions = "tblMMEPhysicalDimensions"; public enum MMEPhysicalDimensionFields { s_GUID, PHYSICAL_DIMENSION, TEXT_L1, TEXT_L2, DEFAULT_UNIT, LENGTH_EXP, TIME_EXP, MASS_EXP, ELECTRIC_CURRENT_EXP, TEMPERATURE_EXP, LUMINOUS_INTENSITY_EXP, AMOUNT_OFSUBSTANCE_EXP, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEPositionsTable = "tblMMEPositions"; public enum MMEPositionsFields { s_GUID, POSITION, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMETestObjectsTable = "tblMMETestObjects"; public enum MMETestObjectsFields { s_GUID, TEST_OBJECT, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } public const string MMEMainLocationTable = "tblMMEMainLocations"; public enum MMEMainLocationsFields { s_GUID, TYPE, TRANS_MAIN_LOC, TEXT_L1, TEXT_L2, VERSION, DATE, REMARKS, EXPIRED, SORTKEY, PICTURE_SHORTNAME, LAST_CHANGE, LAST_CHANGE_TEXT, HISTORY } } public static bool _usingCentralizedDB = true; //True means using a remote, centralized server; False means using a local SqlLocalDb public static bool _usingMSSQL = true; public static bool _usingNTLMAuthentication = false; public static string _previousDir = string.Empty; public class DAS { public const string Table = "tblDAS"; public enum Fields { SerialNumber, Type, MaxModules, MaxMemory, MaxSampleRate, MinSampleRate, FirmwareVersion, CalDate, ProtocolVersion, LastModified, LastModifiedBy, Version, LocalOnly, LastUsed, LastUsedBy, Connection, Channels, Position, ChannelTypes, Reprogramable, Reconfigurable, IsModule } public const string TableDASChannels = "tblDASChannels"; public enum DASChannelFields { HardwareId, ChannelIdx, SupportedBridges, SupportedExcitations, DASDisplayOrder, LocalOnly, SupportedDigitalInputModes, SupportedSquibFireModes, SupportedDigitalOutputModes, ModuleSerialNumber, ModuleArrayIndex } } public static /*System.Data.IDbDataParameter*/ void CreateParam(System.Data.IDbCommand icmd, string name, System.Data.SqlDbType type, object value) { switch (type) { case System.Data.SqlDbType.DateTime: if (null == value) { value = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue; } else if (value is DateTime) { if (((DateTime)value) < (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue) { value = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue; } //value = string.Format("{0:yyyy-MM-dd}", ((DateTime)value)) + " " + ((DateTime)value).ToLongTimeString(); value = string.Format("{0:yyyy-MM-dd} {1}", ((DateTime)value), ((DateTime)value).ToString("HH:mm:ss")); } break; case System.Data.SqlDbType.NVarChar: break; } if (_usingMSSQL) { System.Data.SqlClient.SqlCommand cmd = icmd as System.Data.SqlClient.SqlCommand; var param = new System.Data.SqlClient.SqlParameter(name, type); param.Value = value; icmd.Parameters.Add(param); } else { System.Data.SQLite.SQLiteCommand cmd = icmd as System.Data.SQLite.SQLiteCommand; cmd.Parameters.AddWithValue(name, value); } } // private const string remoteCon = "Persist Security Info=False;Integrated Security=SSPI;database=DATA_PRO;server=192.168.2.101"; public static IDbCommand GetISOCommand() { var cmd = new SqlCommand(); cmd.Connection = new SqlConnection(Connection.GetLocalISOConnectionString()); cmd.Connection.Open(); return cmd; } public static IDbCommand GetCommand() { if (_usingMSSQL) { return new System.Data.SqlClient.SqlCommand(); } else { return new System.Data.SQLite.SQLiteCommand(); } } // public static System.Data.IDbCommand GetSQLOnlyCommand() // { // return new System.Data.SqlClient.SqlCommand(); // } private string _localConnection = null; private string GetLocalConnectionString() { lock (dbLock) { if (null != _localConnection) return _localConnection; if (null == Server /*&& !_bCS3*/) { throw new Exception("db connection not initialized"); } _localConnection = string.Format("Server={0};Database={1};Trusted_Connection=TRUE;", Server, DBName); } return _localConnection; } private string _localISOConnection = null; public string GetLocalISOConnectionString() { lock (dbLock) { if (null != _localISOConnection) return _localISOConnection; _localISOConnection = _usingNTLMAuthentication ? $"Server={Server};Database=ISO;Trusted_Connection=TRUE;" : $"Server={Server};Database=ISO;User Id={Username};Password={Password};"; } return _localISOConnection; } public string Server { get; set; } = null; public string DBName { get; set; } = null; public string Username { get; set; } = ""; public string Password { get; set; } private static bool _lastConnectionStatus = false; public static bool LastConnectionStatus { get { lock (dbLock) { return _lastConnectionStatus; } } set { lock (dbLock) { _lastConnectionStatus = value; } ConnectionStatusChanged?.Invoke(value); } } public delegate void ConnectionStatusChangedDelegate(bool connected); private static ConnectionStatusChangedDelegate _ConnectionStatusChange; public static ConnectionStatusChangedDelegate ConnectionStatusChanged { get { lock (dbLock) { return _ConnectionStatusChange; } } set { lock (dbLock) { _ConnectionStatusChange = value; } } } private static DbOperations _dbOperations = null; // private static DbOperations _dbOperationsCS3 = null; private static object dbLock = new object(); public static DbOperations Connection { get { lock (dbLock) { if (null == _dbOperations) { _dbOperations = new DbOperations(); } } return _dbOperations; } } public const string NoConnection = "NoConnection"; public System.Data.DataSet QueryDataSet(System.Data.IDbCommand icmd) { //try { Log(icmd); } //catch (Exception ex) { APILogger.Log(ex); } if (_usingMSSQL)// || _bCS3) { if (!(icmd is System.Data.SqlClient.SqlCommand cmd)) return null; using (var MsSqlConnection = new System.Data.SqlClient.SqlConnection(GetLocalConnectionString())) { try { MsSqlConnection.Open(); cmd.Connection = MsSqlConnection; LastConnectionStatus = true; } catch (Exception ex) { LastConnectionStatus = false; throw new System.Exception(NoConnection, ex); } using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(cmd)) { var ds = new System.Data.DataSet(); try { adapter.Fill(ds); return ds; } catch (Exception ex) { //Log(icmd, true); throw ex; } } } } string fullDbConnectionPath = System.IO.Path.Combine(_previousDir, "datapro.db"); using (System.Data.SQLite.SQLiteConnection c = new System.Data.SQLite.SQLiteConnection(string.Format("Data Source={0}", fullDbConnectionPath))) { if (c.State == System.Data.ConnectionState.Closed) { try { c.Open(); LastConnectionStatus = true; } catch (Exception ex) { LastConnectionStatus = false; throw new SystemException(NoConnection, ex); } } System.Data.SQLite.SQLiteCommand cmd = icmd as System.Data.SQLite.SQLiteCommand; cmd.Connection = c; using (System.Data.SQLite.SQLiteDataAdapter adapter = new System.Data.SQLite.SQLiteDataAdapter(cmd)) { DataSet ds = new DataSet(); try { adapter.Fill(ds); } catch (Exception) { //Log(icmd, true); //APILogger.Log("Failed to read db", ex); } return ds; } } } public class DigitalInputSettings { public const string Table = "tblDigitalInputSetting"; public enum Fields { SettingName, SettingMode, ScaleMultiplier, LastModified, LastModifiedBy, SensorId, UserValue1, UserValue2, UserValue3, UserTags } } private string _dbConnection = System.IO.Path.Combine("db", "datapro.db"); public int ExecuteCommand(System.Data.IDbCommand icmd) { //try { Log(icmd); } //catch (Exception ex) { APILogger.Log(ex); } if (_usingMSSQL) { System.Data.SqlClient.SqlCommand cmd = icmd as System.Data.SqlClient.SqlCommand; using (var MsSqlConnection = new System.Data.SqlClient.SqlConnection(GetLocalConnectionString())) { try { MsSqlConnection.Open(); cmd.Connection = MsSqlConnection; LastConnectionStatus = true; } catch (Exception ex) { LastConnectionStatus = false; throw new SystemException(NoConnection, ex); } if (cmd != null) { cmd.Connection = MsSqlConnection; } try { return cmd.ExecuteNonQuery(); } catch (Exception ex) { //Log(cmd, true); throw ex; } } } var fullDbConnectionPath = System.IO.Path.Combine(_previousDir, _dbConnection); using (System.Data.SQLite.SQLiteConnection c = new System.Data.SQLite.SQLiteConnection(string.Format("Data Source={0}", fullDbConnectionPath))) { System.Data.SQLite.SQLiteCommand cmd = icmd as System.Data.SQLite.SQLiteCommand; if (c.State == System.Data.ConnectionState.Closed) { try { c.Open(); LastConnectionStatus = true; } catch (Exception ex) { LastConnectionStatus = false; throw new SystemException(NoConnection, ex); } } cmd.Connection = c; try { return cmd.ExecuteNonQuery(); } catch (Exception ex) { //Log(icmd, true); throw ex; } } } public class CustomChannelFieldSizeAttribute : Attribute { internal CustomChannelFieldSizeAttribute(int size) { Size = size; } public int Size { get; private set; } } } }