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,81 @@
---
source_files:
- DataPRO/DASFactoryDb/ARM/ARM.cs
generated_at: "2026-04-16T03:53:10.384931+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "dd0ee32e99af1e4e"
---
# ARM
### **Purpose**
This module provides a centralized static interface for updating the ARM (Armed/Recording Monitor) status of a Data Acquisition System (DAS) record in the database. It acts as a thin data-access wrapper that translates in-memory ARM state flags, metrics, and metadata into a stored procedure call (`sp_ArmStatusSet`) to persist the current operational state of a DAS unit—such as armed status, triggering, fault conditions, recording progress, and sensor readings—ensuring consistency between the applications runtime state and the persisted state in the database.
---
### **Public Interface**
#### `ARM.SetArmStatus(...)`
```csharp
public static void SetArmStatus(
int iDASRecordId,
bool isArmed,
bool isTriggered,
bool isTriggerShorted,
bool isStartShorted,
bool isRecording,
bool isFaulted,
bool isInRealtime,
bool isInFlashWrite,
bool isUndefined,
bool isInPostTestDiagnostics,
double timeRemainingSeconds,
double percentComplete,
ulong totalSamples,
ulong currentSample,
uint sampleRate,
double? inputMilliVolts,
double? batteryMilliVolts,
int? eventNumber,
int recordingMode,
string faultMessage,
bool isRearming,
bool hasBeenRecording,
double? timeLeftInArm
)
```
**Behavior**: Updates the ARM status for the DAS record identified by `iDASRecordId` by invoking the stored procedure `sp_ArmStatusSet`. All parameters map directly to corresponding database columns/parameters. If the database connection is not active (`!DbWrapper.Connected`), the method returns early without executing the procedure. It handles nullable types by substituting defaults (`0` for numerics, `""` for strings) before passing to SQL. It captures and processes output parameters (`@errorNumber`, `@errorMessage`, `@new_id`) via `DbWrapper.ProcessReturn`, and ensures the command connection is disposed in a `finally` block.
---
### **Invariants**
- **Connection requirement**: The method performs no operation if `DbWrapper.Connected` is `false`.
- **Non-nullability enforcement**: Nullable parameters (`double?`, `int?`) are coalesced to non-null defaults (`0` or `""`) before being passed to SQL—no `NULL` values are sent for any parameter.
- **Stored procedure contract**: Assumes `sp_ArmStatusSet` exists and accepts the exact 24 parameters listed (including 3 output parameters).
- **Resource cleanup**: The underlying `SqlCommand.Connection` is explicitly disposed after execution, regardless of success or failure.
- **No return value**: The method does not expose the output values (`@errorNumber`, `@errorMessage`, `@new_id`) to callers—processing is delegated entirely to `DbWrapper.ProcessReturn`.
---
### **Dependencies**
- **Internal dependencies**:
- `DbWrapper.Connected` (property) and `DbWrapper.GetDASFactoryCommand()` (method) — used to check connectivity and obtain a configured `SqlCommand`.
- `DbWrapper.ProcessReturn(...)` — processes output parameters from the stored procedure call.
- **External dependencies**:
- `System.Data` and `System.Data.SqlClient` — for `SqlDbType`, `CommandType`, `SqlParameter`, `ParameterDirection`, and `IDbCommand`.
- Database: Requires the stored procedure `sp_ArmStatusSet` to exist in the DASFactory database with the exact parameter list and types.
**Depended on by**: Presumably other components in the DAS system that need to update ARM status (e.g., recording state machines, fault handlers, telemetry services)—though not visible in this file.
---
### **Gotchas**
- **Silent no-op on disconnect**: If `DbWrapper.Connected` is `false`, the method returns without logging or raising an exception—this may mask connectivity issues.
- **Loss of null semantics**: Nullable parameters (`inputMilliVolts`, `batteryMilliVolts`, `eventNumber`, `timeLeftInArm`) are converted to `0` or `""` when `null`, potentially overwriting meaningful `NULL` states in the database (e.g., “unknown” vs. “zero”).
- **`ulong` → `int` truncation risk**: `totalSamples`, `currentSample` (`ulong`) are passed as `SqlDbType.Int` (signed 32-bit), which may cause silent overflow or incorrect values for large sample counts (> 2³¹1).
- **Hardcoded stored procedure name**: The procedure name `"sp_ArmStatusSet"` is hardcoded—no abstraction or configuration layer.
- **No validation of input values**: No checks for invalid combinations (e.g., `isRecording == true` but `isArmed == false`)—assumes caller maintains logical consistency.
- **Output parameters unused by caller**: Though `@new_id` is declared and returned, its value is not exposed—suggests possible legacy or incomplete implementation.
*None identified from source alone.* — *Note: The above gotchas are inferred from observed behavior and type mismatches; no explicit documentation or comments exist in the source.*

