This commit is contained in:
2026-04-17 14:55:32 -04:00
commit bc3ac1d4c9
18017 changed files with 4371742 additions and 0 deletions

View File

@@ -0,0 +1,688 @@
using DTS.Common.Converters;
using System;
using System.ComponentModel;
using System.IO.Ports;
namespace DTS.Common.Enums.Sensors
{
public abstract class SensorConstants
{
public const string VOLTAGE_INSERTION_UNIT = "mV";
public const string TSRAIR_ACCEL_UNIT = "g";
public const string TSRAIR_ARS_UNIT = "deg/sec";
public const string TSRAIR_TEMPERATURE_UNIT = "C";
public const string TSRAIR_HUMIDITY_UNIT = "%";
public const string TSRAIR_PRESSURE_UNIT = "PSI";
//these are 3D IR-TRACC values for equations
//taken originally from config file for
//http://manuscript.dts.local/f/cases/29720/config-file-properties-not-being-used-in-view-3D-IRTRACC-channel-add
public static double δThorax { get; set; } = 15.65;
public static double δAbdomen { get; set; } = 0;
public static double D0Thorax { get; set; } = 141.8;
public static double D0Abdomen { get; set; } = 150.9;
public static double δThoraxLower { get; set; } = -15.65;
public static double D0ThoraxLower { get; set; } = 141.8;
//EU string for degrees
public const string DEGREES = "deg";
//EUstring for degrees used by GM
public const string DEGREE_ANGLE = "deg-ang";
/// <summary>
/// these are the units we accept when filtering channels for add calculated channel
/// 25513 GM requests option to filter channels available for pots for 3d-IR TRACC to include sensors with "deg-ang"
/// </summary>
public static readonly string[] POTUnits = new[] { DEGREES, DEGREE_ANGLE };
public const double MIN_BRIDGE_RESISTANCE_OHMS = 1;
public const double MAX_BRIDGE_RESISTANCE_OHMS = 32000;
/// <summary>
/// the DEFAULT value for whether sensor calibrations intervals start after calibration or first use
/// </summary>
public const bool SENSOR_FIRST_USE_DEFAULT = false;
/// <summary>
/// the current value for whether sensor calibration intervals start after calibration or first use
/// note does not query the value, just holds the value between different modules
/// </summary>
public static bool UseSensorFirstUseDate { get; set; } = false;
/// <summary>
/// a cached indicator of whether to use isocode filter mapping or not
/// is updated whenever the setting is updated by the application, and on startup
/// </summary>
public static bool UseISOCodeFilterMapping { get; set; } = true;
/// <summary>
/// FB12764 a cached value for default zero method type
/// is updated whenever the setting is updated by the application, and on startup
/// </summary>
public static ZeroMethodType DefaultZeroMethodType { get; set; } = ZeroMethodType.AverageOverTime;
/// <summary>
/// FB12764 a cached value for default window start time, if zero method type is Average Over Time
/// is updated whenever the setting is updated by the application, and on startup
/// </summary>
public static double DefaultZeroMethodStart { get; set; } = -0.05D;
/// <summary>
/// FB12764 a cached value for default window end time, if zero method type is Average Over Time
/// is updated whenever the setting is updated by the application, and on startup
/// </summary>
public static double DefaultZeroMethodEnd{ get; set; } = -0.02D;
/// <summary>
/// 29759 the default range for TSR AIR HiG channels
/// </summary>
public static double DefaultRangeHiG { get; set; } = 400D;
/// <summary>
/// 29759 the default range for TSR AIR LowG channels
/// </summary>
public static double DefaultRangeLowG { get; set; } = 64D;
public static double DefaultRangeLowGDisplay { get; set; } = 50D;
///
/// 29759 the default range for TSR AIR ARS channels
///
public static double DefaultRangeARS { get; set; } = 2000D;
/// <summary>
/// 29917 the default range for the TSR AIR Temperature channel
/// </summary>
public static double DefaultRangeTemperature { get; set; } = 85D;
/// <summary>
/// 29917 the default range for the TSR AIR Humidity channel
/// </summary>
public static double DefaultRangeHumidity { get; set; } = 100D;
/// <summary>
/// 29917 the default range for the TSR AIR Pressure channel
/// </summary>
public static double DefaultRangePressure { get; set; } = 16D; //Actually 15.95 PSI (1100 hPa x 0.0145)
/// <summary>
/// represents the _original_ default for SQUIB DELAY in ms (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double SQUIB_DELAY_CONSTANT = 0D;
/// <summary>
/// represents the _original_ default for whether to limit squib output (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const bool SQUIB_LIMIT_DURATION_CONSTANT = true;
/// <summary>
/// represents the _original_ default for squib output duration (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double SQUIB_DURATION_CONSTANT = 10D;
/// <summary>
/// represents the _original_ default for squib low tolerance (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double SQUIB_LOW_TOLERANCE_CONSTANT = 1D;
/// <summary>
/// represents the _original_ default for squib high tolerance (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// 26826 Max Squib Resistance Limit needs to be raised from 8.0 ohms to 10.0 ohms
/// </summary>
public const double SQUIB_HIGH_TOLERANCE_CONSTANT = 10D;
/// <summary>
/// represents the _original_ default for squib fire mode (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const SquibFireMode SQUIB_FIREMODE_CONSTANT = SquibFireMode.CAP;
/// <summary>
/// represents the _original_ default for squib output current (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double SQUIB_CURRENT_CONSTANT = 1.5D;
/// <summary>
/// represents the _original_ default for digital output mode (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const DigitalOutputModes DIGITALOUT_MODE_CONSTANT = DigitalOutputModes.FVLH;
/// <summary>
/// represents the _original_ default for digital output delay (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double DIGITALOUT_DELAY_CONSTANT = 0D;
/// <summary>
/// represents the _original_ default for digital output limit duration (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const bool DIGITALOUT_LIMITDURATION_CONSTANT = true;
/// <summary>
/// represents the _original_ default for digital output duration (not the default in the db)
/// used for restoring defaults
/// 13677 Restore defaults page button not functional for sensor settings nav step in system settings tile.
/// </summary>
public const double DIGITALOUT_DURATION_CONSTANT = 10D;
/// <summary>
/// represents the _original_ default for uart baud rate (not the default in the db)
/// used for restoring defaults
/// </summary>
public const uint UART_BAUDRATE_CONSTANT = 57600;
/// <summary>
/// represents the _original_ default for uart data bits (not the default in the db)
/// used for restoring defaults
/// </summary>
public const uint UART_DATABITS_CONSTANT = 8;
/// <summary>
/// represents the _original_ default for uart stop bits (not the default in the db)
/// used for restoring defaults
/// </summary>
public const StopBits UART_STOPBITS_CONSTANT = StopBits.One;
/// <summary>
/// represents the _original_ default for uart parity (not the default in the db)
/// used for restoring defaults
/// </summary>
public const Parity UART_PARITY_CONSTANT = Parity.None;
/// <summary>
/// represents the _original_ default for uart flow control (not the default in the db)
/// used for restoring defaults
/// </summary>
public const Handshake UART_FLOWCONTROL_CONSTANT = Handshake.None;
/// <summary>
/// represents the _original_ default for uart data format (not the default in the db)
/// used for restoring defaults
/// </summary>
public const UartDataFormat UART_DATAFORMAT_CONSTANT = UartDataFormat.Binary;
/// <summary>
/// represents the _original_ default for stream input udp address (not the default in the db)
/// used for restoring defaults
/// </summary>
public const string STREAMIN_ADDRESS_CONSTANT = "UDP://239.1.2.10:8400";
/// <summary>
/// represents the _original_ default for stream output udp profile (not the default in the db)
/// used for restoring defaults
/// </summary>
public const UDPStreamProfile STREAMOUT_PROFILE_CONSTANT = UDPStreamProfile.CH10_PCM_128BIT_2HDR;
/// <summary>
/// represents the _original_ default for stream output udp address (not the default in the db)
/// used for restoring defaults
/// </summary>
public const string STREAMOUT_ADDRESS_CONSTANT = "UDP://239.1.2.10:8400";
/// <summary>
/// represents the _original_ default for stream output time channel id (not the default in the db)
/// used for restoring defaults
/// </summary>
public const ushort STREAMOUT_TIME_CHID_CONSTANT = 1;
/// <summary>
/// represents the _original_ default for stream output data channel id (not the default in the db)
/// used for restoring defaults
/// </summary>
public const ushort STREAMOUT_DATA_CHID_CONSTANT = 3;
/// <summary>
/// represents the _original_ default for stream output TmNS configuration (not the default in the db)
/// used for restoring defaults
/// </summary>
public const string STREAMOUT_TMNS_CONFIG_CONSTANT = "(1,6,60,0,0,0,0,0)";
/// <summary>
/// represents the _original_ default for stream output irig time data packet interval (in milliseconds) (not the default in the db)
/// used for restoring defaults
/// </summary>
public const ushort STREAMOUT_IRIG_TDP_INTERVAL_CONSTANT = 500;
public const string TEST_SPECIFIC_DOUT = "TSD_";
public const string TEST_SPECIFIC_SQUIB = "TSQ_";
public const string TEST_SPECIFIC_DIN = "TSI_";
public const string TEST_SPECIFIC_EMB = "TSA_";
public const string TEST_SPECIFIC_EMB_CLK = "TSC_";
public const string TEST_SPECIFIC_UART = "TSU_";
public const string TEST_SPECIFIC_STREAM_OUT = "TSS_";
public const string TEST_SPECIFIC_STREAM_IN = "TSN_";
public const string TEST_SPECIFIC_DIGITAL_IN_SERIAL = "TSI_TestSpecific";
public const string TEST_SPECIFIC_DIGITAL_OUT_SERIAL = "TSD_TestSpecific";
public const string TEST_SPECIFIC_SQUIB_SERIAL = "TSQ_TestSpecific";
public const string TEST_SPECIFIC_ANALOG_SERIAL = "TSA_Embedded";
public const string TEST_SPECIFIC_CLOCK_SERIAL = "TSC_Embedded";
public const string TEST_SPECIFIC_UART_SERIAL = "TSU_TestSpecific";
public const string TEST_SPECIFIC_STREAM_OUT_SERIAL = "TSS_TestSpecific";
public const string TEST_SPECIFIC_STREAM_IN_SERIAL = "TSN_TestSpecific";
public const string VOLTAGE_INPUT = "Voltage input";
public static bool IsTestSpecificDigitalOut(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_DOUT)) return false;
return true;
}
public static bool IsTestSpecificSquib(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_SQUIB)) return false;
return true;
}
/// <summary>
/// returns true if the serial number belongs to a test specific digital input
/// </summary>
public static bool IsTestSpecificDigitalIn(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if( !sn.StartsWith(TEST_SPECIFIC_DIN)) return false;
return true;
}
public static bool IsTestSpecificEmbedded(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_EMB)) return false;
return true;
}
public static bool IsTestSpecificEmbeddedClock(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_EMB_CLK)) return false;
return true;
}
public static bool IsTestSpecificStreamOut(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_STREAM_OUT)) return false;
return true;
}
public static bool IsTestSpecificStreamIn(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_STREAM_IN)) return false;
return true;
}
public static bool IsTestSpecificUart(string sn)
{
if (string.IsNullOrWhiteSpace(sn))
{
return false;
}
if (!sn.StartsWith(TEST_SPECIFIC_UART)) return false;
return true;
}
public const string EditObjectSensorChannelDragFormat = "EditObjectSensorsChannelTable.UserData []";
public enum SensorSettings
{
Range,
CFC,
Polarity,
Position,
LimitDuration, //deprecated in 2.1
Duration, //deprecated in 2.1
Delay, //deprecated in 2.1
OutputMode,
SQMode,
DIMode,
DefaultValue,
ActiveValue, //12 LAST value in V2.0 settings
//new in 2.1
SquibLimitDuration,
SquibDuration,
SquibDelay,
DigitalOutLimitDuration,
DigitalOutDuration,
DigitalOutDelay,
SquibCurrent,
//new in 3.0
ZeroMethod,
ZeroMethodStart,
ZeroMethodEnd,
UserValue1,
UserValue2,
UserValue3,
InitialOffset,
//FB 13120 added filter class
FilterClass,
//new in 4.0
//18363 Uart Channels
UartBaudRate,
UartDataBits,
UartStopBits,
UartParity,
UartFlowControl,
UartDataFormat,
//18364 Stream Out Channels
StreamOutUDPProfile,
StreamOutUDPAddress,
StreamOutUDPTimeChannelId,
StreamOutUDPDataChannelId,
StreamOutUDPTmNSConfig,
StreamOutIRIGTimeDataPacketIntervalMs,
//26828 Stream In Channels
StreamInUDPAddress,
//29760 Implement ACCoupleEnable
ACCouplingEnabled,
//33145 Voltage insertion channel should be half-bridge
BridgeType
}
public enum SensorType
{
Analog,
DigitalIn,
DigitalOut,
Squib,
Clock,
UART,
StreamOut,
StreamIn
}
/// <summary>
/// Separator for encoding an added linear calibration with a non-linear calibrated sensor
/// </summary>
public const string LinearValuesSeparator = "||";
/// <summary>
/// used to convert between different formats and SensivityUnits
/// 14448 Error when trying to import sensors.
/// </summary>
public abstract class SensUnitStringConverter
{
public static SensUnits ConvertFromString(string s)
{
s = s.Trim().ToLower();
switch (s)
{
case "none": return SensUnits.NONE;
case "mv": return SensUnits.mV;
case "mv/v":
case "mvperv":
return SensUnits.mVperV;
case "mv/v/eu":
case "mvpervpereu":
return SensUnits.mVperVperEU;
case "mv/eu":
case "mvpereu":
return SensUnits.mVperEU;
default: throw new InvalidCastException($"Can't convert {s} to SensUnits");
}
}
}
/// <summary>
/// All available Sensitivity Unit types.
/// </summary>
public enum SensUnits
{
/// <summary>
/// No Sensitivity Units (Polynomial Sensor)
/// </summary>
[Description("NONE")] NONE = 0,
/// <summary>
/// Sensitivity expressed in mV with output at Capacity EU
/// </summary>
[Description("mV")] mV = 1,
/// <summary>
/// Excitation proportional sensitivity expressed in mV/V with output at Capacity EU
/// </summary>
[Description("mV/V")] mVperV = 2,
/// <summary>
/// Excitation proportional sensitivity expressed in mV/V/EU
/// </summary>
[Description("mV/V/EU")] mVperVperEU = 3,
/// <summary>
/// Sensitivity expressed in mV/EU
/// </summary>
[Description("mV/EU")] mVperEU = 4
}
/// <summary>
/// All available bridge types.
/// </summary>
public enum BridgeType
{
/// <summary>
/// sensor uses IEPE setup
/// </summary>
[Description("IEPE")] IEPE = 1 << 0,
/// <summary>
/// sensor uses quarter bridge setup
/// </summary>
[Description("Quarter")] QuarterBridge = 1 << 1,
/// <summary>
/// sensor uses half bridge setup
/// </summary>
[Description("Bridge-Half")] HalfBridge = 1 << 2,
/// <summary>
/// sensor has a full bridge setup
/// </summary>
[Description("Bridge-Full")] FullBridge = 1 << 3,
/// <summary>
/// digital input setup
/// </summary>
[Description("DigitalInput")] DigitalInput = 1 << 4,
/// <summary>
/// squib output setup
/// </summary>
[Description("SQUIB")] SQUIB = 1 << 5,
/// <summary>
/// digital output setup
/// </summary>
[Description("TOMDigital")] TOMDigital = 1 << 6,
/// <summary>
/// sensor uses a G5 (signal plus) half bridge setup
/// </summary>
[Description("Bridge-Half SigPlus")] HalfBridge_SigPlus = 1 << 7,
/// <summary>
/// not a "sensor" but encoding the RTC
/// </summary>
[Description("RTC")] RTC = 1 << 8,
/// <summary>
/// not a "sensor" but values recorded on UART
/// </summary>
[Description("UART")] UART = 1 << 9,
/// <summary>
/// not a "sensor" but values sent out via stream
/// </summary>
[Description("StreamOut")] StreamOut = 1 << 10,
/// <summary>
/// not a "sensor" but values received via stream
/// </summary>
[Description("StreamIn")] StreamIn = 1 << 11
}
public static BridgeType ConvertIntToBridgeType(int bridge)
{
switch (bridge)
{
case 0: return BridgeType.IEPE;
case 4: return BridgeType.HalfBridge_SigPlus;
case 3: return BridgeType.FullBridge;
case 2: return BridgeType.HalfBridge;
case 1: return BridgeType.QuarterBridge;
case 8: return BridgeType.RTC;
default: return BridgeType.FullBridge;
}
}
/// <summary>
/// this is apparently needed for historical reasons
/// as the sensor db apparently doesn't use the bitmask value for storage?
/// </summary>
/// <param name="bridge"></param>
/// <returns></returns>
public static int ConvertBridgeToInt(BridgeType bridge)
{
switch (bridge)
{
case BridgeType.IEPE: return 0;
case BridgeType.QuarterBridge: return 1;
case BridgeType.HalfBridge: return 2;
case BridgeType.FullBridge: return 3;
case BridgeType.HalfBridge_SigPlus: return 4;
case BridgeType.RTC: return 8;
default: return 3;
}
}
/// <summary>
/// how to handle sensor calibrations that are out of date
/// 1) always allow sensors in a data collection, just warn
/// 2) don't allow sensors which are out of date, warn if near out of date
/// </summary>
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum SensorCalPolicy
{
[Description("SENSOR_CAL_POLICY_ALLOW_ALWAYS")]
AllowAlways,
[Description("SENSOR_CAL_POLICY_DONT_ALLOW")]
DONT_ALLOW
}
/// <summary>
/// allows for this field to be cached without having to be retrieved when processing a lot of channels
/// </summary>
public static int SensorCalOutOfDateWarningPeriodDays = 14;
public static SensorCalPolicy SensorCalPolicyCurrent = SensorCalPolicy.DONT_ALLOW;
/// <summary>
/// the default policy for sensors is to not allow out of cal sensors
/// </summary>
public const SensorCalPolicy CAL_SENSOR_POLICY_DEFAULT = SensorCalPolicy.DONT_ALLOW;
/// <summary>
/// default warning period for sensors for calibration (in days)
/// </summary>
public const int CAL_SENSOR_POLICY_WARNING_DAYS_DEFAULT = 14;
public enum CouplingModes
{
AC=0,
DC
}
/// <summary>
/// signifies whether autosense for IEPE/analog will be performed
/// this variable only holds the value for the property, it does not
/// serialize, deserialize, the property must be set by any using
/// applications first
/// </summary>
public static bool DisableAutoSense{ get; set; }
// FB16524: diagnostic result should include the resting voltage of an IEPE sensor
// http://manuscript.dts.local/f/cases/16524/diagnostic-result-should-include-the-resting-voltage-of-an-IEPE-sensor
public static double DefaultBridgeOffsetMVTolLow { get; set; } = -100;
public static double DefaultBridgeOffsetMVTolHigh { get; set; } = 100;
public static double DefaultIEPEOffsetMVTolLow { get; set; } = -2000;
public static double DefaultIEPEOffsetMVTolHigh { get; set; } = 2000;
//ARS valid ranges for TSR AIR
private const int ARS2000 = 2000;
private const int ARS250 = 250;
public const int ARSMax = 2000;
public const int ARSMin = 250;
//LowG valid ranges for TSR AIR
private const int LowG64 = 64;
private const int LowG32 = 32;
private const int LowG16 = 16;
private const int LowG8 = 8;
public const int LowGMax = 64;
public const int LowGMin = 8;
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum AvailableRangesLowG
{
[Description("TSRAIR_LOW_g_64")]
LowG64D = LowG64,
[Description("TSRAIR_LOW_g_32")]
LowG32D = LowG32,
[Description("TSRAIR_LOW_g_16")]
LowG16D = LowG16,
[Description("TSRAIR_LOW_g_8")]
LowG8D = LowG8
};
public enum AvailableRangesARS
{
ARS2000D = ARS2000,
ARS250D = ARS250
};
public const string HighG = "-High g";
public const string LowG = "-Low g";
public const string ARS = "-ARS";
public const string Atm = "-Atm";
public const int TSRAirTemperatureChannel = 9;
public const int TSRAirHumidityChannel = 10;
public const int TSRAirPressureChannel = 11;
public static bool IsTSRAirHighGChannel(string moduleSerialNumber)
{
if (moduleSerialNumber.EndsWith(HighG))
{
return true;
}
return false;
}
public static bool IsTSRAirLowGChannel(string moduleSerialNumber)
{
if (moduleSerialNumber.EndsWith(LowG))
{
return true;
}
return false;
}
public static bool IsTSRAirARSChannel(string moduleSerialNumber)
{
if (moduleSerialNumber.EndsWith(ARS))
{
return true;
}
return false;
}
public static bool IsTSRAirAtmChannel(string moduleSerialNumber)
{
if (moduleSerialNumber.EndsWith(Atm))
{
return true;
}
return false;
}
public static bool IsTSRAirHumidityChannel(string moduleSerialNumber, int channelNumber)
{
return IsTSRAirAtmChannel(moduleSerialNumber) && (channelNumber == TSRAirHumidityChannel);
}
}
}