View File

@@ -0,0 +1,74 @@
---
source_files:
- DataPRO/DASFactoryDb/Config/Config.cs
generated_at: "2026-04-16T03:52:17.979930+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "609ad832d02ccb50"
---
# Config
## Documentation: `DASFactoryDb.Config.Config` Module
---
### 1. Purpose
This module provides a thin, static wrapper around three SQL Server stored procedures (`sp_DASInfoInsert`, `sp_DASInfoClear`, and `sp_ConfigDataSet`) for managing DAS (Data Acquisition System) device metadata and configuration in the `DASFactoryDb` database. It abstracts low-level ADO.NET operations—including parameter binding, null handling, and error propagation—into strongly-typed C# methods. Its role is to ensure consistent, validated data persistence for DAS device information (e.g., MAC address, module limits, battery, calibration) and XML-based configuration blobs.
---
### 2. Public Interface
#### `int DASInfoInsert(int iDASRecordId, string macAddress, int owningDASId, uint maxNumberOfModules, ulong? maxEventStorageSpaceInBytes, ulong? numberOfBytesPerSampleClock, string batteryId, DateTime? calibrationDate)`
- **Behavior**: Inserts or updates DAS device metadata by calling the `sp_DASInfoInsert` stored procedure. Returns the ID of the inserted/updated record (via `@new_id` output parameter).
- **Null/Default Handling**:
- `macAddress``string.Empty` if `null`.
- `maxEventStorageSpaceInBytes`, `numberOfBytesPerSampleClock``0` if `null`.
- `calibrationDate``SqlDateTime.MinValue` if `null` or less than `SqlDateTime.MinValue`.
- **Error Handling**: Delegates to `DbWrapper.ProcessReturn` after execution; throws on non-zero `@errorNumber`.
#### `void DASInfoClear(int iDASRecordId)`
- **Behavior**: Clears DAS device metadata by calling `sp_DASInfoClear`. Does nothing if `DbWrapper.Connected` is `false`.
- **Note**: No return value; errors are propagated via `DbWrapper.ProcessReturn`.
#### `void SetConfiguration(int iDASRecordId, string xml, int fileStore)`
- **Behavior**: Stores XML configuration data as UTF-8 encoded binary (`VarBinary`) by calling `sp_ConfigDataSet`. Returns the new configuration record ID via `@new_id` (not exposed in return value).
- **Null/Default Handling**: No explicit null checks on `xml`; passes raw bytes (including `null``DBNull.Value` behavior depends on `SqlParameter` handling).
- **Error Handling**: Same as above; skips execution if not connected.
---
### 3. Invariants
- **Connection State**: `DASInfoClear` and `SetConfiguration` silently exit if `DbWrapper.Connected == false`. `DASInfoInsert` does *not* check connection state and will attempt execution regardless.
- **Parameter Validation**:
- `maxNumberOfModules` is bound as `SqlDbType.Int` despite being `uint`; potential overflow if `> int.MaxValue`.
- `maxEventStorageSpaceInBytes` and `numberOfBytesPerSampleClock` are `ulong?` but bound as `SqlDbType.Int`; values > `int.MaxValue` will overflow silently (to negative or truncated values).
- **Date Handling**: `calibrationDate` is clamped to `SqlDateTime.MinValue` (1753-01-01) if below it; `DateTime.MinValue` (0001-01-01) is converted to this minimum.
- **Error Propagation**: All methods rely on `DbWrapper.ProcessReturn` to interpret `@errorNumber` and `@errorMessage`; non-zero `@errorNumber` likely throws an exception (behavior depends on `DbWrapper.ProcessReturn` implementation, not visible here).
---
### 4. Dependencies
- **Internal Dependencies**:
- `DbWrapper` (static class): Provides `GetDASFactoryCommand()`, `Connected` property, and `ProcessReturn(SqlParameter, SqlParameter)`.
- `System.Data`, `System.Data.SqlClient`, `System.Text`: For ADO.NET types and UTF-8 encoding.
- **External Dependencies**:
- SQL Server database with stored procedures:
- `sp_DASInfoInsert`
- `sp_DASInfoClear`
- `sp_ConfigDataSet`
- Assumed schema: Tables/columns matching parameter names (e.g., `@IDASCommunicationRecordId`, `@ConfigurationData`, `@ConfigStore`).
---
### 5. Gotchas
- **Silent Data Truncation**: `maxEventStorageSpaceInBytes` and `numberOfBytesPerSampleClock` (`ulong?`) are cast to `int` (via `SqlDbType.Int`). Values > `2,147,483,647` will overflow or wrap, causing incorrect data.
- **No Connection Guard in `DASInfoInsert`**: Unlike `DASInfoClear`/`SetConfiguration`, this method proceeds even if `DbWrapper.Connected == false`, risking runtime exceptions.
- **`macAddress` Null Handling**: Converts `null` to `string.Empty` before binding, which may mask missing data (e.g., DB might accept empty string as valid).
- **`xml` Parameter**: No validation or encoding checks; malformed XML or non-UTF-8 data could cause DB errors.
- **Resource Management**: `cmd.Connection.Dispose()` in `finally` blocks may conflict with `DbWrapper`s connection lifecycle if it manages pooled connections.
- **Missing Return Value**: `SetConfiguration` retrieves `@new_id` but discards it; callers cannot confirm the inserted ID.
- **No Timeout Configuration**: Command timeout defaults to `DbWrapper`s implementation (not specified here).
*None identified beyond these.*

View File

@@ -0,0 +1,78 @@
---
source_files:
- DataPRO/DASFactoryDb/DAS/DAS.cs
generated_at: "2026-04-16T03:52:32.887554+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "bd5dcbab40df1de5"
---
# DAS
## Documentation: `DASFactoryDb.DAS.DAS` Module
---
### 1. Purpose
This module provides a simplified data access layer for inserting records into the DAS (Device Acceptance System) factory communication table in a SQL Server database. It encapsulates the logic for calling the stored procedure `sp_IDASCommunicationTableSimpleInsert`, handling parameter binding, output parameter extraction, and error propagation via `DbWrapper.ProcessReturn`. Its role is to abstract low-level ADO.NET operations for a specific high-frequency insert operation, ensuring consistent handling of serial number, firmware version, and connection string data.
---
### 2. Public Interface
#### `InsertDASSimple(string serialNumber, string firmwareVersion, string connectString) → int`
- **Behavior**: Executes the stored procedure `sp_IDASCommunicationTableSimpleInsert` with the provided input parameters (`@SerialNumber`, `@FirmwareVersion`, `@ConnectString`) and returns the newly inserted records ID (`@new_id`).
- **Parameters**:
- `serialNumber`: NVARCHAR(50) — Device serial number.
- `firmwareVersion`: NVARCHAR(50) — Firmware version string.
- `connectString`: NVARCHAR(255) — Connection string for the device.
- **Output**:
- Returns the integer value of the `@new_id` output parameter (the primary key of the inserted row).
- **Error Handling**:
- Delegates error processing to `DbWrapper.ProcessReturn`, passing the `@errorNumber` and `@errorMessage` output parameters.
- Disposes the underlying `SqlConnection` in a `finally` block (via `cmd.Connection.Dispose()`).
> **Note**: Parameter name for `connectString` is misspelled as `"ConnectString"` (missing `@` prefix in the `SqlParameter` constructor), but the stored procedure likely expects `@ConnectString`. This is consistent with the source and must be preserved.
---
### 3. Invariants
- **Parameter Constraints** (inferred from SQL types):
- `serialNumber` must be ≤ 50 characters (NVARCHAR(50)).
- `firmwareVersion` must be ≤ 50 characters (NVARCHAR(50)).
- `connectString` must be ≤ 255 characters (NVARCHAR(255)).
- **Execution Guarantee**:
- The stored procedure is always invoked with `CommandType.StoredProcedure`.
- Output parameters `@errorNumber`, `@errorMessage`, and `@new_id` are *always* expected and used.
- **Resource Management**:
- The `SqlCommand.Connection` is *always* disposed after execution, regardless of success or failure (via `finally` block).
- **Return Semantics**:
- The method *always* returns an `int` derived from `@new_id`; no null-check is performed on `newId.Value` before conversion (assumes non-null output from stored procedure).
---
### 4. Dependencies
#### **Internal Dependencies**
- `DbWrapper.GetDASFactoryCommand()` — Provides a configured `SqlCommand` instance (connection, transaction context, etc.).
- `DbWrapper.ProcessReturn(SqlParameter errorNumber, SqlParameter errorMessage)` — Handles error propagation based on output parameters (e.g., throws exception if `errorNumber ≠ 0`).
#### **External Dependencies**
- `System.Data` (ADO.NET types: `SqlDbType`, `CommandType`, `ParameterDirection`)
- `System.Data.SqlClient` (SQL Server client types: `SqlCommand`, `SqlParameter`)
#### **Downstream Consumers**
- Any code calling `DAS.InsertDASSimple(...)` (e.g., factory test automation, device onboarding services).
- The stored procedure `sp_IDASCommunicationTableSimpleInsert` in the target database (not included in source, but required at runtime).
---
### 5. Gotchas
- **Parameter Name Typo**: The `SqlParameter` for `connectString` is constructed as `new SqlParameter("ConnectString", ...)` instead of `"@ConnectString"`. While ADO.NET typically ignores the `@` prefix in the constructor (it is added automatically), this is non-standard and could cause issues if `DbWrapper.GetDASFactoryCommand()` or the underlying connection setup expects strict naming.
- **No Input Validation**: The method does *not* validate input lengths or nullability before passing values to SQL. Passing `null` or oversized strings may cause runtime errors (e.g., `SqlException` from the stored procedure or truncation).
- **Assumes Non-null `@new_id`**: `Convert.ToInt32(newId.Value)` will throw `InvalidCastException` or `FormatException` if `@new_id` is `DBNull` or non-numeric.
- **Resource Disposal**: While `cmd.Connection.Dispose()` is called, the `using` block on `cmd` does *not* dispose the connection (since `cmd.Connection` is externally managed by `DbWrapper`). This is safe *only if* `DbWrapper` does not reuse the connection after disposal — a subtle risk if `DbWrapper` manages pooled connections incorrectly.
- **No Transaction Scope**: Inserts occur outside an explicit transaction; if atomicity with other operations is required, this method cannot be used directly.
> **None identified from source alone.**
> *(Note: The above gotchas are inferred from code structure and common ADO.NET pitfalls; no explicit documentation or comments in the source clarify intent or constraints.)*