View File

@@ -0,0 +1,12 @@
$solutionDir = [System.IO.Path]::GetDirectoryName($dte.Solution.FullName) + "\"
$path = $installPath.Replace($solutionDir, "`$(SolutionDir)")
$NativeAssembliesDir = Join-Path $path "lib\native"
$x86 = $(Join-Path $NativeAssembliesDir "bin32\*.*")
$x64 = $(Join-Path $NativeAssembliesDir "bin64\*.*")
$HDFPostBuildCmd = "
if not exist `"`$(TargetDir)bin32`" md `"`$(TargetDir)bin32`"
xcopy /s /y `"$x86`" `"`$(TargetDir)bin32`"
if not exist `"`$(TargetDir)bin64`" md `"`$(TargetDir)bin64`"
xcopy /s /y `"$x64`" `"`$(TargetDir)bin64`""

View File

@@ -0,0 +1,494 @@
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
namespace DTS.Common.Utils
{
public static class Database
{
#region properties
/// <summary>
/// used for output from processes
/// </summary>
private static StringBuilder sb = new StringBuilder();
private static StringBuilder sbError = new StringBuilder();
/// <summary>
/// lock to prevent multiple threads operating on sb simultaneously
/// </summary>
private static readonly object PROCESS_LOCK = new object();
#endregion properties
#region methods
/// <summary>
/// used to collect output from a running process
/// </summary>
/// <param name="sendingProcess"></param>
/// <param name="outLine"></param>
private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (outLine.Data != null)
{
if (string.IsNullOrWhiteSpace(outLine.Data))
{
sb.Append("\r\n");
}
sb.Append(outLine.Data);
}
}
/// <summary>
/// log function optionally passed into functions
/// </summary>
/// <param name="paramlist"></param>
public delegate void LogDelegate(params object[] paramlist);
/// <summary>
/// starts a process with a given command and logs
/// </summary>
/// <param name="sqlLocalDbExeFileName"></param>
/// <param name="command"></param>
/// <param name="log"></param>
/// <returns></returns>
private static string SqlCommandProcessor(string sqlLocalDbExeFileName, string command, LogDelegate log)
{
var resultString = string.Empty;
lock (PROCESS_LOCK)
{
sb.Clear();
sbError.Clear();
var process = new Process
{
StartInfo =
{
FileName = sqlLocalDbExeFileName,
Arguments = command,
LoadUserProfile = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
//* Set ONLY ONE handler here.
process.OutputDataReceived += OutputHandler;
process.ErrorDataReceived += Process_ErrorDataReceived;
//* Start process
process.Start();
//* Read one element asynchronously
process.BeginErrorReadLine();
//* Read the other one synchronously
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
log?.Invoke($"Result of {command} command is: {output}");
process.WaitForExit();
if (sb.Length > 0)
{
resultString = sb.ToString();
}
if( sbError.Length > 0)
{
log?.Invoke($"Error command: {command} error: {sbError}");
resultString += sbError.ToString();
}
}
return resultString;
}
/// <summary>
/// handles any error output from running a SqlCmd.exe process
/// </summary>
private static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
if (string.IsNullOrWhiteSpace(e.Data))
{
sbError.Append("\r\n");
}
sbError.Append(e.Data);
}
}
/// <summary>
/// gets the path to SqlServer
/// </summary>
/// <returns></returns>
public static string GetSqlServerLocalDbPath()
{
var highestVersionInstalledPath = string.Empty;
var rk = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var sk1 = rk.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server Local DB\\Installed Versions");
if (sk1 == null) return string.Empty;
var maxProductVersion = 0.0;
foreach (var productSubKeyName in sk1.GetSubKeyNames())
{
if (!double.TryParse(productSubKeyName, NumberStyles.Float, CultureInfo.InvariantCulture, out var thisVersion)) continue;
if (thisVersion < maxProductVersion) continue;
maxProductVersion = thisVersion;
var newKey = sk1.OpenSubKey(productSubKeyName);
if (newKey == null) continue;
var val = newKey.GetValue("InstanceAPIPath", -1, RegistryValueOptions.None).ToString();
if (val == "-1" || !val.EndsWith("SqlUserInstance.dll")) continue;
highestVersionInstalledPath = val.Substring(0, val.Length - "SqlUserInstance.dll".Length);
}
var envProgFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Utilities.Logging.APILogger.Log($"Environment.Program Files is {envProgFiles}");
var envProgFilesNoDrive = envProgFiles.Substring(envProgFiles.LastIndexOf("\\") + 1);
Utilities.Logging.APILogger.Log($"envProgFilesNoDrive is {envProgFilesNoDrive}");
Utilities.Logging.APILogger.Log($"highestVersionInstalledPath before Replace is {highestVersionInstalledPath}");
highestVersionInstalledPath = highestVersionInstalledPath.Replace("Program Files", envProgFilesNoDrive);
Utilities.Logging.APILogger.Log($"highestVersionInstalledPath after Replace is {highestVersionInstalledPath}");
return highestVersionInstalledPath.Replace("LocalDB", "Tools");
}
/// <summary>
/// Instead of relying on the Path environment variable to have the path to the SQLCMD.EXE that
/// we need to run, earlier in the Path list than a path to an older version of SQLCMD.EXE that
/// will not work with the SqlLocalDb version that we are using, search the registry for the
/// newest version of SQLCMD.exe and return that path.
/// The path should be something like $"C:\\Program Files\\Microsoft SQL Server\\Client SDK\\ODBC\\110\\Tools\\Binn"
/// </summary>
/// <returns></returns>
public static string GetODBCToolsPath(LogDelegate log)
{
var ODBCToolsPath = string.Empty;
try
{
var rk = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var sk1 = rk.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server");
if (sk1 == null) return string.Empty;
ODBCToolsPath = ScanRegistry(log, sk1, true);
if (string.IsNullOrWhiteSpace(ODBCToolsPath))
{
//We didn't find the patch using the previous method (ensuring that it had a CurrentVersion sub folder)
//so try to find the path without that sub folder.
ODBCToolsPath = ScanRegistry(log, sk1, false);
}
}
catch (Exception ex)
{
log?.Invoke(ex.Message);
}
finally
{
log?.Invoke($"ODBCToolsPath is {ODBCToolsPath}");
}
return ODBCToolsPath;
// This should return something like $"C:\\Program Files\\Microsoft SQL Server\\Client SDK\\ODBC\\110\\Tools\\Binn";
}
private static string ScanRegistry(LogDelegate log, RegistryKey sk1, bool checkCurrentVersion)
{
var ODBCToolsPath = string.Empty;
var envProgFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Utilities.Logging.APILogger.Log($"Environment.Program Files is {envProgFiles}");
var envProgFilesNoDrive = envProgFiles.Substring(envProgFiles.LastIndexOf("\\") + 1);
Utilities.Logging.APILogger.Log($"envProgFilesNoDrive is {envProgFilesNoDrive}");
try
{
var maxProductVersion = 0;
var maxProductSubKeyNameInt = 0;
foreach (var productSubKeyName in sk1.GetSubKeyNames())
{
if (!double.TryParse(productSubKeyName, NumberStyles.Float, CultureInfo.InvariantCulture, out var thisVersion)) continue;
var productSubKey = sk1.OpenSubKey(productSubKeyName);
if (productSubKey == null) continue;
foreach (var folderName in productSubKey.GetSubKeyNames())
{
if (folderName == "Tools")
{
//e.g. Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\120\Tools
var toolsFolderSubkey = productSubKey.OpenSubKey(folderName);
if (toolsFolderSubkey == null) continue;
foreach (var toolsSubFolderName in toolsFolderSubkey.GetSubKeyNames())
{
if (toolsSubFolderName == "ClientSetup")
{
//e.g. Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\120\Tools\ClientSetup
var clientSetupFolderSubkey = toolsFolderSubkey.OpenSubKey(toolsSubFolderName);
if (clientSetupFolderSubkey == null) continue;
var pathValue = clientSetupFolderSubkey.GetValue("ODBCToolsPath", -1, RegistryValueOptions.None).ToString();
if (pathValue == "-1")
{
log?.Invoke($"There is no ODBCToolsPath subkey in {clientSetupFolderSubkey}");
continue;
}
Utilities.Logging.APILogger.Log($"pathValue before Replace is {pathValue}");
pathValue = pathValue.Replace("Program Files", envProgFilesNoDrive);
Utilities.Logging.APILogger.Log($"pathValue after Replace is {pathValue}");
var sqlcmdFile = Path.Combine(pathValue, "SQLCMD.EXE");
log?.Invoke($"Looking for {sqlcmdFile}");
if (!File.Exists(sqlcmdFile))
{
log?.Invoke($"No file named {sqlcmdFile} exists");
//Try without the "\Client SDK\ODBC\" folders
pathValue = pathValue.Replace("Client SDK\\ODBC\\", "");
sqlcmdFile = Path.Combine(pathValue, "SQLCMD.EXE");
log?.Invoke($"Now looking for {sqlcmdFile}");
if (!File.Exists(sqlcmdFile)) continue;
log?.Invoke($"Found {sqlcmdFile}");
}
if (checkCurrentVersion)
{
foreach (var clientSetupSubFolderName in clientSetupFolderSubkey.GetSubKeyNames())
{
if (clientSetupSubFolderName == "CurrentVersion")
{
//Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\120\Tools\ClientSetup\CurrentVersion
var currentVersionFolderSubkey = clientSetupFolderSubkey.OpenSubKey(clientSetupSubFolderName);
if (currentVersionFolderSubkey == null) continue;
var versionValue = currentVersionFolderSubkey.GetValue("CurrentVersion", -1, RegistryValueOptions.None).ToString();
if (versionValue == "-1") continue;
var majorVersionString = versionValue.Split('.')[0];
if (!Int32.TryParse(majorVersionString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var majorVersionInt)) continue;
if (majorVersionInt > maxProductVersion)
{
maxProductVersion = majorVersionInt;
ODBCToolsPath = pathValue;
}
}
}
}
else
{
if (!Int32.TryParse(productSubKeyName, NumberStyles.Integer, CultureInfo.InvariantCulture, out var productSubKeyNameInt)) continue;
if (productSubKeyNameInt > maxProductSubKeyNameInt)
{
maxProductSubKeyNameInt = productSubKeyNameInt;
ODBCToolsPath = pathValue;
}
}
}
}
}
}
}
}
catch (Exception ex)
{
log?.Invoke(ex.Message);
}
finally
{
log?.Invoke($"ODBCToolsPath is {ODBCToolsPath}");
}
return ODBCToolsPath;
}
/// <summary>
/// installed, and run the command passed in.
/// </summary>
/// Get the path to the latest version of SQL Server Express LocalDB
/// <param name="command"></param>
/// <returns></returns>
private static string ProcessSqlLocalDbCommand(string command, LogDelegate log)
{
//SQL Server Express LocalDB 2014 is a Prerequisite of the DataPRO Installer,
//so it should be there unless it has been subsequently uninstalled.
var localDbPath = GetSqlServerLocalDbPath();
if (localDbPath == string.Empty)
{
//SQL Server LocalDb is not installed so display error and go away
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.LocalDbDoesntExist);
}
var sqlLocalDbExeFileName = localDbPath + "SqlLocalDB.exe";
return SqlCommandProcessor(sqlLocalDbExeFileName, command, log);
}
private static string BatchCommandProcessor(string batchFileName,
string dbName,
string sqlDbFileName,
string sqlLogFileName,
string fullSqlcmdPath,
LogDelegate log)
{
var resultString = string.Empty;
lock (PROCESS_LOCK)
{
sb.Clear();
sbError.Clear();
var process = new Process
{
StartInfo =
{
FileName = batchFileName,
Arguments = dbName + " " + "\"" + sqlDbFileName + "\"" + " " + "\"" + sqlLogFileName + "\"" + " " + "\"" + fullSqlcmdPath + "\"",
LoadUserProfile = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
//* Set ONLY ONE handler here.
process.OutputDataReceived += OutputHandler;
process.ErrorDataReceived += Process_ErrorDataReceived;
//* Start process
process.Start();
//* Read one element asynchronously
process.BeginErrorReadLine();
//* Read the other one synchronously
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
log?.Invoke($"Result of attach {dbName} using {sqlDbFileName} and {sqlLogFileName} is:");
log?.Invoke(output);
process.WaitForExit();
if (sb.Length > 0)
{
resultString = sb.ToString();
}
if( sbError.Length > 0)
{
resultString += sbError.ToString();
}
}
return resultString;
}
/// <summary>
/// attaches to a given database
/// throws DbNotAttached exception
/// </summary>
/// <param name="targetDir"></param>
/// <param name="dbName"></param>
/// <param name="dbFolder"></param>
/// <param name="scriptsFolder"></param>
/// <param name="attachDBsbat"></param>
/// <param name="log"></param>
public static void AttachDatabase(string targetDir,
string dbName,
string dbFolder,
string scriptsFolder,//StringResources.ScriptsFolder
string attachDBsbat,
LogDelegate log) //StringResources.AttachDBsbat
{
const string SqlCmdExe = "sqlcmd.exe";
var dbFileName = Path.Combine(Environment.CurrentDirectory, dbFolder, dbName) + ".mdf";
var logFileName = Path.Combine(Environment.CurrentDirectory, dbFolder, dbName) + "_log.ldf";
var batchFileName = Path.Combine(targetDir, scriptsFolder, attachDBsbat);
var oDBCToolsPath = DTS.Common.Utils.Database.GetODBCToolsPath(log);
var fullSqlcmdPath = Path.Combine(oDBCToolsPath, SqlCmdExe); //e.g. $"\"C:\\Program Files\\Microsoft SQL Server\\Client SDK\\ODBC\\110\\Tools\\Binn\\sqlcmd.exe\""
var resultString = BatchCommandProcessor(batchFileName, dbName, dbFileName, logFileName, fullSqlcmdPath, log);
if (resultString.Length != 0)
{
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.DbNotAttached);
}
}
/// <summary>
/// checks to see if database files exist
/// throws FileNotFound exception
/// </summary>
/// <param name="defaultDbName"></param>
/// <param name="dbFolder"></param>
public static void CheckLocalDatabaseFilesExist(string defaultDbName, string dbFolder)
{
var dbFileNameSource = Path.Combine(Environment.CurrentDirectory, dbFolder, defaultDbName) + ".mdf";
var logFileNameSource = Path.Combine(Environment.CurrentDirectory, dbFolder, defaultDbName) + "_log.ldf";
if (!File.Exists(dbFileNameSource))
{
throw new FileNotFoundException(dbFileNameSource);
}
if (!File.Exists(logFileNameSource))
{
throw new FileNotFoundException(logFileNameSource);
}
}
/// <summary>
/// creates an SQL local db instance
/// throws FailedToCreateInstance exception
/// </summary>
/// <param name="instance"></param>
/// <param name="log"></param>
public static void CreateInstance(string instance, LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"create {instance}", log);
if (resultString.Length != 0)
{
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.FailedToCreateInstance);
}
}
/// <summary>
/// stops a given sql local db instance
/// throws LocalDbDoesntExist exception
/// </summary>
/// <param name="instance"></param>
/// <param name="log"></param>
public static void StopInstance(string instance, LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"stop {instance}", log);
if (resultString.Length != 0)
{
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.FailedToStopInstance, resultString);
}
}
/// <summary>
/// deletes a given sql local db instance
/// throws FailedToDeleteInstance exception
/// </summary>
/// <param name="instance"></param>
/// <param name="log"></param>
public static void DeleteInstance(string instance, LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"delete {instance}", log);
if (resultString.Length != 0)
{
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.FailedToDeleteInstance);
}
}
/// <summary>
/// starts a local db instance
/// throws FailedToStartInstance exception
/// </summary>
/// <param name="instance"></param>
/// <param name="log"></param>
public static void StartInstance(string instance, LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"start {instance}", log);
if (resultString.Length != 0)
{
throw new SqlServerLocalDbException(SqlServerLocalDbException.Errors.FailedToStartInstance);
}
}
#endregion methods
public class SqlServerLocalDbException
: Exception
{
public Errors Error { get; }
public SqlServerLocalDbException(Errors error)
{
Error = error;
}
public SqlServerLocalDbException(Errors error, string msg)
:base(msg)
{
Error = error;
}
public enum Errors
{
FailedToStopInstance,
LocalDbDoesntExist,//sql local db doesn't exist
FailedToDeleteInstance,
FailedToCreateInstance,
FailedToStartInstance,
DbNotAttached,
IsodbNotAttached,
DASFactoryDBNotAttached,
}
}
}
}