View File

@@ -0,0 +1,123 @@
---
source_files:
- DataPRO/DASFactoryDb/Diagnostics/Diagnostics.cs
generated_at: "2026-04-16T03:52:56.599244+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "435708341e9b9055"
---
# Diagnostics
## Documentation: `DASFactoryDb.Diagnostics.Diagnostics` Module
---
### 1. **Purpose**
This module provides a set of static methods to interact with diagnostic-related database operations for DAS (Data Acquisition System) communication records. It serves as the primary interface for inserting, clearing, and managing diagnostic *actions* (configured test parameters) and diagnostic *results* (observed test outcomes) across channels and events. The module abstracts low-level ADO.NET database calls into higher-level operations, delegating actual data persistence to stored procedures in the DASFactory database.
---
### 2. **Public Interface**
All methods are `public static` and reside in the `DASFactoryDb.Diagnostics.Diagnostics` class.
#### `ClearDiagnosticActionsAllChannels(int idasRecordId)`
- **Behavior**: Clears *all* diagnostic action configurations for *all channels* associated with the given `idasRecordId`. Uses the stored procedure `sp_DiagnosticActionsClear`.
- **Parameters**:
- `idasRecordId`: ID of the DAS communication record to clear actions for.
- **Note**: Passes `null` for `@DASChannelNumber` to indicate “all channels”.
#### `InsertDiagnosticAction(...)`
- **Behavior**: Inserts a new diagnostic action configuration for a specific DAS channel. Uses the stored procedure `sp_DiagnosticsActionsInsert`.
- **Parameters**:
- `dasRecordId`: ID of the DAS communication record.
- `dasChannelNumber`: Channel number (0-based or 1-based? — not specified in source).
- Boolean flags indicating which diagnostic tests to perform (e.g., `measureExcitation`, `measureOffset`, `squibFireCheck`, etc.).
- **Returns**: Output parameter `@new_id` (ID of inserted record) is captured but *not returned* by this method.
#### `ClearExistingDiagnosticsAllChannels(int idasRecordId = -1)`
- **Behavior**: Clears *all* diagnostic *results* for a given DAS communication record (or *all records* if `idasRecordId == -1`). Uses the stored procedure `sp_DiagnosticsResultsClear`.
- **Parameters**:
- `idasRecordId`: Optional; defaults to `-1` (clear all records). If non-negative, clears only for that record.
- **Note**: Passes `null` for both `@DASChannelNumber` and `@EventNumber`, indicating “all channels and events”.
#### `InsertAnalogDiagnosticResult(...)`
- **Behavior**: Inserts a full analog diagnostic result record for a specific channel and event. Uses the stored procedure `sp_DiagnosticsResultsAnalogInsert`.
- **Parameters**:
- `iDASRecordId`, `dasChannelNumber`, `eventNumber`: Identifiers for the diagnostic result context.
- Numerous `double`, `short?`, `bool?` parameters representing measured/calculated values (e.g., excitation, offset, noise, gain, shunt deflection, bridge resistance).
- **Returns**: Output parameter `@new_id` is captured but *not returned*.
#### `InsertSquibDiagnosticResult(...)`
- **Behavior**: Inserts a squib (pyro) fire diagnostic result, including raw time-series data (current, voltage, time axis) as binary blobs. Uses the stored procedure `sp_DiagnosticsResultsSquibInsert`.
- **Parameters**:
- `iDASRecordId`, `dasChannelNumber`, `eventNumber`: Identifiers.
- `squibFireCurrentData`, `squibFireVoltageData`, `squibFireTimeAxis`: Arrays of `double` representing raw waveform data.
- Optional metrics: `measuredDurationMS`, `measuredDelayMS`, pass/fail flags.
- Calibration/scaling parameters: `squibThreshold`, `squibVoltageScaler`, `squibCurrentScaler`.
- **Special Behavior**:
- **Early return** if `squibFireCurrentData == null` (prevents exception in `BitConverter.GetBytes`).
- Converts `double[]` arrays to `byte[]` via `BitConverter.GetBytes` before storing in `VARBINARY` parameters.
#### `InsertDigitalDiagnosticResult(...)`
- **Behavior**: Inserts a digital diagnostic result (e.g., for digital input state verification). Uses the stored procedure `sp_DiagnosticsResultsDigitalInsert`.
- **Parameters**:
- `iDASRecordId`, `dasChannelNumber`, `eventNumber`: Identifiers.
- `digitalInputActiveState`: Boolean indicating whether the digital input was in its active state.
---
### 3. **Invariants**
- **Database Connection Check**: Every method first checks `DbWrapper.Connected`. If `false`, the method returns early *without* executing any DB operation or raising an exception.
- **Stored Procedure Execution**: All methods use `CommandType.StoredProcedure` and call `DbWrapper.ProcessReturn(errorNumber, errorMessage)` after execution. This implies:
- Stored procedures are expected to set `@errorNumber` and `@errorMessage` output parameters.
- `DbWrapper.ProcessReturn(...)` likely throws or logs on non-zero `@errorNumber`.
- **Connection Disposal**: All `SqlCommand` objects are wrapped in `using` blocks, and `cmd.Connection.Dispose()` is called explicitly in `finally` blocks — ensuring connections are released even on failure.
- **Null Handling for Parameters**: Parameters with nullable types (e.g., `double?`) are passed directly as `Value = nullableValue`. ADO.NET treats `null` as SQL `NULL`, which is consistent with the stored procedure expectations (e.g., `@EventNumber` can be `null` in `ClearExistingDiagnosticsAllChannels`).
- **No Return of Output Values**: While `@new_id` and error parameters are declared and populated, only errors are processed via `DbWrapper.ProcessReturn(...)`. The `@new_id` values are *not* exposed to callers.
---
### 4. **Dependencies**
#### **Internal Dependencies**
- `DASFactoryDb.Diagnostics.Diagnostics` depends on:
- `DbWrapper` (static class, not shown here) — provides:
- `Connected` property
- `GetDASFactoryCommand()` method (returns `SqlCommand`)
- `ProcessReturn(SqlParameter errorNumber, SqlParameter errorMessage)` method
- `System.Data`, `System.Data.SqlClient` — standard ADO.NET types.
#### **External Dependencies**
- **Database**:
- Stored procedures:
- `sp_DiagnosticActionsClear`
- `sp_DiagnosticsActionsInsert`
- `sp_DiagnosticsResultsClear`
- `sp_DiagnosticsResultsAnalogInsert`
- `sp_DiagnosticsResultsSquibInsert`
- `sp_DiagnosticsResultsDigitalInsert`
- Tables implied by the procedures (not visible in source).
- **Assumed Schema**:
- Tables likely include `IDASCommunicationRecordId`, `DASChannelNumber`, `EventNumber` as composite keys or foreign keys.
- Analog/digital/squib results stored in separate tables (based on procedure names).
#### **Dependents**
- Unknown — not visible in this file. Likely consumed by higher-level diagnostic orchestration or test execution modules.
---
### 5. **Gotchas**
- **Silent Failures on Disconnected State**: If `DbWrapper.Connected` is `false`, *all* methods return immediately with no indication of failure (no exception, no log). This may mask configuration or runtime issues.
- **Missing Return of Inserted IDs**: The `@new_id` output parameter is declared and populated by the stored procedure but *never returned* to the caller. Callers cannot reference newly inserted records.
- **Squib Data Null Guard is Incomplete**: While `squibFireCurrentData == null` triggers early return, `squibFireVoltageData` or `squibFireTimeAxis` being `null` would cause a `NullReferenceException` in the `foreach` loop. This is inconsistent and risky.
- **Typo in Parameter Name**: In `InsertAnalogDiagnosticResult`, the parameter `@AutoZeroPercentDeviation ` has a trailing space in the name (`"AutoZeroPercentDeviation "`), which may cause a mismatch with the stored procedure definition if not also defined with a trailing space.
- **No Validation on Channel/Event Numbers**: No checks for negative or out-of-range `dasChannelNumber` or `eventNumber`. Relies on DB constraints or stored procedure logic.
- **Binary Data Conversion**: `double[]``byte[]` conversion assumes little-endian architecture (standard on .NET on Windows), but may differ on other platforms (though DAS systems are typically Windows-based).
- **Ambiguous Channel Numbering**: Source does not clarify whether `dasChannelNumber` is 0-based or 1-based — critical for correct usage.
> **None identified from source alone** for other potential issues (e.g., transactional consistency, concurrency, error logging behavior beyond `ProcessReturn`).

View File

@@ -0,0 +1,118 @@
---
source_files:
- DataPRO/DASFactoryDb/Download/Download.cs
generated_at: "2026-04-16T03:52:56.569022+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "8f2bca6182f06470"
---
# Documentation: `DASFactoryDb.Download.Download` Module
## 1. Purpose
This module provides a set of static methods for managing event-related data in the DAS (Distributed Acoustic Sensing) factory database. Its primary role is to **clear or insert records related to event downloads, arm attempts, fault flags, event metadata, GUIDs, and download requests**—all scoped to a specific `IDASCommunicationRecordId`. It acts as a database abstraction layer, encapsulating calls to stored procedures for data integrity and separation of concerns, and ensures that operations are only executed when the database connection is active.
## 2. Public Interface
All methods are `public static` and belong to the `DASFactoryDb.Download.Download` class.
### Clearing Methods (all return `void`, accept `int idasRecordId`)
| Method | Signature | Behavior |
|--------|-----------|----------|
| `ClearExistingEventDownloadStatus` | `public static void ClearExistingEventDownloadStatus(int idasRecordId)` | Clears all existing download status entries for the given DAS communication record. Calls `sp_EventDownloadStatusClear`. |
| `ClearExistingEventArmAttempts` | `public static void ClearExistingEventArmAttempts(int idasRecordId)` | Clears all arm attempt records for the given DAS communication record. Calls `sp_EventArmAttemptsClear`. |
| `ClearExistingFaultFlags` | `public static void ClearExistingFaultFlags(int idasRecordId)` | Clears all fault flags for the given DAS communication record. Calls `sp_EventFaultFlagsClear`. |
| `ClearExistingDownloadReports` | `public static void ClearExistingDownloadReports(int idasRecordId)` | Clears all download report entries for the given DAS communication record. Calls `sp_DownloadReportClear`. |
| `ClearExistingEventGuids` | `public static void ClearExistingEventGuids(int idasRecordId)` | Clears all event GUIDs for the given DAS communication record. Calls `sp_EventGuidsClear`. |
| `ClearExistingDownloadRequests` | `public static void ClearExistingDownloadRequests(int idasRecordId)` | Clears all download request entries for the given DAS communication record. Calls `sp_DownloadRequestsClear`. |
| `ClearExistingUARTDownloadRequests` | `public static void ClearExistingUARTDownloadRequests(int idasRecordId)` | Clears all UART-specific download request entries for the given DAS communication record. Calls `sp_UARTDownloadRequestsClear`. |
### Insertion Methods (all return `void`, accept `idasRecordId` + event-specific parameters)
| Method | Signature | Behavior |
|--------|-----------|----------|
| `InsertEventFaultFlags` | `public static void InsertEventFaultFlags(int iDASRecordId, ushort faultFlag)` | Inserts a single fault flag for the given DAS record. Calls `sp_EventFaultFlagsInsert`. Returns `@new_Id` output parameter (not exposed). |
| `InsertEventArmAttempts` | `public static void InsertEventArmAttempts(int iDASRecordId, int armAttempts)` | Inserts arm attempt count for the given DAS record. Calls `sp_EventArmAttemptsInsert`. Returns `@new_id` output parameter (not exposed). |
| `InsertEventInfo` | `public static void InsertEventInfo(int iDASRecordId, int eventNumber, Guid testGUID, ushort faultFlags, int armAttempts, DateTime testTime, string testID, string description, bool hasBeenDownloaded, bool wasTriggered, string xml)` | Inserts core event metadata. Calls `sp_EventInfoInsert`. `testTime` is normalized to `SqlDateTime.MinValue` if `DateTime.MinValue`. `testGUID` is uppercased before insertion. `xml` is UTF-8 encoded and stored as `VarBinary`. Returns `@new_id`. |
| `InsertEventDownloadStatus` | `public static void InsertEventDownloadStatus(int iDASRecordId, bool downloadStatus)` | Inserts download status (`Downloaded` flag) for the given DAS record. Calls `sp_EventDownloadStatusInsert`. Returns `@new_id`. |
| `DownloadRequestInsert` | `public static void DownloadRequestInsert(int iDASRecordId, ushort eventNumber, int dasChannelNumber, ulong startSample, ulong endSample, ulong samplesToSkip, double startRecordTimeStampSec, double triggerTimeStampSec, double startRecordTimeStampNanoSec, double triggerTimestampNanoSec, bool PTPMasterSync)` | Inserts a standard (likely Ethernet-based) download request. Calls `sp_DownloadRequestsInsert`. Note: `@StartRecordTimestampNanoSec` parameter is incorrectly assigned `startRecordTimeStampSec` instead of `startRecordTimeStampNanoSec` (see *Gotchas*). |
| `UARTDownloadRequestInsert` | `public static void UARTDownloadRequestInsert(int iDASRecordId, ushort eventNumber, ulong totalByteCount, ulong triggerByteCount, ulong faultByteCount, ulong startTimestamp, ulong endTimestamp, int baudRate)` | Inserts a UART-specific download request. Calls `sp_UARTDownloadRequestsInsert`. |
| `EventGuidInsert` | `public static void EventGuidInsert(int iDASRecordId, Guid guid)` | Inserts a single event GUID for the given DAS record. Calls `sp_EventGuidsInsert`. `guid.ToString().ToUpper()` is used. Returns `@new_Id`. |
> **Note on Output Parameters**: All insertion methods declare output parameters (`@errorNumber`, `@errorMessage`, `@new_id`/`@new_Id`) and call `DbWrapper.ProcessReturn(errorNumber, errorMessage)` *except* `InsertEventFaultFlags`, which does **not** call `DbWrapper.ProcessReturn`. This is inconsistent and may lead to unhandled errors.
## 3. Invariants
- **Database Connection Check**: Every method first checks `if (!DbWrapper.Connected) { return; }`. No operation proceeds if the database is not connected.
- **Stored Procedure Execution**: All methods use `CommandType.StoredProcedure` and execute via `cmd.ExecuteNonQuery()`.
- **Connection Disposal**: Each method disposes the command connection in a `finally` block (`cmd.Connection.Dispose()`), ensuring cleanup even on exceptions.
- **Parameter Naming Consistency**: Stored procedure parameters consistently use `@IDASCommunicationRecordId`, `@errorNumber`, `@errorMessage`, and `@new_id`/`@new_Id`.
- **GUID Normalization**: GUIDs passed to `InsertEventInfo` and `EventGuidInsert` are uppercased via `.ToString().ToUpper()`.
- **DateTime Normalization**: `testTime == DateTime.MinValue` is converted to `SqlDateTime.MinValue` before insertion in `InsertEventInfo`.
- **XML Encoding**: The `xml` parameter in `InsertEventInfo` is UTF-8 encoded before being passed as `VarBinary`.
## 4. Dependencies
### Internal Dependencies
- `DASFactoryDb.Download.Download` depends on:
- `DbWrapper` (static class, not shown in source) — provides `Connected`, `GetDASFactoryCommand()`, and `ProcessReturn()` methods.
- Standard .NET libraries: `System.Data`, `System.Data.SqlClient`, `System.IO`, `System.Text`, `System.Xml`.
### External Dependencies
- **SQL Server Database** — requires the following stored procedures to exist:
- `sp_EventDownloadStatusClear`
- `sp_EventArmAttemptsClear`
- `sp_EventFaultFlagsClear`
- `sp_DownloadReportClear`
- `sp_EventGuidsClear`
- `sp_DownloadRequestsClear`
- `sp_EventFaultFlagsInsert`
- `sp_EventArmAttemptsInsert`
- `sp_EventInfoInsert`
- `sp_EventDownloadStatusInsert`
- `sp_DownloadRequestsInsert`
- `sp_UARTDownloadRequestsInsert`
- `sp_UARTDownloadRequestsClear`
- `sp_EventGuidsInsert`
- **Database Schema** — expects tables/columns compatible with the above stored procedures.
### Who Depends on This Module?
- Any code that needs to manage DAS event data in the database (e.g., event processing pipelines, download initiators, fault handlers). Not specified in source.
## 5. Gotchas
- **Parameter Mismatch in `DownloadRequestInsert`**:
The parameter `@StartRecordTimestampNanoSec` is assigned `startRecordTimeStampSec` instead of `startRecordTimeStampNanoSec`. This is likely a copy-paste error and will cause incorrect timestamp data to be stored.
```csharp
// Current (incorrect):
new SqlParameter("@StartRecordTimestampNanoSec", SqlDbType.Decimal)
{ Value = startRecordTimeStampSec }); // ← should be startRecordTimeStampNanoSec
```
- **Inconsistent Error Handling**:
`InsertEventFaultFlags` does **not** call `DbWrapper.ProcessReturn(errorNumber, errorMessage)`, while all other insertion methods do. This may result in unhandled database errors (e.g., constraint violations, stored procedure errors) going silently unnoticed.
- **No Return of Output Values**:
Although all methods declare and populate `@new_id`/`@new_Id` output parameters, none expose them to callers. If the new record ID is needed, callers must refactor the method or access it via `cmd.Parameters["@new_id"].Value` after execution (not possible here due to static encapsulation).
- **Silent Failures on Disconnection**:
Methods return early if `!DbWrapper.Connected`, but no logging or exception occurs. Callers may assume success even when no operation was performed.
- **No Input Validation**:
Methods do not validate input parameters (e.g., `idasRecordId` is not checked for negative values). Assumed valid by downstream stored procedures.
- **Case Sensitivity of GUIDs**:
GUIDs are uppercased before insertion. If the database or downstream consumers expect lowercase or canonical format, mismatches may occur.
- **No Transaction Support**:
Each method executes in its own implicit transaction (default ADO.NET behavior). If callers need atomicity across multiple operations (e.g., clear + insert), they must manage transactions externally.
- **String Length Assumptions**:
Parameters like `@errorMessage` are declared with `SqlDbType.NVarChar, 255`. If stored procedures return longer messages, truncation may occur silently.
- **Missing `using` for `SqlParameter`**:
Parameters are not wrapped in `using` blocks. While not strictly necessary (theyre not `IDisposable`), its inconsistent with best practices and may raise static analysis warnings.
None identified beyond the above.

View File

@@ -0,0 +1,35 @@
---
source_files:
- DataPRO/DASFactoryDb/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T03:52:28.192883+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "4cb05f8c94826e69"
---
# Properties
## 1. Purpose
This module is the `DASFactoryDb` .NET assembly, serving as a foundational data access layer component within the `DataPRO` product suite. Its primary role is to encapsulate database-related functionality—though the provided `AssemblyInfo.cs` file contains only metadata attributes and no executable logic—suggesting it is a supporting infrastructure assembly intended to be consumed by other modules (e.g., data access implementations, repositories, or ORM configurations). The assembly is not directly executable (no entry point) and exists solely to be referenced by other projects in the solution.
## 2. Public Interface
**No public API surface is defined in this file.**
`AssemblyInfo.cs` is a metadata file used by the .NET build system to embed assembly-level attributes (e.g., version, title, COM visibility). It declares no classes, interfaces, methods, properties, or fields. All public-facing functionality—should it exist—is located in *other* source files not included here.
## 3. Invariants
- The assembly identity is fixed at version `1.0.0.0` (both `AssemblyVersion` and `AssemblyFileVersion`).
- The assembly is **not visible to COM** (`ComVisible(false)`), meaning external COM clients cannot directly instantiate types from this assembly unless explicitly exposed via other means.
- The GUID `49c60032-9c8a-4ea5-9e26-2f1663555759` is reserved for the type library (typelib) ID if the assembly is later exposed to COM.
- No runtime invariants apply, as this file contains no executable code.
## 4. Dependencies
- **Dependencies of this assembly**: None. `AssemblyInfo.cs` only imports standard .NET attributes (`System.Reflection`, `System.Runtime.CompilerServices`, `System.Runtime.InteropServices`) and does not reference any external libraries or internal modules.
- **Dependents**: This assembly is intended to be referenced by other projects (e.g., `DataPRO` core modules or database service layers), but no specific consumers are identifiable from this file alone.
## 5. Gotchas
- **Misleading file location**: The path `DataPRO/DASFactoryDb/Properties/AssemblyInfo.cs` suggests this assembly may contain database access logic (per the `DASFactoryDb` name), but this file provides no implementation—only metadata. Developers should not expect database-related APIs here.
- **Versioning rigidity**: The `AssemblyVersion` is hardcoded to `1.0.0.0` with no wildcard (`*`), meaning build/revision numbers cannot auto-increment. This may complicate deployment or version tracking if not managed externally (e.g., via CI/CD).
- **COM visibility**: While `ComVisible(false)` is set, developers integrating with legacy COM systems must ensure types requiring COM exposure are explicitly marked `[ComVisible(true)]` in *other* source files.
- **No documentation**: `AssemblyDescription` and `AssemblyCulture` are empty, indicating incomplete assembly metadata—this may hinder automated tooling or documentation generation.
None identified beyond the above.