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,105 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/Enums.cs
generated_at: "2026-04-16T04:57:15.509262+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "a6932d6dcfd8e263"
---
# Classes
### **Purpose**
This module defines a set of core enumerations used throughout the `DatabaseExport` subsystem for version 57 of the database schema. These enums standardize the representation of test configuration settings (`TestSettingsEnum`), data acquisition modes (`RecordingModes`), sensor compatibility policies (`IsoChannelSensorCompatibilityLevels`), export format capabilities (`SupportedExportFormatBitFlags`), template tag identifiers (`TestTemplateTags`), and validation behavior levels (`StrictLevel`). They serve as foundational constants for serialization, UI binding, and logic branching in downstream export, configuration, and test execution components.
---
### **Public Interface**
#### **`TestSettingsEnum`**
- **Definition**: `public enum TestSettingsEnum`
- **Description**: Represents non-columned test settings—i.e., configuration flags or steps not stored as database columns but used in test logic or UI. Values correspond to checklist items and warmup/excitation settings.
- **Members**:
- `ArmCheckListStep`
- `CheckListInputVoltageCheck`
- `CheckListBatteryVoltageCheck`
- `CheckListSquibResistanceCheck`
- `CheckListSensorIDCheck`
- `CheckListTriggerStartCheck`
- `EW` *(ExcitationWarmup)*
- `CheckListMustPass`
#### **`RecordingModes`**
- **Definition**: `public enum RecordingModes`
- **Description**: Specifies the data acquisition recording strategy during a test.
- **Members**:
- `CircularBuffer`: Continuous overwrite buffer; only recent data retained until triggered.
- `Recorder`: Standard sequential recording from start to end.
- `HybridRecorder`: Combination of circular buffer pre-trigger and sequential post-trigger recording.
#### **`IsoChannelSensorCompatibilityLevels`**
- **Definition**: `public enum IsoChannelSensorCompatibilityLevels`
- **Description**: Controls how the system responds to incompatibility between ISO channels and connected sensors.
- **Members**:
- `DontWarn`: No warning or error raised for incompatibility.
- `Warn`: Log warning but allow proceeding.
- `DontAllow`: Block test execution if incompatibility detected.
#### **`SupportedExportFormatBitFlags`**
- **Definition**: `[Flags] public enum SupportedExportFormatBitFlags`
- **Description**: Bit-flag enumeration of supported export formats. Used to compose sets of formats via bitwise OR. *Note: `diademfiltered` is commented out and unused.*
- **Members** (selected notable examples):
- `csvunfiltered = 0x1`
- `isounfiltered = 0x4`
- `tdmsadc = 0x10`
- `csvfiltered = 0x80`
- `isofiltered = 0x200`
- `HDFUnfiltered = 0x10000`
- `xlsxfiltered = 0x100000`
- `ChryslerDDAS = 0x8000`
- **Full list**: All 20 explicitly defined flags (including `none = 0x0`) are present; no gaps except `diademfiltered`.
#### **`TestTemplateTags`**
- **Definition**: `public enum TestTemplateTags`
- **Description**: Defines string identifiers used as keys in test templates (e.g., XML/JSON config files) to map UI elements, data fields, or logic hooks. Includes both legacy and current test configuration properties.
- **Members**: 102 named constants, e.g.:
- `UploadData`, `UploadFolder`, `CommonLine`, `AllCustomers`, `Test`, `SamplesPerSecond`, `PreTriggerSeconds`, `RecordingMode`, `EW`, `ExcitationWarmupTimeMS`, `TestDirectory`, `ISFFile`, `GroupsStepValid`, etc.
- **Note**: Duplicates exist between `TestSettingsEnum` (e.g., `EW`, `ArmCheckListStep`, `CheckListBatteryVoltageCheck`, etc.)—this is intentional per source.
#### **`StrictLevel`**
- **Definition**: `public enum StrictLevel`
- **Description**: Controls strictness of validation or schema compliance during export or import.
- **Members**:
- `Strict`: Enforce full compliance; fail on mismatches.
- `UpdateTable`: Allow schema updates/relaxations (e.g., add missing columns).
---
### **Invariants**
- `SupportedExportFormatBitFlags` is explicitly marked `[Flags]`; valid combinations must be constructed via bitwise OR of individual flags (e.g., `csvunfiltered | tdmsadc`).
- Values in `TestTemplateTags` include both direct mappings to `TestSettingsEnum` members (e.g., `EW`, `ArmCheckListStep`) and additional tags—indicating that `TestTemplateTags` serves as a superset of template keys, not a one-to-one mapping.
- `RecordingModes` has exactly three mutually exclusive values; no combination is intended or supported.
- `IsoChannelSensorCompatibilityLevels` values form a strict hierarchy: `DontWarn``Warn``DontAllow` in enforcement level.
- No enum value is assigned explicitly beyond `SupportedExportFormatBitFlags` (which uses hex literals); all others rely on implicit sequential numbering starting at 0.
---
### **Dependencies**
- **Internal**: This module resides in the `DatabaseExport` namespace and is likely consumed by:
- Classes in the same `DatabaseExport` project (e.g., export pipeline, test runner, config parser).
- UI layers that bind `TestTemplateTags` to form fields or template variables.
- Validation modules using `StrictLevel` and `IsoChannelSensorCompatibilityLevels`.
- **External**: Depends solely on `System` (no external NuGet or third-party dependencies inferred).
- **No reverse dependencies inferred**: This file defines *only* enums; no class or method implementations are present to indicate what *imports* it.
---
### **Gotchas**
- **Duplicate enum members across `TestSettingsEnum` and `TestTemplateTags`**: Identical names (e.g., `EW`, `ArmCheckListStep`, `CheckListBatteryVoltageCheck`) appear in both enums. This suggests they are *not* semantically identical—`TestSettingsEnum` likely represents internal logic flags, while `TestTemplateTags` represents template key strings. Confusing them may cause runtime errors.
- **`diademfiltered` is commented out**: Though defined as `0x100`, it is unused and commented. Do *not* assume support for Diadem filtered exports unless validated in consuming code.
- **`LastMmodifiedBy` typo**: The enum member `LastMmodifiedBy` (with double `m`) likely contains a typo for `LastModifiedBy`. Verify usage in consuming code before renaming.
- **`EW` ambiguity**: Appears in both `TestSettingsEnum` and `TestTemplateTags`. In `TestTemplateTags`, it likely maps to a template key (e.g., `<EW>...</EW>`), while in `TestSettingsEnum` it represents a checklist step. Ensure context distinguishes usage.
- **No documentation on `StrictLevel.UpdateTable` behavior**: The meaning of “UpdateTable” is not self-evident; its semantics (e.g., auto-migrate schema?) must be verified in dependent code.
- **`TestTemplateTags` includes `GroupsStepValid`**: Suggests a specific validation state for group-based test steps; ensure logic handling this tag aligns with actual test execution flow.
None identified beyond these.

View File

@@ -0,0 +1,117 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/Hardware/DASSettings.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/Hardware/HardwareChannel.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/Hardware/DASHardware.cs
generated_at: "2026-04-16T04:59:11.131587+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "45f7e783788f3070"
---
# Hardware
## Documentation: DAS Hardware Abstraction Layer (Version 57)
### 1. Purpose
This module provides a version-specific abstraction layer for DAS (Data Acquisition System) hardware configuration and metadata within the `DatabaseExport` subsystem of the DataPRO system. It enables serialization of DAS settings (e.g., sample rate, AAF, trigger timing) into the legacy database schema (`tblTestSetupDASSettings`, `tblDAS`, `tblDASChannel`) and supports hardware discovery, comparison, and channel management. The classes (`DASSettings`, `HardwareChannel`, `DASHardware`, `DASHardwareList`) serve as DTOs and adapters for interacting with historical database structures, preserving compatibility with Version 57 schema while abstracting underlying `Hardware` and `ISOHardwareChannel` objects.
---
### 2. Public Interface
#### `DASSettings`
- **Properties**
- `string DASSerialNumber { get; set; }` — Serial number of the DAS device associated with the test settings.
- `double SampleRate { get; set; }` — Sampling rate (Hz) configured for the test.
- `int ExcitationWarmupTimeMS { get; set; }` — Warm-up time (milliseconds) for excitation voltage before data acquisition.
- `double HardwareAAF { get; set; }` — Hardware anti-aliasing filter cutoff frequency (Hz).
- `double PreTriggerSeconds { get; set; }` — Duration (seconds) of data captured *before* a trigger event.
- `double PostTriggerSeconds { get; set; }` — Duration (seconds) of data captured *after* a trigger event.
- `bool StatusLineCheck { get; set; }` — Flag indicating whether status line monitoring is enabled.
- `bool BatteryCheck { get; set; }` — Flag indicating whether battery voltage monitoring is enabled.
- `double InputVoltageMin { get; set; }` — Minimum acceptable input voltage (volts).
- `double InputVoltageMax { get; set; }` — Maximum acceptable input voltage (volts).
- `double BatteryVoltageMin { get; set; }` — Minimum acceptable battery voltage (volts).
- `double BatteryVoltageMax { get; set; }` — Maximum acceptable battery voltage (volts).
#### `HardwareChannel`
- **Constructors**
- `HardwareChannel(HardwareChannel copy)` — Deep-copies channel data (including `Sensor`).
- `HardwareChannel(ISOHardwareChannel channel, DASHardware hardware)` — Initializes from an `ISOHardwareChannel` and its parent `DASHardware`.
- **Properties**
- `DASHardware Hardware { get; }` — Parent DAS hardware instance.
- `int ChannelNumber { get; }` — Zero-based channel index (`ChannelIdx` from `ISOHardwareChannel`).
- `SensorData Sensor { get; set; }` — Sensor configuration for this channel (nullable).
- `TestObjectChannel TestObjectChannel { get; set; }` — Logical test object channel mapped to this hardware channel.
- **Methods**
- `ISOHardwareChannel GetISOChannel()` — Returns the underlying `ISOHardwareChannel` instance.
- `int CompareTo(HardwareChannel right)` — Compares channels first by `DASDisplayOrder`, then by `ChannelIdx`.
- `string GetId()` — Returns a unique ID in the format `{HardwareId}x{1-based ChannelNumber}`.
- `bool IsSupportedBridgeType(Test.Module.Channel.Sensor.BridgeType bridgeType)` — Checks if `bridgeType` is supported by this channel (via bitwise AND with `SupportedBridges`).
#### `DASHardware`
- **Properties**
- `string SerialNumber { get; set; }` — DAS serial number (from `_hardware.SerialNumber`).
- `string Connection { get; set; }` — Network address (e.g., IP) for the DAS (from `_hardware.IPAddress`).
- `DateTime CalDate { get; }` — Calibration date (read-only, from `_hardware.CalDate`).
- `HardwareChannel[] Channels { get; set; }` — Sorted array of channels (sorted by `CompareTo` in setter).
- `bool LocalOnly { get; set; }` — Flag indicating local-only operation (from `_hardware.LocalOnly`).
- **Methods**
- `Hardware GetHardware()` — Returns the underlying `Hardware` instance.
- `int GetHardwareTypeInt()` — Returns `_hardware.DASType` as an integer.
- `HardwareTypes GetHardwareTypeEnum()` — Casts `DASType` to `Hardware.HardwareTypes` enum.
- `long GetMaxMemoryLong()` — Returns `_hardware.MaxMemory`.
- `Dictionary<string, string> GetValues()` — Serializes DAS metadata (e.g., serial, type, firmware, sample rates, channel types) into a dictionary keyed by `DbOperations.DAS.Fields` enum values.
- `Dictionary<string, string> GetChannelValues(HardwareChannel channel)` — Serializes channel metadata (e.g., `ChannelIdx`, `SupportedBridges`, `DASDisplayOrder`) into a dictionary keyed by `DbOperations.DAS.DASChannelFields` enum values.
- `bool IsDummy()` — Returns `true` if `SerialNumber` contains `"Dummy"`.
- **Inherited from `DbTimeStampBase`**
- `override string LookupTable => "tblDAS"` — Database table name for persistence.
- `override ConstraintHelper[] GetConstraints()` — Returns a constraint for `SerialNumber` (used for DB lookups).
#### `DASHardwareList` (Singleton)
- **Methods**
- `static DASHardwareList GetList()` — Returns the singleton instance (lazy-initialized via `PopulateHardware`).
- `DASHardware GetHardware(string id)` — Retrieves DAS by ID (hardware ID or serial number).
- `DASHardware GetHardware(string id, bool bThrowExceptionIfChanged, out bool changed)` — Retrieves DAS; if ID format includes a type suffix (e.g., `SN_123`) and the hardware type has changed, throws `HardwareTypeChangedException` (if `bThrowExceptionIfChanged=true`) or sets `changed=true`.
- `DASHardware[] Hardware { get; }` — Returns all non-prototype DAS instances.
- **Nested Exception**
- `HardwareTypeChangedException : Exception` — Thrown when hardware type mismatch is detected during lookup.
---
### 3. Invariants
- **Channel Ordering**: `HardwareChannel.CompareTo` enforces ordering by `DASDisplayOrder` first, then `ChannelIdx`.
- **Channel Array Consistency**: Setting `DASHardware.Channels` sorts the array internally and raises `OnPropertyChanged` for both `Channels` and `ChannelCount`.
- **Hardware ID Format**: `HardwareChannel.GetId()` uses `1 + ChannelNumber` (1-based indexing in ID, 0-based in `ChannelNumber`).
- **Prototype Exclusion**: `DASHardwareList.GetAllHardware()` filters out hardware with `Position == "Prototype"`.
- **Serial Number Uniqueness**: `DASHardwareList` uses `_hardware.ContainsKey(h.GetHardware().GetId())` for deduplication during population.
- **Dummy Detection**: `IsDummy()` checks for substring `"Dummy"` in `SerialNumber` (case-sensitive).
---
### 4. Dependencies
- **Internal Dependencies**
- `Hardware` (from `DatabaseExport.Hardware` namespace) — Core data model for DAS hardware metadata.
- `ISOHardwareChannel` — Encapsulates channel-level metadata (e.g., `ChannelIdx`, `SupportedBridges`).
- `DbOperations.DAS.Fields` / `DbOperations.DAS.DASChannelFields` — Enumerations defining database column names (used in `GetValues`/`GetChannelValues`).
- `DbTimeStampBase` — Base class for time-stamped database entities (provides `LookupTable`, `GetConstraints`, `DbTimeStamp`).
- `SensorData` — Sensor configuration (used in `HardwareChannel`).
- `Test.Module.Channel.Sensor.BridgeType` — Bridge type enum (used in `IsSupportedBridgeType`).
- **External Dependencies**
- `System.Collections.Generic`, `System.Linq`, `System.Data.SqlDbType` — Standard .NET libraries.
- `System.IComparable<T>` — Implemented by `HardwareChannel` and `DASHardware`.
---
### 5. Gotchas
- **`CompareTo` Null Handling**: `HardwareChannel.CompareTo` returns `0` for `null` input (non-standard behavior; typically `null` comparisons should return `1`).
- **`GetHardware(string id)` Ambiguity**: Lookup prioritizes hardware ID (e.g., `"DAS_123"`) over serial number, but falls back to serial if ID fails. If the ID contains `_` (e.g., `"SN_123"`), it truncates to `"SN"` for serial matching, risking incorrect matches.
- **`Channels` Setter Sorts In-Place**: The setter sorts the input list and replaces `_channels`, but does not validate channel uniqueness or consistency with `_hardware.ISOChannels`.
- **`IsDummy()` Substring Match**: `IsDummy()` uses `Contains("Dummy")`, which may yield false positives (e.g., `"MyDummyDAS"`).
- **`DASHardwareList` Singleton Initialization**: Thread-safety is not guaranteed (no locking in `GetList()`).
- **Hardcoded Prototype Filter**: Prototype exclusion uses a magic string `"Prototype"` (comment notes `/*DbOperations.DAS.PROTOTYPE_POSITION*/` suggests a constant should be used).
- **`GetChannelValues` Field Names**: Uses `DbOperations.DAS.DASChannelFields` enum values directly as keys; mismatches here would cause DB schema errors.
- **No Validation in `DASSettings`**: Properties lack validation (e.g., negative `SampleRate` or `PreTriggerSeconds` allowed).
None identified beyond these source-observable quirks.

View File

@@ -0,0 +1,197 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/RegionsAndZones/Zone.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/RegionsAndZones/RegionAdorner.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/RegionsAndZones/Region.cs
generated_at: "2026-04-16T04:59:50.772455+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "086bec3733d0d7e4"
---
# Documentation: `Region` and `Zone` Classes (DatabaseExport Module, Version 57)
---
## 1. Purpose
This module provides data structures and UI adorning logic for representing and manipulating *regions* and *zones* within medical imaging test object templates, conforming to ISO 13499 standards. The `Zone` class encapsulates a named area of an image (with optional picture, description, and associated regions), while the `Region` class defines a rectangular sub-region with associated MME (Medical Monitoring Equipment) metadata (e.g., direction, filter class, transducer location). The `RegionAdorner` class enables interactive drawing and manipulation of regions on WPF `Image` elements. Together, they support editing, serialization, and ISO-compliant code generation for test object configurations.
---
## 2. Public Interface
### `Zone` Class (`Zone.cs`)
| Member | Signature | Description |
|--------|-----------|-------------|
| **Constructor** | `Zone(TemplateZone z, TestObjectTemplate template)` | Initializes a `Zone` from a `TemplateZone` and `TestObjectTemplate`. Loads picture, sets description, and constructs `Region` objects from `z.TemplateRegions`. |
| `Name` | `string Name { get; set; }` | Gets or sets the zone name (from `z.ZoneName`). |
| `Description` | `string Description { get; set; }` | Gets or sets the zone description (from `z.Description`; defaults to `""` if null). |
| `Image` | `string Image { get; set; }` | Gets or sets the picture filename (from `z.Picture`). |
| `ISODllZone` | `TemplateZone ISODllZone { get; }` | Immutable reference to the underlying `TemplateZone` object. |
| `AllPictures` | `string[] AllPictures { get; }` | Returns an alphabetically sorted array of all picture filenames (by `FileInfo.FullName`) in the `"ZonePictures"` subdirectory of `AppDomain.CurrentDomain.BaseDirectory`. |
| `PictureIndex` | `int PictureIndex { get; set; }` | Gets or sets the index of the currently selected picture in `AllPictures`. Setting to `< 0` clears `PictureSource`; otherwise, loads and sets `BitmapImage` from `_fileNames[value].FullName`. |
| `GetPictureName()` | `string GetPictureName()` | Returns the filename of the picture at `_pictureIndex`, or `""` if `_pictureIndex < 0`. |
| `PictureSource` | `System.Windows.Media.ImageSource PictureSource { get; set; }` | Gets or sets the WPF `ImageSource` for the currently selected picture. Initialized to `null`. |
| `Regions` | `Region[] Regions { get; set; }` | Gets or sets the array of `Region` objects associated with this zone. Internally stored as `List<Region>`. |
#### Nested Type: `FileInfoComparer`
| Member | Signature | Description |
|--------|-----------|-------------|
| `Compare` | `int IComparer<FileInfo>.Compare(FileInfo left, FileInfo right)` | Compares two `FileInfo` objects by `FullName`. Handles `null` inputs (`null < non-null`). |
---
### `Region` Class (`Region.cs`)
| Member | Signature | Description |
|--------|-----------|-------------|
| **Constructors** | `Region(RegionAdorner adorner, TestObjectTemplate template)`<br>`Region(TestObjectTemplate template, TemplateRegion r)` | First: Creates a *new* region (e.g., for drawing), initializes defaults (`"New region"`, `"Describe region"`), and populates ISO settings from `template`.<br>Second: Loads region from persisted `TemplateRegion` (e.g., deserialization), including coordinates, ISO codes, and filters channels. |
| `RegionName` | `string RegionName { get; set; }` | Gets or sets the region name. Triggers `InvalidateVisual()` on change. |
| `RegionDescription` | `string RegionDescription { get; set; }` | Gets or sets the region description. Triggers `InvalidateVisual()` on change. |
| `RegionUpperLeft` | `Point RegionUpperLeft { get; set; }` | Gets or sets the upper-left coordinate of the region (WPF `Point`, in pixel space). |
| `RegionBottomRight` | `Point RegionBottomRight { get; set; }` | Gets or sets the bottom-right coordinate of the region (WPF `Point`, in pixel space). |
| `RegionDirection` | `MMEDirections RegionDirection { get; set; }` | Gets or sets the direction (e.g., `"A"`, `"S"`, `"?"`). Triggers `SetISOCode()`. |
| `RegionFilterClass` | `MMEFilterClasses RegionFilterClass { get; set; }` | Gets or sets the filter class. Updates `_filterClassIndex` and triggers `SetISOCode()`. |
| `RegionFineLocation1/2/3` | `MMEFineLocations1/2/3 RegionFineLocation1/2/3 { get; set; }` | Gets or sets fine location properties. Each triggers `SetISOCode()`. |
| `RegionMainLocation` | `MMETransducerMainLocation RegionMainLocation { get; set; }` | Gets or sets the main transducer location. Triggers `SetISOCode()`. |
| `RegionPhysicalDimension` | `MMEPhysicalDimensions RegionPhysicalDimension { get; set; }` | Gets or sets the physical dimension (e.g., `"mm"`, `"??"`). Triggers `SetISOCode()`. |
| `RegionPosition` | `MMEPositions RegionPosition { get; set; }` | Gets or sets the position (e.g., `"P1"`, `"?"`). Triggers `SetISOCode()`. |
| `RegionTestObject` | `MMETestObjects RegionTestObject { get; set; }` | Gets or sets the associated test object (from ISO code or template). |
| `RegionChannels` | `TestObjectTemplateChannel[] RegionChannels { get; set; }` | Gets or sets the list of channels *filtered* by current region settings. Setting triggers `DetermineAvailableISOSettings()`. |
| `RegionUIChannels` | `TemplateChannelUI[] RegionUIChannels { get; set; }` | Gets or sets the UI channel list corresponding to `RegionChannels`. |
| `ISOCode` | `string ISOCode { get; set; }` | Gets or sets the 16-character ISO code (e.g., `"A1B2C3D4E5F6G7H8"`). Computed from `SetISOCode()` using all region properties. |
| `AllDirections`, `AllFilterClasses`, `AllFineLocations1/2/3`, `AllMainLocations`, `AllPhysicalDimensions`, `AllPositions` | `T[] AllX { get; set; }` | Arrays of available ISO enum values (e.g., `MMEDirections[]`). Each has a corresponding `AllXStrings` property (e.g., `string[] AllDirectionsStrings`). Setting populates the string array from `Text_L1` (or `"?"`, `"??"`, `"????"` for nulls). |
| `AllDirectionsStrings`, `AllFilterClassStrings`, `AllFineLocations1Strings`, `AllFineLocations2Strings`, `AllFineLocations3Strings`, `AllMainLocationsStrings`, `AllPhysicalDimensionStrings`, `AllPositionStrings` | `string[] AllXStrings { get; set; }` | String representations of the corresponding enum arrays. |
| `RegionAddVisibility` | `Visibility RegionAddVisibility { get; set; }` | Gets or sets UI visibility for "add region" controls. Default: `Visible`. |
| `RegionDeleteVisibility` | `Visibility RegionDeleteVisibility { get; set; }` | Gets or sets UI visibility for "delete region" controls. Default: `Hidden`. |
| `Template` | `TestObjectTemplate Template { get; set; }` | Gets or sets the parent template. Setting triggers `DetermineAvailableISOSettings()`. |
| `ToISORegion(TestObjectTemplate, Zone, int)` | `TemplateRegion ToISORegion(TestObjectTemplate template, Zone zone, int number)` | Serializes this `Region` to a `TemplateRegion` object, converting `Point` coordinates to `System.Drawing.Point` and handling nulls with ISO defaults (`"?"`, `"??"`, etc.). |
---
### `RegionAdorner` Class (`RegionAdorner.cs`)
| Member | Signature | Description |
|--------|-----------|-------------|
| **Constructor** | `RegionAdorner(UIElement adornedElement, TestObjectTemplate template, Contexts context)` | Creates a new adorner for an `Image`. Initializes `_region`, `SelectRect`, `_geometry`, and `_path` (blue, semi-transparent stroke). Attaches mouse event handlers. |
| `GetUpperLeft()` | `Point GetUpperLeft()` | Returns the *upper-left* point of `SelectRect`, adjusted for image scaling (difference between `RenderSize` and `Source` dimensions). |
| `GetLowerRight()` | `Point GetLowerRight()` | Returns the *lower-right* point of `SelectRect`, similarly scaled. Returns `(0,0)` if `AdornedElement.Source` is `null`. |
| `IsNew` | `bool IsNew { get; set; }` | Gets or sets whether this adorner represents a *new* region being drawn. Updates `RegionAddVisibility`/`RegionDeleteVisibility` accordingly. |
| `AnchorPoint` | `Point AnchorPoint { get; set; }` | Gets or sets the starting point for drawing (set on `MouseDown`). |
| `SelectRect` | `Rect SelectRect { get; set; }` | Gets or sets the current selection rectangle. Updates `MyRegion.RegionUpperLeft`/`RegionBottomRight` via `GetUpperLeft()`/`GetLowerRight()`. |
| `MyRegion` | `Region MyRegion { get; set; }` | Gets or sets the associated `Region` instance. |
| `Context` | `Contexts Context { get; set; }` | Gets or sets the editing context (`EditTestObject` or `EditTestObjectTemplate`). |
| `OnRegionSelected` | `event RegionSelectedHandler OnRegionSelected` | Event raised on `MouseLeftButtonDown`. |
| `OnEndSelection` | `event EndSelectionHandler OnEndSelection` | Event raised on `MouseLeftButtonUp` (after `EndSelection()`). |
| `Region_MouseMove` | `void Region_MouseMove(...)` | Handles mouse drag: calls `DrawSelection()` (if `IsNew`) or `MoveSelection()` (if editing). Invalidates visuals. |
| `DrawSelection` | `void DrawSelection(...)` | Updates `SelectRect` to a rectangle between `AnchorPoint` and current mouse position. |
| `MoveSelection` | `void MoveSelection(...)` | Moves `SelectRect` by the delta from the previous mouse position (`p1`). |
| `EndSelection` | `void EndSelection(...)` | Releases mouse capture and raises `OnEndSelection`. |
#### Nested Type: `Contexts`
| Value | Description |
|-------|-------------|
| `EditTestObject` | Context for editing a specific test object instance. |
| `EditTestObjectTemplate` | Context for editing a reusable template. |
---
## 3. Invariants
- **`Zone`**:
- `Description` is never `null`; defaults to `""` if `z.Description` is `null`.
- `Image` is set from `z.Picture`; if non-empty, the code attempts to load the image from `"ZonePictures/{Image}"`.
- `PictureIndex` is `-1` if the image file does not exist or fails to load (e.g., invalid format).
- `Regions` is always initialized as a `List<Region>`; populated from `z.TemplateRegions` in the constructor.
- **`Region`**:
- `ISOCode` is always 16 characters (uses `"?"`, `"??"`, `"????"` for null/missing values).
- `RegionChannels` and `RegionUIChannels` are filtered based on current ISO settings (direction, filter class, fine locations, etc.) via `FilterRegionChannels()`.
- `DetermineAvailableISOSettings()` ensures that each enum property (e.g., `RegionDirection`) includes a wildcard option (`"?"`, `"??"`) in its `AllX` array.
- `RegionTestObject` is set from the first distinct test object in `RegionChannels` during `DetermineAvailableISOSettings()`.
- **`RegionAdorner`**:
- `SelectRect` is always synchronized with `MyRegion.RegionUpperLeft`/`RegionBottomRight`.
- Scaling adjustments in `GetUpperLeft()`/`GetLowerRight()` assume the `AdornedElement` is an `Image` with a `Source` of known dimensions.
---
## 4. Dependencies
### Imports/References (from source):
- **WPF namespaces**: `System.Windows.*` (`Adorner`, `Image`, `MouseEventArgs`, `Point`, `Rect`, `Visibility`, `Brushes`, `Path`, `RectangleGeometry`, `ImageSource`, `BitmapImage`).
- **System.IO**: `AppDomain`, `Directory`, `Path`, `FileInfo`.
- **Custom types** (inferred from usage):
- `TestObjectTemplate`, `TemplateRegion`, `TemplateZone`, `TestObjectTemplateChannel`, `TemplateChannelUI`
- ISO enums: `MMEDirections`, `MMEFilterClasses`, `MMEFineLocations1/2/3`, `MMETransducerMainLocation`, `MMEPhysicalDimensions`, `MMEPositions`, `MMETestObjects`
- `ISO13499FileDb.IsoDb` (static singleton with methods like `GetDirectionByIso`, `GetFilterClassByIso`, etc.)
- `ISO.IsoCode.GetString(...)` (static method for code generation)
- `Common.BindableBase` (commented out in `Zone` class definition; not used)
### Inferred Consumers:
- UI layers (WPF) that use `RegionAdorner` to draw/edit regions on images.
- Serialization/deserialization logic (via `ToISORegion` and `Region(TemplateRegion)` constructor).
- Code that accesses `Zone.Regions` and `Region.RegionChannels` for analysis or export.
---
## 5. Gotchas
- **`PictureIndex` and `AllPictures`**:
`AllPictures` is lazily initialized on first access and sorted by `FileInfo.FullName`. If the `"ZonePictures"` directory is missing or inaccessible, `_fileNames` remains `null`, and `PictureIndex` will always be `-1`.
- **Scaling in `GetUpperLeft()`/`GetLowerRight()`**:
The scaling logic assumes the `AdornedElement` is an `Image` with a `Source` whose dimensions differ from `RenderSize`. If `Source` is `null`, `GetLowerRight()` returns `(0,0)`; `GetUpperLeft()` may throw if `Source` is `null` (though not explicitly guarded).
- **Null Handling in ISO Enums**:
Enum properties (e.g., `RegionDirection`) may be `null`, and their string representations use `"?"` (or `"??"`, `"????"`). This is critical for ISO code generation.
- **Channel Filtering**:
`FilterRegionChannels()` mutates `_regionChannels`/`_regionUIChannels` in-place. If `RegionChannels` is set externally, `DetermineAvailableISOSettings()` is triggered, which may overwrite user selections if no channels match.
- **`FileInfoComparer`**:
Compares by `FullName`, not `Name`. This may cause unexpected ordering if paths differ (e.g., `"ZonePictures/a.png"` vs `"ZonePictures/sub/a.png"`).
- **No `INotifyPropertyChanged`**:
The `Zone` class has `Common.BindableBase` commented out. Changes to properties (e.g., `PictureIndex`, `Regions`) do not raise change notifications (unless handled elsewhere).
- **`IsNew` Side Effects**:
Setting `IsNew = true` hides delete controls and shows add controls, but does *not* reset `SelectRect` or `MyRegion` coordinates.
- **`ToISORegion` Coordinate Conversion**:
Converts `Point` (WPF, `double`) to `System.Drawing.Point` (WinForms, `int`) via `Convert.ToInt32(...)`, which truncates (not rounds). May cause precision loss.
- **No Thread Safety**:
`AllPictures` uses non-thread-safe lazy initialization (`_fileNames`). Concurrent access may cause race conditions.
- **`_pictureIndex` Field**:
`_pictureIndex` is private and used only in `PictureIndex`. It is not synchronized with `PictureSource` if set directly (though the property setter handles this).
- **`RegionAdorner` Mouse Capture**:
`EndSelection` calls `ReleaseMouseCapture()`, but there is no explicit `CaptureMouse()` call in `DrawSelection`/`MoveSelection`. Mouse events may fire even after drag ends if capture was not held.
- **Hardcoded Paths**:
`"ZonePictures"` is hardcoded as the picture directory. No configuration or fallback is provided.
- **`TemplateRegion` Constructor**:
`ToISORegion` passes `template.IsLocalOnly` to `TemplateRegion` constructor, but `IsLocalOnly` is not used elsewhere in the provided code.
- **`Region` Constructor Overload**:
The `Region(TestObjectTemplate, TemplateRegion)` constructor does *not* call `FilterRegionChannels()` until after setting all properties, but `SetISOCode()` is called at the end. This is safe, but the intermediate state may be inconsistent.
- **`AllX` Properties**:
Setting `AllX` (e.g., `AllDirections`) populates `AllXStrings` from `Text_L1`, but setting `AllXStrings` does *not* update `AllX`. This breaks two-way binding if used.
- **`RegionAdorner` Mouse Events**:
`Region_MouseLeftButtonDown` raises `OnRegionSelected`, but does *not* set `AnchorPoint` or begin selection. This must be handled externally (e.g., by the adorner layer).
- **`RegionAdorner` `_MeasuredSize`**:
`_MeasuredSize` is set from `adornedElement.RenderSize` in the constructor. If the element resizes later, scaling calculations become incorrect.
- **`RegionAdorner` `IsNew` Default**:
`IsNew` defaults to `true`, meaning the adorner starts in "drawing" mode unless explicitly set to `false`.
- **`RegionAdorner` `AnchorPoint` Initialization**:
`AnchorPoint` is not initialized in the constructor. If `DrawSelection` is called before `AnchorPoint` is set, it will be `

View File

@@ -0,0 +1,55 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TabPage/TabPageCommon.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TabPage/TabPage.cs
generated_at: "2026-04-16T04:59:00.585426+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "2bb1e521c729f483"
---
# TabPage
## Documentation: `TabPageCommon` and Related Types
### 1. Purpose
This module defines a lightweight, hierarchical data model for representing UI tab structures during database export operations in legacy (Version 57) contexts. It provides base abstractions (`TabPageCommon`, `TabPageItem`, `TabPageItemGroup`) to encapsulate tab content and grouping, and a singleton `TabPageSource` to expose a global collection of tab groups. The model is intended for *data export* (e.g., serialization, reporting), not runtime UI rendering—though it references `UserControl`, suggesting it may originate from or interface with WPF UI components.
### 2. Public Interface
- **`TabPageCommon`** (abstract class)
- `public virtual string GetName()` → Returns the value of `UniqueId`.
- `public string UniqueId { get; set; }` → A string identifier; defaults to `string.Empty`. Used as the logical name via `GetName()`.
- **`TabPageItem`** (class, inherits `TabPageCommon`)
- `public UserControl Content { get; set; }` → Holds the WPF UI content for the tab (nullable). Represents a single tab page.
- **`TabPageItemGroup`** (class, inherits `TabPageCommon`)
- `public ObservableCollection<TabPageItem> Items { get; }` → A mutable collection of `TabPageItem` instances belonging to this group. Initialized lazily (non-null).
- **`TabPageSource`** (static singleton class)
- `public ObservableCollection<TabPageItemGroup> AllGroups { get; }` → Global collection of tab groups.
- `public static IEnumerable<TabPageItemGroup> GetGroups(string uniqueid)` → Returns `_source.AllGroups` *only if* `uniqueid == "AllGroups"`; otherwise throws `ArgumentException`.
- *Note:* The method name and parameter suggest extensibility (e.g., filtering by ID), but only one value is currently supported.
### 3. Invariants
- `TabPageCommon.UniqueId` must be set to a non-null, non-whitespace string for meaningful identification (though not enforced by code).
- `TabPageItem.Content` may be `null`, but no validation prevents this.
- `TabPageItemGroup.Items` is never `null` (initialized inline) and uses `ObservableCollection<T>`, implying change notifications are expected.
- `TabPageSource.GetGroups()` enforces a strict invariant: **only** `"AllGroups"` is accepted as `uniqueid`; any other value throws `ArgumentException`.
- `TabPageSource` is a singleton: `_source` is initialized once and reused.
### 4. Dependencies
- **Depends on**:
- `System` (core types: `ArgumentException`, `IEnumerable<T>`, `ObservableCollection<T>`)
- `System.Collections.Generic` (`IEnumerable<T>`)
- `System.Collections.ObjectModel` (`ObservableCollection<T>`)
- `System.Windows.Controls` (`UserControl`)
- **Depended on by**:
- Unknown from source alone. Given the namespace `DatabaseExport`, this module is likely consumed by export-specific logic (e.g., serialization to XML/JSON, reporting tools). No explicit references to consumers are present.
### 5. Gotchas
- **Misleading `GetGroups` signature**: Despite accepting a `uniqueid` parameter, it only supports `"AllGroups"`. This suggests incomplete implementation or legacy design—future extensions may break callers if they assume filtering capability.
- **`GetName()` is trivial**: It directly returns `UniqueId` without normalization or fallback logic. Callers must ensure `UniqueId` is set meaningfully.
- **`UserControl` coupling**: Using `System.Windows.Controls.UserControl` ties this module to WPF, despite being in a *database export* context. This may cause issues if reused in non-UI or cross-platform scenarios.
- **No immutability guarantees**: `AllGroups` and `Items` are mutable collections. External code can modify them (add/remove groups/items), which may lead to race conditions if accessed concurrently (though no threading model is specified).
- **No documentation on lifecycle**: It is unclear how `TabPageSource.AllGroups` is populated—no initialization methods or event hooks are visible.

View File

@@ -0,0 +1,124 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestMetaData/CustomerDetails.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestMetaData/LabratoryDetails.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestMetaData/TestEngineerDetails.cs
generated_at: "2026-04-16T04:59:22.874172+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "283afdf9f6a03436"
---
# Documentation: Test Metadata Wrappers (Version 57)
## 1. Purpose
This module provides managed wrapper classes for low-level `ISO.*Details` types (`CustomerDetails`, `LabratoryDetails`, `TestEngineerDetails`) used in database export operations for Version 57 of the database schema. Its primary role is to encapsulate and standardize access to these domain entities—offering lazy-loaded, sorted, and deduplicated collections via singleton list managers (`CustomerDetailsList`, `LabratoryDetailsList`, `TestEngineerDetailsList`). It ensures consistent handling of a special "(none)" placeholder entry and provides thread-safe access to metadata used in test reporting and export workflows.
## 2. Public Interface
### `CustomerDetails`
- **`CustomerDetails()`**
Default constructor. Initializes internal `_customerDetails` with a new `ISO.CustomerDetails`, setting its `Name` to `"(none)"`.
- **`CustomerDetails(ISO.CustomerDetails customerDetails)`**
Copy constructor. Creates a new `ISO.CustomerDetails` instance from the provided `customerDetails`.
- **`string Name { get; set; }`**
Gets or sets the `Name` property of the underlying `ISO.CustomerDetails`.
- **`ISO.CustomerDetails GetISOCustomer()`**
Returns the internal `ISO.CustomerDetails` instance.
- **`override string ToString()`**
Returns the `Name` property.
### `CustomerDetailsList`
- **`static CustomerDetailsList CustomerList { get; }`**
Singleton accessor.
- **`CustomerDetails[] Customers { get; }`**
Returns a sorted (by `Name`, ordinal) array of all `CustomerDetails`, including the "(none)" entry. Thread-safe via `lock` and lazy initialization.
- **`CustomerDetails[] GetAllCustomers()`**
Returns a fresh array containing a new "(none)" `CustomerDetails` followed by all `CustomerDetails` created from `ISO.CustomerDetails.GetAllCustomerDetails()`.
- **`CustomerDetails GetCustomerDetail(string name)`**
Returns the first `CustomerDetails` in `Customers` (parallel query) matching `name`, or `null` if none found.
---
### `LabratoryDetails`
- **`LabratoryDetails()`**
Default constructor. Initializes `_lab` with a new `ISO.LabratoryDetails`, setting `Name` to `"(none)"`.
- **`LabratoryDetails(ISO.LabratoryDetails lab)`**
Copy constructor. Creates a new `ISO.LabratoryDetails` instance from `lab`.
- **`string Name { get; set; }`**
Gets or sets the `Name` property of `_lab`.
- **`ISO.LabratoryDetails GetIsoLab()`**
Returns the internal `_lab` instance.
- **`override string ToString()`**
Returns the `Name` property.
### `LabratoryDetailsList`
- **`protected LabratoryDetailsList()`**
Protected constructor (enforces singleton via private instantiation).
- **`static LabratoryDetailsList LabratoryList { get; }`**
Singleton accessor.
- **`LabratoryDetails[] Labs { get; }`**
Returns a sorted (by `Name`, ordinal) array of all `LabratoryDetails`, including "(none)". Thread-safe via `lock` and lazy initialization.
- **`LabratoryDetails GetLab(string name)`**
Returns the `LabratoryDetails` for `name` from the internal `_labs` dictionary (if populated), or `null`. Includes exception handling (logs via `APILogger` on failure).
- **`private LabratoryDetails[] GetAllLabs()`**
Returns a fresh array containing a new "(none)" `LabratoryDetails` followed by all `LabratoryDetails` created from `ISO.LabratoryDetails.GetAllLabratoryDetails()`. Includes exception handling.
---
### `TestEngineerDetails`
- **`TestEngineerDetails()`**
Default constructor. Initializes `_testEngineerDetails` with a new `ISO.TestEngineerDetails`, setting `Name` to `"(none)"`.
- **`TestEngineerDetails(ISO.TestEngineerDetails testEngineerDetails)`**
Copy constructor. Creates a new `ISO.TestEngineerDetails` instance from `testEngineerDetails`.
- **`string Name { get; set; }`**
Gets or sets the `Name` property of `_testEngineerDetails`.
- **`ISO.TestEngineerDetails GetISOTestEngineer()`**
Returns the internal `_testEngineerDetails` instance.
- **`override string ToString()`**
Returns the `Name` property.
### `TestEngineerDetailsList`
- **`static TestEngineerDetailsList TestEngineerList { get; }`**
Singleton accessor.
- **`TestEngineerDetails[] TestEngineers { get; }`**
Returns a sorted (by `Name`, using `CompareTo`) array of all `TestEngineerDetails`, including "(none)". Thread-safe via `lock` and lazy initialization.
- **`TestEngineerDetails[] GetAllTestEngineers()`**
Returns a fresh array containing a new "(none)" `TestEngineerDetails` followed by all `TestEngineerDetails` created from `ISO.TestEngineerDetails.GetAllTestEngineerDetails()`.
- **`TestEngineerDetails GetTestEngineerDetail(string name)`**
Returns the first `TestEngineerDetails` in `TestEngineers` (parallel LINQ query) matching `name`, or `null`.
## 3. Invariants
- **"(none)" Placeholder**: Each list (`CustomerDetails`, `LabratoryDetails`, `TestEngineerDetails`) *always* includes a special entry with `Name == "(none)"` as the first element returned by `GetAll*()` methods.
- **Deduplication**: The internal `_customers`, `_labs`, and `_testEngineers` dictionaries use `Name` as the key, ensuring only one entry per unique name (last one wins in case of duplicates in `GetAll*()`).
- **Sorted Output**: The `Customers`, `Labs`, and `TestEngineers` properties return arrays sorted by `Name` using ordinal string comparison (`String.Compare(..., StringComparison.Ordinal)` or `CompareTo`).
- **Thread Safety**: All list properties (`Customers`, `Labs`, `TestEngineers`) and their underlying population methods (`PopulateCustomers`, `PopulateList`, `PopulateEngineers`) are guarded by dedicated static `lock` objects. However, `GetCustomerDetail` and `GetTestEngineerDetail` use `AsParallel()` on the *already-computed* `Customers`/`TestEngineers` array, which is safe but not optimized.
- **Null Handling**: `Compare*` methods explicitly handle `null` inputs (returning `-1`, `0`, or `1` as appropriate). `Get*Detail` methods return `null` if no match is found.
## 4. Dependencies
- **Internal Dependencies**:
- `ISO.CustomerDetails`, `ISO.LabratoryDetails`, `ISO.TestEngineerDetails` (from the `ISO` namespace) — core data types being wrapped.
- `ISO.CustomerDetails.GetAllCustomerDetails()`, `ISO.LabratoryDetails.GetAllLabratoryDetails()`, `ISO.TestEngineerDetails.GetAllTestEngineerDetails()` — static methods to fetch raw data.
- **External Dependencies**:
- `DTS.Utilities.Logging.APILogger` (used in `LabratoryDetailsList` only) — for logging exceptions during lab retrieval.
- Standard .NET: `System`, `System.Collections.Generic`, `System.Linq`.
- **Depended Upon**: This module is part of `DatabaseExport` namespace and is likely consumed by higher-level export/reporting logic in the `DataPRO` system (not visible in source).
## 5. Gotchas
- **Inconsistent Naming**: Class is named `LabratoryDetails` (misspelled) instead of `LaboratoryDetails`. This typo is propagated in both class and list names.
- **Exception Swallowing**: `LabratoryDetailsList` silently swallows exceptions in `GetLab` and `GetAllLabs` (logs only via `APILogger`), which may hide failures during lab data loading.
- **Race Condition in `Populate*`**: While `Populate*` methods are called under lock, they are not idempotent-safe in all cases:
- `CustomerDetailsList.PopulateCustomers()` checks `if (null != _customers) return;` — safe.
- `TestEngineerDetailsList.PopulateEngineers()` does *not* check `_testEngineers != null` before reassigning — safe only because its called under lock *and* only once.
- `LabratoryDetailsList.PopulateList()` has the same safe guard (`if (null != _labs) return;`).
→ All are safe *in practice* due to locking, but the pattern is fragile.
- **Redundant Copying**: Both constructors (`CustomerDetails(ISO.CustomerDetails)`, etc.) create a *new* instance of the underlying `ISO.*Details` (via copy constructor), not a reference wrapper. This is intentional but may be surprising if mutation of the returned `ISO.*Details` is expected to affect the wrappers internal state.
- **Inconsistent `Get*Detail` Implementations**:
- `CustomerDetailsList.GetCustomerDetail` and `TestEngineerDetailsList.GetTestEngineerDetail` use `AsParallel()` on the *already-computed* array — unnecessary overhead for small lists.
- `LabratoryDetailsList.GetLab` uses direct dictionary lookup (`_labs.ContainsKey`) — more efficient, but only works *after* `Labs` property has been accessed (since `_labs` is populated in `Labs` getter, not eagerly).
- **No Validation**: No validation on `Name` values (e.g., empty strings, duplicates in raw data) — relies on underlying `ISO.*` types or data source to prevent invalid names.
- **Hardcoded Placeholder**: The `"(none)"` string is hardcoded in constructors. No constant or resource reference (despite commented-out `Strings.StringResources.TestTemplate_EmptyListName` in `TestEngineerDetails`).

View File

@@ -0,0 +1,201 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/TemplateChannelUI.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/GroupTemplateTableInfo.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/TestObjectList.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/TestObjectTemplateCollection.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/TestTestObject.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestObject/TestObjectTemplate.cs
generated_at: "2026-04-16T05:00:11.636548+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "5a4f5e976b551f99"
---
# Documentation: `DatabaseExport.TestObject` Module
## 1. Purpose
This module provides a legacy (Version57) abstraction layer over ISO 13499 test object and template data for database export operations. It encapsulates domain entities—such as `TestObject`, `TestObjectTemplate`, and `TestTestObject`—and their relationships, enabling retrieval, manipulation, and serialization of test configuration data (including channel definitions, zones, and metadata) from a database-backed ISO 13499 file structure. It serves as an intermediate layer between raw database access (`DbOperations`, `ISO13499FileDb`) and higher-level UI or export logic, specifically supporting legacy workflows where templates and test objects must be exported or migrated.
## 2. Public Interface
### `TemplateChannelUI`
- **Constructor**: `public TemplateChannelUI(TestObjectTemplateChannel channel)`
- Wraps a `TestObjectTemplateChannel` instance for UI binding purposes. No additional behavior beyond storage.
### `GroupTemplateTableInfo`
- **Constructor**: `public GroupTemplateTableInfo(string templateName, SerializedSettings.ISOSupportLevels isoSupportLevel, bool sysBuilt, string templateDescription, DateTime lastModified, string lastModifiedBy, bool embedded)`
- Immutable data transfer object (DTO) representing metadata for a test object template.
- **Properties**:
- `TemplateName` (`string`)
- `ISOSupportLevel` (`SerializedSettings.ISOSupportLevels`)
- `SysBuilt` (`bool`)
- `TemplateDescription` (`string`)
- `LastModified` (`DateTime`)
- `LastModifiedBy` (`string`)
- `Embedded` (`bool`)
- **Overrides**: `ToString()` returns `TemplateName`.
### `TestObjectList`
- **Static Property**: `public static TestObjectList TestObjectsList { get; }`
- Implements lazy-initialized singleton pattern (thread-safe via `lock`). Returns the single instance of `TestObjectList`.
- **Instance Method**: `public List<string> GetAllGroupSerialNumbers()`
- Queries `tblTestObjects` for all `SerialNumber` values, deduplicates, and returns them as a `List<string>`.
- **Instance Method**: `public TestObject GetTestObject(string serialNumber)`
- Retrieves a `TestObject` by `serialNumber` using `ISO.TestObject.GetTestObject`, wrapping the result in a new `TestObject` instance with `SysBuilt` flag preserved. Returns `null` if not found.
- **Instance Method**: `public TestObject GetAddedGroup(string serialNumber)`
- Alias for `GetTestObject`. Delegates directly to it.
### `TestObjectTemplateCollection`
- **Static Property**: `public static TestObjectTemplateCollection TemplateCollection { get; }`
- Thread-safe lazy singleton via double-checked locking (`volatile` + null-coalescing assignment).
- **Instance Method**: `public GroupTemplateTableInfo[] GetAllTemplates(bool bIncludeEmbeddedAndSysBuilt = true)`
- Queries `tblTestObjectTemplates`. If `bIncludeEmbeddedAndSysBuilt` is `false`, filters rows where `Embedded = 0 OR NULL` and `SysBuilt = 0`.
- For each row, constructs a `GroupTemplateTableInfo`:
- `ISOSupportLevel` is inferred: `NO_ISO` if `TestObjectType` contains `NON_ISO_TESTOBJECT_CHANNEL_TYPE` or `NONISOCHANNELTYPE`; otherwise `ISO_ONLY`.
- `Embedded` is safely parsed (treats `DBNull` as `false`).
- Returns array of `GroupTemplateTableInfo`.
- **Instance Property**: `public TestObjectTemplate SysBuiltTestObjectTemplate { get; }`
- Returns the static `_sysBuiltTestObjectTemplate` field (currently unassigned in source; always `null`).
- **Instance Method**: `public TestObjectTemplate GetTemplate(string templateId)`
- Retrieves a template by `templateId` via `ISO.TestObjectTemplate.GetTemplate`.
- If not found, returns a default-constructed `TestObjectTemplate()`; otherwise wraps the ISO template in a new `TestObjectTemplate`.
### `TestTestObject`
- **Constructor**: `public TestTestObject(TestObject obj)`
- Base constructor; delegates to `TestObject` base class.
- **Properties**:
- `Position` (`MMEPositions`)
- Gets/sets position key (`#` = channel defaults, `@` = user-set/multiple).
- On set: updates `_position`, toggles `GroupPositionComboBoxVisible`/`GroupPositionButtonVisible`, and if not `UserSetKey`, propagates position to all required sensors with valid serial numbers.
- `GroupPositionComboBoxVisible`, `GroupPositionButtonVisible` (`System.Windows.Visibility`)
- Visibility depends on `ISOSupportLevel`: always `Collapsed` if `NO_ISO`; otherwise reflects internal `_groupPosition*` fields.
- `TestObject` (`MMETestObjects`)
- Gets/sets the test object. On set, propagates `TestObject.Test_Object` to all required sensors with valid serial numbers.
- `AvailablePositions` (`MMEPositions[]`)
- Returns all positions from `ISO13499FileDb.IsoDb.GetPositions()`.
- `AvailableGroupPositions` (`MMEPositions[]`)
- Returns `AvailablePositions` + a special `ChannelDefaultsKey` (`#`) entry and a `UserSetKey` (`@`) entry.
- `ExcitationWarmupTimeMS` (`int`)
- Gets/sets warmup time (ms), default from `Properties.Settings.Default.DefaultTestExcitationWarmupMS`.
- `TargetSampleRate` (`double`)
- Gets/sets target sample rate.
- **Constants**:
- `ChannelDefaultsKey = "#"`
- `UserSetKey = "@"`
- **Methods**:
- `SetTestObject(string s)`, `SetPosition(string s)`
- Setters that bypass property change propagation logic (e.g., no sensor propagation); only update backing field and raise `OnPropertyChanged`.
### `TestObjectTemplate`
- **Constants**:
- `NON_ISO_TESTOBJECT_CHANNEL_TYPE = "x_NonISOTestObjectType_x"`
- `NON_ISO_TESTOBJECT_NAME = "x_NonISOTestObjectName_x"`
- **Properties**:
- `LastModifiedBy` (`string`, default `"N/A"`)
- `LastModified` (`DateTime`, default `SqlDateTime.MinValue`)
- `CurrentZoneIndex` (`int`)
- Setter updates `CurrentZone` and `AreZoneControlsEnabled`.
- `CurrentZone` (`Zone`)
- Setter toggles `AreZoneControlsEnabled` based on nullability.
- `AreZoneControlsEnabled` (`bool`)
- `RequiredChannels` (`List<TestObjectTemplateChannel>`)
- `TemplateParent` (`string`)
- `SysBuilt` (`bool`)
- `Embedded` (`bool`)
- `OriginalTemplateName` (`string`)
- `TemplateName` (`string`)
- `TemplateDescription` (`string`)
- `IsLocalOnly` (`bool`)
- `TestObject` (`MMETestObjects`)
- Setter initializes `AvailableTestObjectTypes` and `TestObjectTypeIndex`.
- `TestObjectType` (`string`)
- Setter populates `_channels` and `TemplateAllChannels`.
- `TemplateAllChannels` (`TestObjectTemplateChannel[]`)
- Getter sorts by `DisplayOrder`; setter builds `TemplateAllUIChannels`.
- `TemplateAllUIChannels` (`TemplateChannelUI[]`)
- `TemplateZones` (`Zone[]`)
- `AvailableTestObjectTypes` (`string[]`)
- Lazy-initialized from `ISO13499FileDb.IsoDb.GetTestObjectTypeForTestObject`.
- `TestObjectTypeIndex` (`int`)
- Getter: index in `AvailableTestObjectTypes`; setter: updates `TestObjectType` and rebuilds channels.
- **Static Methods**:
- `GetNonISOTestObject()`
- Finds or creates a system test object with code `NON_ISO_TESTOBJECT_NAME`. Returns first unused alpha (`A``Z`) or numeric (`0``9`) code. Throws `NotSupportedException` if none available.
- **Instance Methods**:
- `ToISOTestObjectTemplate()`
- Converts this instance to an `ISO.TestObjectTemplate`, including zones, regions, channels, and metadata. Includes extensive logging via `EventLog`.
- `GetValues()`
- Returns a dictionary mapping `GroupTemplateFields` enum names to string values (from the ISO template).
- `GetTemplateChannelValues(TestObjectTemplateChannel channel)`
- Returns a dictionary mapping `GroupTemplateChannelFields` enum names to string values (from the channel).
- **Constructors**:
- `TestObjectTemplate(TestObjectTemplate copy, ref ISO13499FileDb db)`
- Deep copy constructor.
- `TestObjectTemplate(ISO.TestObjectTemplate template, ref ISO13499FileDb db)`
- Wraps an ISO template.
- `TestObjectTemplate()`
- Default constructor: initializes `TestObject` based on `SerializedSettings.ISOSupportLevel`. For `NO_ISO`, calls `InitializeNonISO()`.
## 3. Invariants
- **Singleton Consistency**:
- `TestObjectList.TestObjectsList` and `TestObjectTemplateCollection.TemplateCollection` are lazily initialized singletons. Once created, the same instance persists for the application lifetime.
- **Template Channel Sorting**:
- `TestObjectTemplate.TemplateAllChannels` getter always returns channels sorted by `DisplayOrder`.
- **ISO Support Level Inference**:
- `TestObjectTemplateCollection.GetAllTemplates` infers `ISOSupportLevel` strictly based on `TestObjectType` string content (`NON_ISO_TESTOBJECT_CHANNEL_TYPE` or `NONISOCHANNELTYPE``NO_ISO`; else → `ISO_ONLY`).
- **Embedded Field Handling**:
- `GroupTemplateTableInfo.Embedded` and `TestObjectTemplate.Embedded` safely handle `DBNull` in database queries (treated as `false`).
- **Non-ISO Template Initialization**:
- When `TestObjectTemplate()` is constructed with `NO_ISO` support level, `TestObject` is set to a system-created object with code `NON_ISO_TESTOBJECT_NAME`, and `TestObjectType` is set to `NON_ISO_TESTOBJECT_CHANNEL_TYPE`.
## 4. Dependencies
### Imports/Usings
- `System`, `System.Collections.Generic`, `System.Data` (via `DataRow`, `DataSet`)
- `DatabaseExport` namespace (same module)
- `ISO` namespace (e.g., `ISO.TestObject`, `ISO.TestObjectTemplate`, `ISO13499FileDb`)
- `SerializedSettings` (for `ISOSupportLevels`)
- `Properties.Settings` (for `DefaultTestExcitationWarmupMS`)
- `System.Diagnostics` (for `EventLog`)
### External Dependencies
- **Database**:
- `tblTestObjects` (used by `TestObjectList.GetAllGroupSerialNumbers`)
- `tblTestObjectTemplates` (used by `TestObjectTemplateCollection.GetAllTemplates`)
- **ISO Layer**:
- `ISO13499FileDb.IsoDb` (static property) for database access and metadata lookups.
- `DbOperations.GetCommand()` and `DbOperations.Connection.QueryDataSet()` for SQL execution.
- **UI Framework**:
- `System.Windows.Visibility` (used in `TestTestObject` for WPF visibility properties).
- **Other Modules**:
- `MMEPositions`, `MMETestObjects`, `MMEPossibleChannels` (from `ISO` or related modules).
- `Zone`, `TemplateZone`, `TemplateRegion` (referenced but not defined here; assumed external).
### Dependents
- **Inferred**:
- UI layers (e.g., WPF) consuming `TemplateChannelUI`, `TestTestObject`, `GroupTemplateTableInfo`.
- Export/migration workflows relying on `TestObjectTemplateCollection.GetAllTemplates()` and `TestObjectList.TestObjectsList`.
## 5. Gotchas
- **`SysBuiltTestObjectTemplate` is always `null`**:
- The static field `_sysBuiltTestObjectTemplate` in `TestObjectTemplateCollection` is declared but never assigned. Accessing `SysBuiltTestObjectTemplate` will always return `null`.
- **`TestObjectTemplateCollection.GetAllTemplates()` filters `Embedded` permissive**:
- `DBNull` values in `Embedded` column are treated as `false`, which may differ from database semantics if `NULL` has special meaning.
- **`TestObjectTemplate.GetTemplate()` returns default instance on failure**:
- Returns a new `TestObjectTemplate()` (with default properties) instead of `null` when template is not found, potentially masking errors.
- **`TestTestObject.Position` propagation is conditional**:
- Sensor position updates only occur for required channels with non-whitespace `SensorSerialNumber`. Channels missing these are silently skipped.
- **`TestObjectTemplate()` constructor behavior depends on global settings**:
- Default constructor behavior changes based on `SerializedSettings.ISOSupportLevel`, which may not be obvious to callers expecting consistent initialization.
- **`GetNonISOTestObject()` may throw**:
- If no unused single-character test object codes (`A``Z`, `0``9`) are available, it throws `NotSupportedException` instead of returning `null` or retrying.
- **`TemplateAllChannels` setter rebuilds `TemplateAllUIChannels`**:
- Assigning directly to `TemplateAllChannels` triggers construction of new `TemplateChannelUI` wrappers. This side effect is not obvious from the property name.
- **`CurrentZoneIndex` setter has side effects**:
- Setting `CurrentZoneIndex` updates `CurrentZone` and toggles `AreZoneControlsEnabled`, which may affect UI state unexpectedly if not coordinated.
- **`TestObjectTemplate.ToISOTestObjectTemplate()` logs heavily**:
- Uses `EventLog.Source = "DataPROInstaller"` and writes many entries. May impact performance or cause issues in non-installer contexts (e.g., unit tests).

View File

@@ -0,0 +1,153 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestTemplate/HardwareInclusionInstruction.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestTemplate/TestTemplateLite.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestTemplate/TestTemplateTableObject.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Classes/TestTemplate/TestTemplateList.cs
generated_at: "2026-04-16T04:59:45.231634+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "45cdf642e27469a5"
---
# TestTemplate
## Documentation: `DatabaseExport.TestTemplate` Module (Version 57)
---
### 1. Purpose
This module provides lightweight, read-only representations of test templates stored in the database (`tblTestSetups`) and supporting infrastructure for template management, primarily for export or migration workflows in legacy database versions (v57). It includes classes to load essential metadata from the database without instantiating the full `TestTemplate` object (which may trigger expensive side effects), and utilities to serialize/deserialize sensor settings and manage tag metadata. The module supports operations like retrieving templates by name, listing all templates in a simplified form, and handling special cases like the "Quick checkout" temporary template.
---
### 2. Public Interface
#### `HardwareInclusionInstruction`
- **`HardwareInclusionInstruction(string hardwareId, Actions action)`**
Constructor. Initializes a rule to explicitly include or exclude a specific hardware item from a test, overriding group-based inclusion logic (e.g., to support "DAS-less" groups).
- **`HardwareId { get; }`**
The identifier of the hardware item to which the rule applies.
- **`Action { get; }`**
The action to take: `Actions.Remove` (exclude despite group membership) or `Actions.Add` (include despite absence from groups).
#### `TestTemplateLite`
- **`Name { get; set; }`**
Template name.
- **`Description { get; set; }`**
Template description (defaults to `""`).
- **`RecordingMode { get; set; }`**
Recording mode (e.g., `Recorder`, `CircularBuffer`).
- **`PreTriggerSeconds { get; set; }`**
Pre-trigger duration in seconds. *Behavior*: Returns `0.0` for `Recorder` or `HybridRecorder` modes; otherwise returns the stored value.
- **`PostTriggerSeconds { get; set; }`**
Post-trigger duration in seconds.
- **`LastModified { get; set; }`**
Timestamp of last modification.
- **`LastModifiedBy { get; set; }`**
User who last modified the template.
- **`IsComplete { get; set; }`**
Whether the template is marked as complete.
#### `TestTemplateTableObject`
- **`TestTemplateTableObject(string name, string description, RecordingModes recordingMode, DateTime lastModified, string lastModifiedBy, bool isComplete, string completionErrorMessage, bool useCustomerDetails, string customerDetails, int[] tagIds)`**
Constructor. Initializes a simplified row-like object representing a `tblTestSetups` entry.
- **`Name { get; private set; }`**
Template name.
- **`Description { get; private set; }`**
Template description.
- **`RecordingMode { get; private set; }`**
Recording mode enum value.
- **`LastModified { get; private set; }`**
Last modification timestamp.
- **`LastModifiedBy { get; private set; }`**
Last modifier user ID.
- **`IsComplete { get; private set; }`**
Completion status.
- **`CompletionErrorMessage { get; private set; }`**
Error message if template is incomplete.
- **`UseCustomerDetails { get; private set; }`**
Whether customer details are enabled.
- **`CustomerDetails { get; private set; }`**
Customer details string (likely an ID or reference).
- **`TagIds { get; private set; }`**
Array of tag IDs associated with the template.
#### `TestTemplateList`
- **`TemporaryTemplate { get; set; }`**
Holds a temporary `TestTemplate` instance (e.g., for "Quick checkout") without persisting to DB.
- **`GetTemplate(string name) → TestTemplate`**
Retrieves a `TestTemplate` instance from `tblTestSetups` by name. Only loads fields defined in `DbOperations.TestSetups.Fields`. Sets `tt._bIsLoaded = false` to indicate incomplete loading. Returns `null` if not found or on error. Special case: Returns `TemporaryTemplate` if `name == "Quick checkout"`.
- **`GetSensorFromSettings(string settings, string serial, Dictionary<string, SensorData> lookup) → SensorData`**
Parses a comma-separated settings string (e.g., `"3=100,5=+"`) into a `SensorData` object. Uses `lookup` if provided and contains `serial`; otherwise queries `SensorsCollection.SensorsList`. Returns `null` if sensor not found. Supports settings: `CFC`, `Position`, `Polarity`, `Range`, `Delay`, `Duration`, `OutputMode`, `SQMode`, `DIMode`, `LimitDuration`, `ActiveValue`, `DefaultValue`.
- **`GetSensorFromSettings(string settings, string serial) → SensorData`**
Overload without `lookup` (passes `null`).
- **`GetSensorSettings(SensorData sd) → string`**
Serializes `SensorData` into the same comma-separated format used by `GetSensorFromSettings`. Only includes settings with non-default/empty values.
- **`TestTemplatesList { get; }`**
Singleton accessor for `TestTemplateList`.
- **`SysBuiltObject(string serialNumber) → bool`**
Queries `tblTestObjects` for `SysBuilt` flag of a given serial number. Returns `false` if not found.
- **`ConvertToDictionary(DataTable dt, ref Dictionary<string, List<Dictionary<string, object>>> lookup, string key)`**
Populates `lookup` by grouping rows in `dt` by `key` column. Each row becomes a `Dictionary<string, object>` of column values.
- **`GetAllTemplates() → TestTemplateTableObject[]`**
Queries `tblTestSetups` for all templates and returns an array of `TestTemplateTableObject`. Handles `UserTags` blob → `int[]` conversion via `GetTagIds`. If `Dirty` flag is true, re-fetches the full `TestTemplate` to update `IsComplete` status.
- **`GetTagIds(byte[] bytes) → int[]`**
Converts a byte array (from `UserTags` column) into an `int[]` using `Buffer.BlockCopy`. Returns empty array on failure.
---
### 3. Invariants
- **`TestTemplateLite.PreTriggerSeconds`**:
For `RecordingModes.Recorder` and `RecordingModes.HybridRecorder`, `PreTriggerSeconds` is *always* `0.0`, regardless of the stored `_preTriggerSeconds` value.
- **`TestTemplateTableObject` immutability**:
All properties are `private set`, meaning instances are immutable after construction.
- **`TestTemplateList.GetTemplate` behavior**:
Templates loaded via `GetTemplate` are explicitly marked as *not fully loaded* (`_bIsLoaded = false`), indicating that only `tblTestSetups` fields were populated. Consumers must avoid relying on lazily-loaded data (e.g., channels, groups).
- **`TemporaryTemplate` special case**:
Only returned when `name == "Quick checkout"` (exact string match). Empty/whitespace names return `null`.
- **`TagIds` blob format**:
`UserTags` is stored as a `byte[]` and converted to `int[]` assuming 4-byte `int` elements (via `sizeof(int)`). Failure to parse yields an empty array.
---
### 4. Dependencies
#### Internal Dependencies (from source):
- **`DbOperations`**: Used for database access (`GetCommand`, `CreateParam`, `QueryDataSet`, `TestSetups` table/field enums).
- **`Properties.Settings.Default.DownloadFolder`**: Used as fallback for `ExportFolder` and `DownloadFolder` in `GetTemplate`.
- **`CustomerDetailsList.CustomerList`**, **`TestEngineerDetailsList.TestEngineerList`**, **`LabratoryDetailsList.LabratoryList`**: Used to resolve customer/test engineer/lab details from stored IDs.
- **`SensorsCollection.SensorsList`**: Used by `GetSensorFromSettings` to look up sensors by serial number.
- **`ISO.TestObject.SensorSettings`**: Enum defining sensor setting types (e.g., `CFC`, `Range`, `Delay`).
- **`OutputTOMDigitalChannel.DigitalOutputMode`**, **`OutputSquibChannel.SquibFireMode`**, **`DigitalInputScaleMultiplier.InputModes`**: Enums used in sensor settings parsing.
#### External Dependencies:
- **`System.Data`**: `SqlDbType`, `DataRow`, `DataTable`, `DataSet`.
- **`System.Globalization`**: `CultureInfo.InvariantCulture` for numeric parsing.
#### Inferred Consumers:
- Modules performing template export/migration (e.g., `DatabaseExport` namespace usage implies integration with export pipelines).
- Code needing lightweight template metadata (e.g., UI lists, version comparison, migration scripts).
---
### 5. Gotchas
- **`PreTriggerSeconds` logic is mode-dependent**:
The property setter stores the value in `_preTriggerSeconds`, but the getter *ignores* it for `Recorder`/`HybridRecorder` modes. This may cause confusion if consumers expect the stored value to be returned.
- **`GetTemplate` does *not* load full template data**:
Despite returning a `TestTemplate`, only `tblTestSetups` fields are populated. Consumers must not assume groups, channels, or other related data are available.
- **`Dirty` flag triggers redundant full load**:
In `GetAllTemplates`, if `Dirty` is true, `GetTemplate` is called to re-fetch `IsComplete`. This may be inefficient and could fail silently (exceptions are caught and ignored).
- **`GetTagIds` assumes fixed `int` size**:
Uses `sizeof(int)` (4 bytes) for conversion. May fail on platforms with non-standard `int` sizes or malformed blobs.
- **`TemporaryTemplate` is mutable and global**:
As a singleton property, `TemporaryTemplate` can be overwritten by any caller. No thread-safety is implied beyond the singleton initialization.
- **`GetSensorFromSettings` silently handles missing sensors**:
Returns `null` if sensor not found, but only after creating a placeholder `SensorData` with empty `SerialNumber` if `serial` is null/whitespace.
- **`GetSensorSettings` omits default/empty values**:
Only includes settings with non-default values. This may cause round-trip mismatches if consumers expect all settings to be serialized.
None identified beyond the above.

View File

@@ -0,0 +1,172 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/Test.Module.Channel.Sensor.Bridge.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/Test.Module.Channel.Sensor.SensorUnits.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/Test.Module.Channel.Sensor.ZeroMethod.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/DigitalInputScaleMultiplier.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/Test.Module.Channel.Sensor.ExcitationVoltage.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/InitialOffset.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/DASConcepts/LinearizationFormula.cs
generated_at: "2026-04-16T04:57:48.606656+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "af9c7b6d258fe03e"
---
# Documentation: DAS Sensor Concepts (Version 57)
## 1. Purpose
This module defines core enumerations and data structures used to configure and process sensor data within the DTS DAS (Data Acquisition System) framework, specifically for database export in Version 57. It provides type-safe representations of sensor bridge configurations, sensitivity units, zeroing methods, excitation voltages, and linearization formulas—enabling consistent interpretation of sensor metadata across data import, processing, and export pipelines. These constructs serve as a bridge between legacy database formats and current system logic, preserving historical behavior while supporting extensibility.
## 2. Public Interface
### Nested Enumerations (within `DatabaseExport.Test.Module.Channel.Sensor`)
#### `BridgeType`
- **Definition**: `public enum BridgeType`
- **Values**:
- `IEPE = 1 << 0` — Sensor uses IEPE (Integrated Electronics Piezo-Electric) setup.
- `QuarterBridge = 1 << 1` — Sensor uses quarter-bridge configuration.
- `HalfBridge = 1 << 2` — Sensor uses half-bridge configuration.
- `FullBridge = 1 << 3` — Sensor uses full-bridge configuration.
- `DigitalInput = 1 << 4` — Sensor acts as a digital input.
- `SQUIB = 1 << 5` — Sensor uses SQUIB (a proprietary DTS technology).
- `TOMDigital = 1 << 6` — TOM digital input mode.
- **Behavior**: Bitwise flags; intended for combination via OR operations.
#### `SensUnits`
- **Definition**: `public enum SensUnits`
- **Values**:
- `NONE = 0` — No sensitivity units (used for polynomial sensors).
- `mV = 1` — Sensitivity in millivolts at full-scale (Capacity EU).
- `mVperV = 2` — Excitation-proportional sensitivity in mV/V at full-scale.
- `mVperVperEU = 3` — Sensitivity in mV/V per Engineering Unit.
- `mVperEU = 4` — Sensitivity in mV per Engineering Unit.
- **Behavior**: Represents sensitivity unit types for sensor calibration.
#### `ZeroMethodType`
- **Definition**: `public enum ZeroMethodType`
- **Values**:
- `AverageOverTime = 0` — Electrical zero calculated as average over time.
- `UsePreEventDiagnosticsZero = 1` — Zero calculated using pre-event diagnostics.
- `None = 2` — Zero set via absolute/injected value.
- **Notes**: Order and values are preserved for legacy compatibility (e.g., GM ISF import).
#### `OriginalZeroMethodType`
- **Definition**: `public enum OriginalZeroMethodType`
- **Values**:
- `AverageOverTime` — Same as `ZeroMethodType.AverageOverTime`.
- `UsePreCalZero` — Zero calculated using pre-calibration diagnostics.
- `None` — Same as `ZeroMethodType.None`.
- **Notes**: Distinct from `ZeroMethodType` to preserve original enum values during migration; `UsePreCalZero` maps to `UsePreEventDiagnosticsZero` semantically.
#### `ExcitationVoltageOption`
- **Definition**: `public enum ExcitationVoltageOption`
- **Values**:
- `Undefined = 1` — Voltage magnitude 0.0 V.
- `Volt2 = 2` — 2.0 V.
- `Volt2_5 = 4` — 2.5 V.
- `Volt3 = 8` — 3.0 V.
- `Volt5 = 16` — 5.0 V.
- `Volt10 = 32` — 10.0 V.
- `Volt1 = 64` — 1.0 V.
- **Behavior**: Bitwise flags (powers of two); values are *not* sequential.
#### `DigitalInputScaleMultiplier.InputModes`
- **Definition**: `public enum InputModes`
- **Values**:
- `TLH = 1 << 1` — Transition Low-to-High.
- `THL = 1 << 2` — Transition High-to-Low.
- `CCNO = 1 << 3` — Contact Closure, Normally Open.
- `CCNC = 1 << 4` — Contact Closure, Normally Closed.
#### `DigitalInputScaleMultiplier.Forms`
- **Definition**: `public enum Forms`
- **Values**:
- `ArbitraryLowAndHigh` — Only supported form; maps digital 0/1 to configurable `DefaultValue`/`ActiveValue`.
### Public Classes
#### `DigitalInputScaleMultiplier`
- **Namespace**: `DatabaseExport`
- **Properties**:
- `Form` (`Forms`) — Format of the scale multiplier; currently only `ArbitraryLowAndHigh`.
- `DefaultValue` (`double`) — Value displayed for digital input `0` (OFF).
- `ActiveValue` (`double`) — Value displayed for digital input `1` (ON); defaults to `1.0`.
- **Constructors**:
- `DigitalInputScaleMultiplier()` — Initializes with `DefaultValue = 0.0`, `ActiveValue = 1.0`.
- `DigitalInputScaleMultiplier(DigitalInputScaleMultiplier copy)` — Copy constructor.
- **Methods**:
- `string ToSerializeDbString()` — Serializes to `"ArbitraryLowAndHigh{sep}DefaultValue{sep}ActiveValue"` using invariant culture list separator.
- `void FromDbSerializeString(string s)`**Currently unimplemented** (body commented out). Returns early if `s == null`.
#### `InitialOffset`
- **Namespace**: `DatabaseExport`
- **Properties**:
- `Form` (`InitialOffset.Forms`) — Format: `None`, `EU`, or `EUAtMV`.
- `EU` (`double`) — Offset in Engineering Units (used for `EU` and `EUAtMV` forms).
- `MV` (`double`) — Millivolt value at which `EU` is observed (used only for `EUAtMV` form).
- **Constructors**:
- `InitialOffset()` — Initializes with `Form = None`, `EU = 0`, `MV = 0`.
- `InitialOffset(InitialOffset copy)` — Copy constructor.
- **Methods**:
- `string ToDbSerializeString()` — Serializes to `"Form{sep}EU{sep}MV"`.
- `void FromDbSerializeString(string input)` — Parses serialized string; throws `InvalidDataException`/`FormatException` on malformed input.
#### `LinearizationFormula`
- **Namespace**: `DatabaseExport`
- **Properties**:
- `Style` (`LinearizationFormula.Styles`) — Linearization method; defaults to `IRTraccDiagnosticsZero`.
- `PolynomialSensitivity` (`double`) — Sensitivity factor for polynomial scaling; defaults to `1.0`.
- `LinearizationExponent` (`double`) — Exponent used in power-law linearization; defaults to `1.0`.
- `MMPerV` (`double`) — Millimeters per volt (slope for IRTracc-style linearization).
- `MVAt0MM` (`double`) — Millivolts at zero millimeters (offset for diagnostics/average zeroing).
- `Slope`, `Intercept` (`double`) — Linear coefficients (used for `IRTraccManual`).
- `CalibrationFactor`, `ZeroPositionIntercept` (`double`) — Used for `IRTraccCalFactor`.
- `UsemVOverVForPolys` (`bool`) — If `true`, polynomial inputs are converted to mV/V; defaults to `true`.
- **Constructors**:
- `LinearizationFormula()` — Initializes with default coefficients `[0,0,0,0]` and exponents `[0,1,2,3]`.
- `LinearizationFormula(LinearizationFormula copy)` — Copy constructor.
- **Methods**:
- `bool IsValid()` / `void MarkValid(bool)` — Tracks validity state.
- `string ToSerializeString()` — Serializes to `"{Style}_{params}"` format (e.g., `"Polynomial_c0xe0,c1xe1,...,S=...,mV=..."`).
- `void FromSerializeString(string s)` — Parses serialized string; throws `NotSupportedException` on invalid format.
- `string ToPolynomialString()` / `void FromPolynomialString(...)` — Handles polynomial-specific serialization.
## 3. Invariants
- **`BridgeType`**: Values are powers of two (bit flags); valid combinations are bitwise ORs of distinct values.
- **`ExcitationVoltageOption`**: Values are powers of two (bit flags); `GetExcitationVoltageMagnitudeFromEnum` and `GetExcitationVoltageEnumFromMagnitude` enforce bijection between enum and magnitude via `VoltageMagnitudeAttribute`.
- **`ZeroMethodType`**: Enum values are fixed for backward compatibility; `UsePreEventDiagnosticsZero` (value `1`) corresponds to `UsePreCalZero` in `OriginalZeroMethodType`.
- **`DigitalInputScaleMultiplier.Form`**: Only `ArbitraryLowAndHigh` is implemented; other forms would throw `NotSupportedException`.
- **`InitialOffset.Form`**:
- `EU`: `EU` is the direct offset in engineering units.
- `EUAtMV`: `EU` is the engineering unit value observed at `MV`; actual offset in EU must be computed (not stored).
- `None`: `EU` and `MV` are ignored.
- **`LinearizationFormula.Style`**: Each style has a required set of fields; e.g., `Polynomial` requires `_coefficients` and `_exponents`, while `IRTraccManual` requires `Slope` and `Intercept`.
## 4. Dependencies
### Imports/Usings
- `System.ComponentModel` — For `[Description]` attributes on enums.
- `System` — Core types (`Exception`, `Attribute`, `AttributeUsage`, `List`, `StringBuilder`, etc.).
### Inferred Usage
- **Consumers**: Likely used by database import/export logic (e.g., `DatabaseExport` namespace implies integration with legacy DB layers), sensor configuration UIs, and calibration tools.
- **Depends on**:
- `AttributeCoder<TEnum, TAttr, TValue>` (not shown in source) — Used by `VoltageMagnitudeAttributeCoder`.
- `System.Globalization.CultureInfo` — For culture-invariant serialization/deserialization.
- **Depended on by**:
- Sensor configuration classes (e.g., `Test.Module.Channel.Sensor`).
- Data processing pipelines that apply linearization or zero corrections.
## 5. Gotchas
- **`DigitalInputScaleMultiplier.FromDbSerializeString` is unimplemented**: The method body is commented out; calling it will silently return if `s == null` but otherwise throw `NotImplementedException` (or similar) at runtime.
- **`InitialOffset` copy constructor ignores null**: `InitialOffset(InitialOffset copy)` returns without error if `copy == null`, leaving the new instance in default state.
- **`ZeroMethodType` vs `OriginalZeroMethodType`**: The two enums have overlapping semantics but different names for `UsePreCalZero`/`UsePreEventDiagnosticsZero`; migration code must map them explicitly.
- **`ExcitationVoltageOption` values are powers of two, not sequential**: `Volt1 = 64`, `Volt2 = 2`, etc. — Do not assume ordering.
- **`LinearizationFormula` serialization is style-specific**: Each `Style` has a unique serialization format (e.g., polynomial uses comma-separated `cxe` pairs with `S=` and `mV=` suffixes); deserialization fails on unrecognized styles or malformed tokens.
- **Polynomial serialization assumes mV/V by default**: `UsemVOverVForPolys = true` converts input to mV/V before applying coefficients; GM-style inputs may require `false`.
- **`SensUnits.mVperVperEU` (value `3`)**: Rarely used; ensure downstream logic handles this case if present in legacy data.

View File

@@ -0,0 +1,294 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/AbstractOLEDbWrapper.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TemplateZone.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TestObjectChannel.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/CalculatedValueClass.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/HardwareChannel.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TemplateRegion.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/LevelTriggerChannel.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/MMEFigures.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TestSetting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TestEngineerDetails.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/TestObjectMetaData.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/IsoCode.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/ISO/CustomerDetails.cs
generated_at: "2026-04-16T04:57:15.551651+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "8139d487746881b8"
---
# Documentation: DatabaseExport.ISO Module (Version 57)
## 1. Purpose
This module provides data models and utility classes for exporting test data to ISO-compliant formats, specifically targeting legacy database schema version 57. It serves as a bridge between internal data structures and standardized export formats by encapsulating database row mappings, ISO code construction logic, and metadata handling. The module supports template-based channel definitions, calculated values, level triggers, hardware configuration, and customer/test engineer metadata—enabling consistent serialization and deserialization of test setup information for interoperability with external systems.
## 2. Public Interface
### `AbstractOLEDbWrapper`
- **`GetLong(IDataReader reader, string field)`**
Safely extracts a `long` value from an `IDataReader`. Returns `long.MinValue` if the field value is `DBNull.Value`.
- **`GetDate(IDataReader reader, string field)`**
Safely extracts a `DateTime` value from an `IDataReader`. Returns `DateTime.MinValue` if the field value is `DBNull.Value`.
### `TemplateZone`
- **Constructor `TemplateZone(string template, string name, string picture, string description)`**
Initializes a new zone with explicit values.
- **Constructor `TemplateZone(DataRow dr)`**
Initializes from a database row. Sets `ZoneName` to `"Default zone"` if `ZoneName` is `DBNull.Value`; sets `Description` to `""` if `ZoneDescription` is `DBNull.Value`; populates `TemplateRegions` via `TemplateRegion.GetAllRegions()`.
- **Properties**
- `TemplateName` (read-only)
- `ZoneName` (read-only, defaults to `""`)
- `Picture` (read-write)
- `Description` (read-only, defaults to `""`)
- `TemplateRegions` (read-write array of `TemplateRegion`)
### `TestObjectChannel`
- **`GetGraphID()`**
Returns `GetId() + "_CU"` if `SquibChannelType == SquibChannelTypes.Current`; otherwise returns `GetId()`.
- **`GetId()`**
Returns `GetIdWithSpecificChannelId(Channel.Id)`.
- **`GetIdWithSpecificChannelId(long id)`**
Returns formatted string: `"{SerialNumber}_{MMEChannelType}_{id}"`.
- **`GetID()` / `GetIDWithSpecificChannelId(long id)`**
Alias methods identical to `GetId()` / `GetIdWithSpecificChannelId(long id)`.
- **`CompareTo(TestObjectChannel right)`**
Compares by `DisplayOrder`, then `Name`, then `TestObject.SerialNumberOrOriginalSerialNumber` (if both non-null). Returns `1` if `right == null`.
- **Properties**
- `SquibChannelType` (`SquibChannelTypes` enum: `None`, `Voltage`, `Current`)
- `SensorSerialNumber` (read-write string, default `""`)
- `HardwareId` (read-write string; setter normalizes format: splits on `'_'`, keeps first two tokens, and appends everything from first `'x'` in third token)
- `TestObject` (read-only `ISO.TestObject`)
- `ChannelIDX` (read-write `int`, initialized to `CHANNEL_IDX_UNKNOWN = -1`)
### `CalculatedValueClass`
- **Constructor `CalculatedValueClass(DataRow dr)`**
Populates properties from `DbOperations.CalculatedChannels.Fields` enum values. Skips `DBNull.Value` fields.
- **Properties**
- `Id` (`int`, default `-1`)
- `Operation` (`Operations` enum: `SUM`, `AVERAGE`, `IRTRACC3D`, `IRTRACC3D_ABDOMEN`, `IRTRACC3D_LOWERTHORAX`; default `SUM`)
- `CalculatedValueCode` (`string`, default `"???????????????X"`)
- `InputChannelIds` (`string[]`)
- `InputChannelIdsBlob` (`byte[]`):
- Getter joins `InputChannelIds` with `CultureInfo.InvariantCulture.TextInfo.ListSeparator`, encodes to UTF-8.
- Setter decodes UTF-8, splits by list separator, populates `_inputChannelIds`.
- `CFCForInputChannels` (`string`, default `""`)
- `ChannelFilterClassForOutput` (`string`, default `""`)
- `TestSetupName` (`string`)
- `Name` (`string`)
### `ISOHardwareChannel`
- **Constructor `ISOHardwareChannel(ISOHardwareChannel copy, Hardware h)`**
Deep-copies configuration from `copy`, assigns `ParentDAS = h`.
- **Constructor `ISOHardwareChannel(DataRow dr, Hardware hardware)`**
Populates from `DbOperations.DAS.DASChannelFields` enum values. Throws `NotSupportedException` for unknown fields.
- **Static Method `PhysicalCompare(ISOHardwareChannel left, ISOHardwareChannel right)`**
Compares by `ChannelIdx`. Returns `-1`/`0`/`1` for null checks.
- **Properties**
- `ParentDAS` (`Hardware`)
- `SupportedBridges`, `SupportedSquibFireModes`, `SupportedExcitations`, `SupportedDigitalInputModes`, `SupportedDigitalOutputModes` (`int`, defaults `12`, `16`, `16`, `16`, `16`)
- `ChannelIdx`, `DASDisplayOrder` (`int`)
- `ModuleSerialNumber` (`string`, default `""`)
- `ModuleArrayIndex` (`int`, default `0`)
- `LocalOnly` (`bool`, default `false`)
### `TemplateRegion`
- **Constructor `TemplateRegion(string templateName, string zoneName, bool bLocalOnly)`**
Initializes with explicit values.
- **Constructor `TemplateRegion(DataRow dr)`**
Populates all fields from database row, including coordinate points (`UpperLeft`, `LowerRight`).
- **Static Method `GetAllRegions(string templateName, string zoneName)`**
Queries `tblTemplateRegions` via `DbOperations`, returns array of `TemplateRegion`. Silently ignores exceptions.
- **Properties**
- `TemplateName`, `TemplateZone` (read-only)
- `RegionNumber`, `RegionName`, `RegionDescription`, `TestObject`, `Position`, `MainLocation`, `FineLocation1-3`, `PhysicalDimension`, `Direction`, `FilterClass` (`string`)
- `LocalOnly` (read-only `bool`)
- `UpperLeft`, `LowerRight` (`System.Drawing.Point`)
### `LevelTriggerChannel`
- **Constructor `LevelTriggerChannel(LevelTriggerChannel copy)`**
Deep-copies all properties.
- **Constructor `LevelTriggerChannel(DataRow dr)`**
Populates from `DbOperations.LevelTriggers.Fields` enum values. Silently ignores exceptions.
- **Properties**
- `TestSetupName`, `GroupSerialNumber`, `TestObjectChannelId`, `HardwareChannelId`, `SensorSerialNumber` (`string`, defaults `""`)
- `GreaterThanEnabled`, `LessThanEnabled` (`bool`, defaults `true`, `false`)
- `GreaterThanThresholdEU`, `LessThanThresholdEU` (`double`, defaults `0D`)
- `TriggerBetweenBounds`, `TriggerOutsideBounds` (`bool`, defaults `false`)
- `InsideUpperLevelEU`, `InsideLowerLevelEU`, `OutsideUpperLevelEU`, `OutsideLowerLevelEU` (`double`, defaults `0D`)
### `MMEFigures`
- **Constructor `MMEFigures(...)`**
Initializes all fields explicitly.
- **Static Method `GetFigures()`**
Queries `MMEFIGURES` table via `DbOperations.GetISOCommand()`, returns array of `MMEFigures`. Silently ignores exceptions during row processing.
- **Properties**
- `ID`, `IntAuthor`, `IntVersion` (`long`)
- `TxtShortName`, `TxtDescription`, `TxtRemarks`, `TxtImageFile`, `TxtSortKey`, `TxtPath`, `Last_Change_Text`, `History` (`string`)
- `DatRevision`, `Last_Change` (`DateTime`)
- `IntPage`, `IntPages` (`ushort`)
- `BolExpired` (`bool`)
- `BitStdPath` (`bool`)
- `IntIDStdPath` (`long`)
### `TestSetting` & `TestSettingDictionary`
- **`TestSetting`**
- **Constructor `TestSetting(string id, string value, string defaultValue)`**
- **`ToSerializeString()`**
Returns `"id=value"` with `=` replaced by `"_x_"` in both fields.
- **Static `TryParse(string s, out TestSetting ts)`**
Parses `"id=value"` format (reverses `"_x_"``"="`). Returns `false` if parsing fails.
- **`TestSettingDictionary`**
- **`GetValue(string ID, string defaultValue)`**
Returns `_lookup[ID].Value` if exists and non-null; otherwise `_lookup[ID].DefaultValue`; otherwise `defaultValue`.
- **`SetValue(TestSetting setting, string value)`**
Replaces entry for `setting.Id` with new `TestSetting` (preserves `Id`, `DefaultValue`, sets `Value = value`).
- **`SetValue(TestSetting setting)`**
Adds/updates entry with `setting`.
- **`SetValue(string id, string value)`**
Adds new entry or updates `Value` if key exists.
- **`ToSerializeString()` / `LoadSettings(string s)`**
Serializes/deserializes settings using `"id=value"` pairs separated by `CultureInfo.InvariantCulture.TextInfo.ListSeparator`, with internal `"_X_"` escaping.
### `TestEngineerDetails`
- **Constructor `TestEngineerDetails(DataRow dr)`**
Populates from `tblTestEngineerDetails` row.
- **Static Method `GetAllTestEngineerDetails()`**
Queries `tblTestEngineerDetails`, returns array. Silently ignores exceptions.
- **Properties**
- `Name`, `TestEngineerName`, `TestEngineerPhone`, `TestEngineerFax`, `TestEngineerEmail` (`string`; setters ignore empty strings for engineer fields)
- `LocalOnly` (`bool`)
- `LastModified` (`DateTime`)
- `LastModifiedBy` (`string`)
- `Version` (`int`, default `1`)
- **`GetValues()`**
Returns `Dictionary<string, string>` of all fields.
### `TestObjectMetaData` & `TestSetupMetaData`
- **`TestObjectMetaData`**
- **Constructor `TestObjectMetaData(char testobject)`**
Initializes properties from `Fields`, `CommentFields`, `OptionFields` enums. Sets `NOVALUE` defaults (except `VelocityOfTestObject`, `MassOfTestObject``""`).
- **Properties**
- `Version` (`double`, default `1.06`)
- `NOVALUE = "NOVALUE"`
- `TestObject` (`char`, default `'?'`)
- `Properties` (`MetaData[]`)
- **`TestSetupMetaData`**
- **Constructor `TestSetupMetaData(bool requireXCrashCompatibilityForISOExports)`**
Initializes properties from `Fields` enum. Sets `NOVALUE` or `""` based on `requireXCrashCompatibilityForISOExports`.
- **`SetProperty(MetaData meta, bool requireXCrashCompatibilityForISOExports)`**
Overrides `NOVALUE``""` for specific fields if `requireXCrashCompatibilityForISOExports` is `true`.
- **Properties**
- `Version` (`double`, default `1.06`)
- `NOVALUE = "NOVALUE"`, `MEDIADEFAULT = "1/1"`
- `TestObject = '_'`
- `Properties` (`MetaData[]`)
- **`MetaData`**
- **Constructor `MetaData(string name, bool optional, string value, double version)`**
- **Properties**
- `Name`, `Value` (`string`)
- `IsOptional`, `Version` (`bool`, `double`)
### `IsoCode`
- **Constructor `IsoCode(string isoCode)`**
Normalizes input to 16 characters (truncates or pads with `'?'`).
- **Static Methods**
- **`GetString(MMEPossibleChannels, MMETestObjects, MMEPositions, MMEFilterClasses)`**
Constructs 16-char ISO code from components. Uses `'?'` for null inputs.
- **`GetString(MMEPossibleChannels, bool careAboutTestTimeFields)`**
Same as above, but masks `TestObject` and `FilterClass` to `'?'` if `careAboutTestTimeFields == false`.
- **`GetString(string testObject, string position, string main, string floc1, string floc2, string floc3, string physdim, string dir, string fc)`**
Concatenates inputs into 16-char code (no padding/truncation).
- **Properties**
- `TestObject`, `Position`, `MainLocation`, `FineLocation1-3`, `PhysicalDimension`, `Direction`, `FilterClass` (read-write `string`; setters enforce 1-char/4-char/2-char constraints)
- `StringRepresentation` (`string`):
- Getter: returns full 16-char code.
- Setter: pads with `'0'` if shorter than 16.
### `CustomerDetails`
- **Constructor `CustomerDetails(DataRow dr)`**
Populates from `tblCustomerDetails` row.
- **Static Method `GetAllCustomerDetails()`**
Queries `tblCustomerDetails`, returns array. Silently ignores exceptions.
- **Properties**
- `Name`, `CustomerName`, `CustomerTestRefNumber` (`string`)
- `ProjectRefNumber`, `CustomerOrderNumber`, `CustomerCostUnit` (`string`; setters ignore empty strings)
- `LocalOnly` (`bool`)
- `LastModified` (`DateTime`)
- `LastModifiedBy` (`string`)
- `Version` (`int`, default `1`)
- **`GetValues()`**
Returns `Dictionary<string, string>` of all fields.
## 3. Invariants
- **`AbstractOLEDbWrapper`**:
- `GetLong` never throws on `DBNull`; returns `long.MinValue`.
- `GetDate` never throws on `DBNull`; returns `DateTime.MinValue`.
- **`TemplateZone`**:
- `ZoneName` defaults to `"Default zone"` only if `DBNull.Value` in DB row; otherwise preserved.
- `Description` defaults to `""` if `DBNull.Value` in DB row.
- **`TestObjectChannel`**:
- `HardwareId` setter enforces format: splits on `'_'`, expects 3 tokens, and reassembles first two tokens + suffix from third token after first `'x'`.
- `CompareTo` uses `DisplayOrder` as primary key; `Name` as secondary; `SerialNumberOrOriginalSerialNumber` as tertiary (if both non-null).
- **`CalculatedValueClass`**:
- `InputChannelIdsBlob` getter/setter uses `CultureInfo.InvariantCulture.TextInfo.ListSeparator` (typically `','`), not locale-specific.
- `CalculatedValueCode` defaults to `"???????????????X"` (15 chars + `'X'`).
- **`IsoCode`**:
- `StringRepresentation` setter pads with `'0'` if input < 16 chars.
- All individual properties enforce fixed widths:
- `TestObject`, `Position`, `Direction`, `FilterClass`: 1 char
- `MainLocation`: 4 chars
- `FineLocation1-3`: 2 chars each
- `PhysicalDimension`: 2 chars
- Total length always 16 characters.
- **`TestSettingDictionary`**:
- `ToSerializeString` escapes `ListSeparator``"_X_"` in serialized values.
- `LoadSettings` preserves existing default settings; only updates `Value` if key exists.
## 4. Dependencies
### Internal Dependencies
- **`DbOperations`** (referenced via `DbOperations.GetCommand()`, `DbOperations.GetISOCommand()`, `DbOperations.CreateParam()`, `DbOperations.Connection.QueryDataSet()`):
Provides database access utilities (SQL command creation, parameterization, query execution).
- **`ISO.TestObject`** (used in `TestObjectChannel.TestObject`):
Referenced but not defined in provided files.
- **`ISO.TestObjectTemplate`** (used in `TestObjectChannel` constructor):
Referenced but not defined in provided files.
- **`Hardware`** (used in `ISOHardwareChannel.ParentDAS`):
Referenced but not defined in provided files.
- **`MMEPossibleChannels`, `MMETestObjects`, `MMEPositions`, `MMEFilterClasses`** (used in `IsoCode.GetString`):
Referenced but not defined in provided files.
### External Dependencies
- **`System.Data`** (`System.Data.OleDb`, `System.Data.SqlClient`):
Used for `IDataReader`, `DataRow`, `SqlDbType`, `OleDbCommand`.
- **`System.Text`**:
Used for `StringBuilder`, `Encoding.UTF8`.
- **`System.Drawing`**:
Used for `System.Drawing.Point` in `TemplateRegion.UpperLeft/LowerRight`.
- **`System.Globalization`**:
Used for `CultureInfo.InvariantCulture.TextInfo.ListSeparator`.
### Inferred Usage
- `TemplateRegion.GetAllRegions()` and `TestEngineerDetails.GetAllTestEngineerDetails()`/`CustomerDetails.GetAllCustomerDetails()` imply database persistence layer.
- `TestSettingDictionary` serialization suggests configuration storage/retrieval (e.g., XML, DB).
- `CalculatedValueClass` and `LevelTriggerChannel` imply integration with channel processing logic.
## 5. Gotchas
- **`AbstractOLEDbWrapper.GetDate`**:
Returns `DateTime.MinValue` for `DBNull`, which may be ambiguous if `DateTime.MinValue` is a valid value in the domain. Consider using `DateTime?` or sentinel values.
- **`TestObjectChannel.HardwareId` setter**:
Mutates input by stripping characters after first `'x'` in the third token. This may cause data loss if `'x'` appears elsewhere in the hardware ID.
- **`CalculatedValueClass.InputChannelIdsBlob`**:
Uses `

View File

@@ -0,0 +1,89 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Properties/AssemblyInfo.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Properties/Settings.Designer.cs
generated_at: "2026-04-16T04:58:11.614258+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "271f9fb7b6317edd"
---
# Properties
## Documentation: DatabaseExport Module (Version 57)
### 1. Purpose
This module is a .NET assembly named **DatabaseExport**, part of the `DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport` codebase, intended for exporting database content—specifically from an ISO-compliant MME database (`mme_code.mdb`)—as part of legacy version support for Version 57 of the system. It provides configuration-driven behavior for test and export operations, including settings for sensor validation, test checklist steps, ROI parameters, and export format preferences. The module is not a standalone executable but a library assembly (likely referenced by other components), as indicated by its structure and lack of entry-point methods.
### 2. Public Interface
The module exposes **no public types or methods beyond its settings class**. The only publicly accessible type is:
- **`DatabaseExport.Properties.Settings`**
A strongly-typed, application settings class derived from `System.Configuration.ApplicationSettingsBase`. It provides read/write access to configuration values via static property `Default`.
- **Properties** (all read-only unless otherwise noted):
- `string ISOMMEDbLocation` — Path to the ISO MME database file (default: `"ISO\\mme_code.mdb"`).
- `bool AllowAutoArm` — Whether auto-arming is permitted (default: `false`).
- `int CalWarningPeriodDays`*User-scoped*; calibration warning period in days (default: `7`).
- `int DBType` — Database type identifier (default: `1`).
- `bool DefaultSuppressMissingSensorsWarning`*User-scoped*; suppress warning for missing sensors (default: `true`).
- `bool DefaultTestAllowMissingSensors` — Allow tests to proceed with missing sensors (default: `false`).
- `bool DefaultTestAllowSensorIdToBlankChannel` — Permit sensor ID mapping to blank channels (default: `true`).
- `bool DefaultTestArmCheckListStep` — Require checklist step before arming (default: `false`).
- `bool DefaultTestCheckListBatteryVoltageCheck` — Include battery voltage check in checklist (default: `true`).
- `bool DefaultTestCheckListInputVoltageCheck` — Include input voltage check in checklist (default: `true`).
- `bool DefaultTestCheckListMustPass` — Checklist must pass for test to continue (default: `false`).
- `bool DefaultTestCheckListSensorIDCheck` — Include sensor ID check in checklist (default: `true`).
- `bool DefaultTestCheckListSquibResistanceCheck` — Include squib resistance check in checklist (default: `true`).
- `bool DefaultTestCheckListTriggerStartCheck` — Include trigger start check in checklist (default: `true`).
- `bool DefaultTestDownloadAll` — Download all data during test (default: `true`).
- `bool DefaultTestDownloadROI` — Download only ROI data during test (default: `true`).
- `int DefaultTestExcitationWarmupMS` — Excitation warm-up time in milliseconds (default: `6000`).
- `bool DefaultTestExport` — Enable export during test (default: `false`).
- `bool DefaultTestQuitTestWithoutWarning` — Allow test exit without warning (default: `false`).
- `int DefaultTestRealtimeModeGraphCount` — Number of graphs in real-time mode (default: `6`).
- `ulong DefaultTestExportFormat` — Export format identifier (default: `0`).
- `bool DefaultTestRequireAllUnitsPassDiagnostics` — Require all units to pass diagnostics (default: `true`).
- `bool DefaultTestRequireUserConfirmationOnErrors` — Require user confirmation on errors (default: `true`).
- `double DefaultTestROIEnd` — End time of ROI (default: `1.0`).
- `double DefaultTestROIStart` — Start time of ROI (default: `-1.0`).
- `bool DefaultTestRunPostTestDiagnostics` — Run diagnostics after test (default: `false`).
- `double DefaultTestSampleRate` — Sample rate in Hz (default: `10000.0`).
- `bool DefaultTestSuppressNotAllChannelsViewedWarningRealTime` — Suppress warning for unviewed channels in real-time (default: `false`).
- `bool DefaultTestTriggerCheckStep` — Require trigger check step (default: `true`).
- `bool DefaultTestSuppressNotAllChannelsViewedWarningViewer` — Suppress warning for unviewed channels in viewer (default: `false`).
- `bool DefaultTestViewAll` — View all channels by default (default: `false`).
- `bool DefaultTestViewROI` — View ROI channels by default (default: `true`).
- `bool DefaultUploadEnabled` — Enable upload functionality (default: `false`).
- `string DownloadFolder` — Default folder for downloads (default: `"..\\Data"`).
- `bool RequireXCrashCompatibilityForISOExports` — Enforce XCrash compatibility for ISO exports (default: `true`).
- `string InstallerCustomActions`*User-scoped*; custom actions for installer (default: `"InstallerCustomActions"`).
> **Note**: All properties are read-only except `CalWarningPeriodDays`, `DefaultSuppressMissingSensorsWarning`, and `InstallerCustomActions`, which have public setters (user-scoped settings). All others are application-scoped and immutable at runtime.
### 3. Invariants
- **Application-scoped settings** (most properties) are immutable at runtime; attempts to modify them via assignment will fail or be ignored unless explicitly allowed (see above).
- **User-scoped settings** (`CalWarningPeriodDays`, `DefaultSuppressMissingSensorsWarning`, `InstallerCustomActions`) can be modified per-user and persisted, but require explicit save logic (not shown here).
- `DBType` is an integer identifier; its semantics (e.g., `1` = ISO) are not defined in this file and must be inferred from consuming code.
- `DefaultTestROIStart = -1.0` likely indicates "auto-detect start" or "entire dataset", but this is not enforced in this module.
- The assembly is **not COM-visible** (`ComVisible(false)`), so it is not intended for interop with COM clients.
### 4. Dependencies
- **Runtime Dependencies**:
- `System.Configuration` (for `ApplicationSettingsBase`, attributes like `ApplicationScopedSettingAttribute`)
- `System` (core types, e.g., `string`, `bool`, `int`, `double`, `ulong`)
- **Build Dependencies**:
- Visual Studio Settings Designer (indicated by `GeneratedCodeAttribute` version `"15.5.0.0"`)
- .NET Framework 4.0+ (runtime version `4.0.30319.42000`)
- **Consumers**:
This assembly is referenced by other modules in the `DataPRO/Modules/PreviousDBVersions/Version57/` hierarchy (e.g., test harnesses, export tools), though no direct references are visible in the provided files.
### 5. Gotchas
- **Hardcoded paths**: `ISOMMEDbLocation` defaults to `"ISO\\mme_code.mdb"`—relative path behavior depends on the working directory of the consuming process.
- **Ambiguous `DBType`**: The meaning of integer values (e.g., `1`) is not documented here; consumers must know the mapping (e.g., `1 = ISO`, `2 = proprietary`).
- **`DefaultTestROIStart = -1.0`**: This sentinel value may be interpreted specially by downstream logic (e.g., "use full dataset"), but no validation or documentation is present in this module.
- **No error handling in settings access**: Property getters throw if the underlying configuration store is corrupted or missing a value (e.g., type mismatch), but this is not handled in this file.
- **Auto-generated file**: `Settings.Designer.cs` warns that manual changes are lost on regeneration—any customization must be done via the `.settings` designer or partial class extension.
- **No versioning or migration logic**: Settings schema changes (e.g., adding/removing keys) are not handled; this could cause runtime failures if settings evolve across versions.
> **None identified from source alone.**
> *(Note: This section was intentionally left as a placeholder per instructions, but the above gotchas were inferred from observed patterns and common pitfalls in similar .NET settings usage.)*

View File

@@ -0,0 +1,316 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/SensorRange.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/SensorDB.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/DigitalInputSetting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/ZeroMethod.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/DigitalOutputSetting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/FilterClass.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/SquibSetting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/IsoCode.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/CalibrationRecords.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SensorDB/SensorsCollection.cs
generated_at: "2026-04-16T04:58:51.573580+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "56b13794f7fbf4fa"
---
# Documentation: `DatabaseExport` Sensor Data Types (Version 57)
---
## 1. Purpose
This module defines data structures and types used to represent sensor configurations, calibration metadata, and related settings for legacy database version 57 in the DataPRO system. It provides strongly-typed classes to deserialize sensor and channel configuration data from database rows (`System.Data.DataRow`) and serialize them for persistence or exchange. These types serve as an abstraction layer between the raw database schema and higher-level application logic, enabling consistent handling of sensor metadata, digital I/O settings, calibration records, and ISO location codes across the system.
---
## 2. Public Interface
### `SensorRange`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `double Low { get; set; }`
- `double Medium { get; set; }`
- `double High { get; set; }`
- **Constructor**: `SensorRange(double _low, double _medium, double _high)`
Initializes all three range values.
### `LowHigh`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `double Low { get; set; }`
- `double High { get; set; }`
- **Constructor**: `LowHigh(double _low, double _high)`
Initializes low and high bounds.
### `SensorStatus`
- **Namespace**: `DatabaseExport`
- **Enum Values**:
- `Available`
- `InUse`
- `OutForService`
- `OutForCalibration`
- `Retired`
### `ShuntMode`
- **Namespace**: `DatabaseExport`
- **Enum Values**:
- `None`
- `Emulation`
- `Internal`
- `External`
### `BridgeLeg`
- **Namespace**: `DatabaseExport`
- **Enum Values**:
- `First`
- `Second`
- `Third`
- `Fourth`
### `CouplingModes`
- **Namespace**: `DatabaseExport`
- **Enum Values**:
- `AC = 0`
- `DC`
### `DigitalInputSetting`
- **Namespace**: `DatabaseExport`
- **Inherits**: `SensorData`
- **Constructors**:
- `DigitalInputSetting()`
Initializes with defaults via `SetDefaults`.
- `DigitalInputSetting(DigitalInputSetting copy)`
Copy constructor; initializes with defaults after copying.
- **Static Method**:
- `static void SetDefaults(SensorData sd)`
Sets default values for a `SensorData` instance:
- `AxisNumber = 0`
- `NumberOfAxes = 1`
- `Capacity = 1` (overwrites earlier `2400`)
- `Bridge = Test.Module.Channel.Sensor.BridgeType.DigitalInput`
- `DisplayUnit = "V"`
- `BridgeResistance = double.NaN`
- `CheckOffset = false`
- `Manufacturer = "Generic"`
- `OffsetToleranceHigh = 2500`
- `OffsetToleranceLow = 2500`
- `Model = "Digital Input Setting"`
- `Shunt = ShuntMode.None`
- `MeasureExcitation = false`
- `MeasureNoise = false`
### `ZeroMethod`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `Test.Module.Channel.Sensor.ZeroMethodType Method { get; set; }`
- `double Start { get; set; }`
- `double End { get; set; }`
- **Constructors**:
- `ZeroMethod(Test.Module.Channel.Sensor.ZeroMethodType zm, double _start, double _end)`
- `ZeroMethod(string zm)`
Parses a comma-separated string: `"MethodName,start,end"`; throws no exception on failure—silently returns uninitialized if tokens < 3.
- `ZeroMethod(ZeroMethod copy)`
Deep copy.
- **Methods**:
- `string ToDbString()`
Returns `"Method,start,end"` using default formatting.
- `string ToSerializeString()`
Returns `"Method,start,end"` using `InvariantCulture` for numbers.
### `DigitalOutputSetting`
- **Namespace**: `DatabaseExport`
- **Inherits**: `SensorData`
- **Properties**:
- `string ChannelDescription { get; set; }`
Getter returns `SerialNumber`; setter updates `SerialNumber` and raises `OnPropertyChanged("ChannelDescription")`.
- **Constructors**:
- `DigitalOutputSetting()`
Initializes with defaults via `SetDefaults`.
- `DigitalOutputSetting(System.Data.DataRow dr)`
Populates instance from database row. Supports fields from `DbOperations.DigitalOutputSettings.Fields`:
- `Version`, `OutputMode`, `LocalOnly`, `LimitDuration`, `LastModifiedBy`, `LastModified`, `DurationMSFloat`, `DelayMS`, `ChannelDescription`, `UserTags`
- `DurationMS` is ignored (marked obsolete).
- **Static Method**:
- `static void SetDefaults(SensorData sd)`
Sets defaults:
- `SupportedExcitation = [Volt5]`
- `Bridge = Test.Module.Channel.Sensor.BridgeType.TOMDigital`
- `AxisNumber = 0`, `NumberOfAxes = 1`
- `Capacity = 1`
- `DisplayUnit = "V"`
- `BridgeResistance = double.NaN`
- `CheckOffset = false`
- `Manufacturer = "Generic"`
- `OffsetToleranceHigh = 2500`
- `OffsetToleranceLow = 2500`
- `Model = "Digital Output Setting"`
- `Shunt = ShuntMode.None`
- `MeasureExcitation = false`
- `MeasureNoise = false`
### `FilterClass`
- **Namespace**: `DatabaseExport`
- **Nested Enum**: `FilterClassType`
- `None = 0`
- `AdHoc = -1`
- `CFC10 = 17`
- `CFC60 = 100`
- `CFC180 = 300`
- `CFC600 = 1000`
- `CFC1000 = 1650`
- **Fields**:
- `FilterClassType FClass { get; set; }`
- `double Frequency { get; set; }`
- **Constructors**:
- `FilterClass(FilterClassType fc)`
Initializes `FClass` and `Frequency` (e.g., `CFC60``Frequency = 100.0`). Throws on unknown type.
- `FilterClass(string fclass)`
Parses string (e.g., `"100"`, `"CFC60"`, `"123.45"`). Maps known numeric codes to enum values; falls back to `AdHoc` with parsed frequency.
- **Methods**:
- `override string ToString()`
Returns `"None"`, `"17 (CFC10)"`, etc., or numeric string for `AdHoc`.
### `SquibSetting`
- **Namespace**: `DatabaseExport`
- **Inherits**: `SensorData`
- **Properties**:
- `string SquibDescription { get; set; }`
Getter returns `SerialNumber`; setter updates `SerialNumber` and raises `OnPropertyChanged("SquibDescription")`.
- `bool BypassCurrentFilter { get; set; }`
- `bool BypassVoltageFilter { get; set; }`
- `string ArticleId { get; set; }`
Getter returns `Id`; setter updates `Id` and raises `OnPropertyChanged("ArticleId")`.
- **Constructors**:
- `SquibSetting(System.Data.DataRow dr)`
Populates from `tblTOMSquibChannels`. Supports fields from `DbOperations.Squib.Fields`:
- `Version`, `SquibToleranceLow`, `SquibToleranceHigh`, `SquibOutputCurrent`, `SquibDescription`, `MeasurementType`, `LocalOnly`, `LimitDuration`, `LastModifiedBy`, `LastModified`, `ISOCode`, `FireMode`, `DurationMS`, `DelayMS`, `BypassVoltageFilter`, `BypassCurrentFilter`, `ArticleId`, `UserValue1`, `UserValue2`, `UserValue3`, `UserTags`
- **Static Method**:
- `static void SetDefaults(SensorData sd)`
Sets defaults:
- `AxisNumber = 0`, `Capacity = 5`, `NumberOfAxes = 1`
- `Manufacturer = "Generic"`, `Model = "Squib Setting"`
- `Shunt = ShuntMode.None`
- `CheckOffset = false`
- `BridgeResistance = -1`
- `MeasureNoise = false`, `MeasureExcitation = false`
- `Bridge = Test.Module.Channel.Sensor.BridgeType.SQUIB`
- `SupportedExcitation = [Volt5]`
- `DisplayUnit = "V"`
- `Comment = SerialNumber` (if `UserValue1` is empty/whitespace)
### `IsoCode`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `string TestObject { get; set; }` (1 char, index 0)
- `string Position { get; set; }` (1 char, index 1)
- `string MainLocation { get; set; }` (4 chars, indices 25)
- `string FineLocation1 { get; set; }` (2 chars, indices 67)
- `string FineLocation2 { get; set; }` (2 chars, indices 89)
- `string FineLocation3 { get; set; }` (2 chars, indices 1011)
- `string PhysicalDimension { get; set; }` (2 chars, indices 1213)
- `string Direction { get; set; }` (1 char, index 14)
- `string FilterClass { get; set; }` (1 char, index 15)
- **Constructors**:
- `IsoCode(string isoCode)`
Normalizes input to 16 chars: truncates if >16, pads with `'?'` if <16.
- **Properties**:
- `string StringRepresentation { get; set; }`
Getter returns full 16-char string; setter normalizes to 16 chars (truncates/pads with `'0'` if shorter).
### `CalibrationRecords`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `CalibrationRecord[] Records { get; set; }`
- **Constructors**:
- `CalibrationRecords()`
Initializes with one default `CalibrationRecord`.
- `CalibrationRecords(CalibrationRecords copy)`
Deep copy of `Records`.
- `CalibrationRecords(string records)`
Parses serialized string via `FromSerializedString`.
- **Methods**:
- `void FromSerializedString(string s)`
Splits on `"__x__"` (with fallback `"___xx___"`), constructs `CalibrationRecord`s.
- `string ToSerializedString(SensorCalibration sc)`
Serializes each `CalibrationRecord`, escapes `"__x__"``"___xx___"`.
### `CalibrationRecord`
- **Namespace**: `DatabaseExport`
- **Fields**:
- `double Sensitivity { get; set; }`
- `double ZeroPoint { get; set; }`
Computed from `Poly.ZeroPositionIntercept / Poly.CalibrationFactor` if `Poly.CalibrationFactor ≠ 0`; else returns stored `_zeroPoint`.
- `LinearizationFormula Poly { get; set; }`
- `bool AtCapacity { get; set; } = false`
- `string EngineeringUnits { get; set; } = "g"`
- `Test.Module.Channel.Sensor.SensUnits SensitivityUnits { get; set; } = NONE`
- `Test.Module.Channel.Sensor.ExcitationVoltageOption Excitation { get; set; } = Volt5`
- `int CapacityOutputIsBasedOn { get; set; } = 1`
- **Constructors**:
- `CalibrationRecord()`
Initializes `Poly = new LinearizationFormula()`.
- `CalibrationRecord(string s)`
Parses via `FromString`.
- `CalibrationRecord(CalibrationRecord copy)`
Deep copy.
- **Methods**:
- `string ToSerializedString(SensorCalibration parentCal)`
Serializes fields (including `Poly`) with escaping of list separators.
- `void FromString(string s)`
Parses serialized string.
---
## 3. Invariants
- **`SensorRange`**: No explicit validation; `Low`, `Medium`, `High` may be any `double`.
- **`ZeroMethod`**: Parsing from string silently fails if fewer than 3 comma-separated tokens; no exception thrown.
- **`FilterClass`**: Constructor from `FilterClassType` throws `System.Exception` for unknown types. Constructor from string may assign `AdHoc` with arbitrary frequency.
- **`IsoCode`**: All 16 positions are always populated; missing/short inputs are padded with `'?'`, excess truncated. Setter for `StringRepresentation` pads with `'0'` (not `'?'`) if shorter than 16.
- **`CalibrationRecord.ZeroPoint`**: Computed value takes precedence over stored `_zeroPoint` if `Poly.CalibrationFactor ≠ 0`.
- **`SensorsCollection`**:
- Singleton via `SensorsList` (thread-safe via `lock`).
- `GetSensorBySerialNumber` excludes sensors with `Broken = true`, `DoNotUse = true`, or `NumberOfAxes > 1` or `AxisNumber > 0`.
- `AllSensorsDb` excludes multi-axis sensors but *not* `Broken`/`DoNotUse`.
- Sensors loaded from `tblSensors`, `tblDigitalInputSetting`, `tblTOMSquibChannels`, `tblTOMDigitalChannels` into a single `_sensorDictionary`.
---
## 4. Dependencies
### Internal Dependencies (Inferred from Source)
- **`Test.Module.Channel.Sensor` namespace**:
- Types used: `ZeroMethodType`, `BridgeType`, `ExcitationVoltageOption`, `SensUnits`
- **`DbOperations` namespace**:
- Nested types: `DigitalOutputSettings.Fields`, `Squib.Fields`, `DigitalInputSettings.Fields`
- Methods: `GetCommand()`, `Connection.QueryDataSet(...)`
- **`SensorData` base class**: Used by `DigitalInputSetting`, `DigitalOutputSetting`, `SquibSetting`. Not provided in source, but assumed to define common properties like `SerialNumber`, `Id`, `Version`, `LastModified`, `TagsBlobBytes`, `Broken`, `DoNotUse`, `UserValue1`, etc.
- **`LinearizationFormula`**: Referenced by `CalibrationRecord`. Not provided in source.
### External Dependencies
- `System` (core types: `Enum`, `Convert`, `StringBuilder`, `CultureInfo`)
- `System.Data` (`DataRow`, `DataSet`, `DBNull`)
- `System.Collections.Generic`
### What Depends on This Module?
- `SensorsCollection.SensorsList` is used to load and cache all sensor configurations at runtime.
- `DigitalInputSetting`, `DigitalOutputSetting`, `SquibSetting` are instantiated from database rows during initialization.
- `CalibrationRecords` and `CalibrationRecord` are used to serialize/deserialize calibration metadata.
---
## 5. Gotchas
- **`DigitalInputSetting.SetDefaults` sets `Capacity = 2400` then immediately overwrites to `1`** — likely a typo or legacy artifact.
- **`ZeroMethod` constructor from string silently ignores malformed input** — no exception, no logging; returns partially initialized object.
- **`IsoCode.StringRepresentation` setter pads with `'0'`, but constructor/partial setters pad with `'?'`** — inconsistent default padding.
- **`CalibrationRecord.ZeroPoint` is computed only when `Poly.CalibrationFactor ≠ 0`** — stored `_zeroPoint` may be stale if `Poly` changes.
- **`SensorsCollection.GetSensorBySerialNumber` returns `null` for multi-axis sensors** — even if valid — due to legacy restriction "Disable 6-axis sensor capability".
- **`FilterClass` constructor from string may assign `AdHoc` for unrecognized values** — no validation that frequency is positive or meaningful.
- **`DigitalOutputSetting` copy constructor is commented out** — no deep copy support for this type.
- **`CalibrationRecords` uses custom separators (`"__x__"` and `"___xx___"`)** — risk of collision if data contains these strings; escaping is manual and error-prone.
- **`SensorData` is not defined in provided sources** — behavior of inherited properties (e.g., `Id`, `SerialNumber`, `TagsBlobBytes`) must be inferred from usage.
- **`SquibSetting.Comment` defaults to `SerialNumber` if `UserValue1` is empty**, but `UserValue1` is set from DB row — potential for unintended override.

View File

@@ -0,0 +1,35 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Serialization/Control/DAS/IFilterable.cs
generated_at: "2026-04-16T05:00:02.860150+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "6a6ec5473cc48c6d"
---
# DAS
1. **Purpose**
This module defines the `IFilterable` interface within the `DatabaseExport` namespace, specifically as part of the Version 57 database export functionality under the `DAS` (likely *Data Acquisition System*) control layer. Its purpose is to serve as a marker interface—providing a type-level contract indicating that a slice control event module channel supports filtering. It exists to enable compile-time or runtime type-based identification of filterable entities, likely used in conjunction with filtering logic elsewhere in the export pipeline.
2. **Public Interface**
- **`IFilterable`**
- *Type*: Interface
- *Namespace*: `DatabaseExport`
- *Definition*: An empty interface with no members.
- *Behavior*: Serves solely as a type tag; implementation signals that a channel or module instance is eligible for filtering operations (e.g., by a downstream filter processor). No behavior is defined by this interface itself.
3. **Invariants**
- Any type implementing `IFilterable` must be a class or struct (as per C# interface implementation rules), but the interface imposes no additional constraints (e.g., no required properties, methods, or events).
- There are no stated runtime invariants, validation rules, or ordering guarantees derived from this interface alone.
- The interface is intended to be used in type checks (e.g., `is IFilterable`) or generic constraints (e.g., `where T : IFilterable`), but such usage is not specified in this file.
4. **Dependencies**
- **Dependencies *of* this module**: None. The file has no `using` directives and defines only an interface with no base interfaces or type references.
- **Dependencies *on* this module**: Not specified in this source file. However, given the namespace (`DatabaseExport`) and path (`DAS/IFilterable.cs`), it is likely consumed by modules in the same `DatabaseExport` project (e.g., filter processors, channel registrars, or serialization logic), but no such consumers are visible here.
5. **Gotchas**
- **Ambiguity of intent**: The interface is empty and lacks documentation beyond a single summary line. Its purpose as a *marker interface* is implied but not explicit; developers may misinterpret whether filtering behavior is expected to be implemented elsewhere (e.g., via extension methods or derived interfaces).
- **Typo in summary**: The XML comment reads “Methodical definition of a filterable slice control event module channle” — note the misspelling of *channel* as *channle*.
- **No versioning or deprecation markers**: The file resides in `Version57`, but the interface itself contains no attributes or comments indicating whether it is stable, deprecated, or subject to change in future versions.
- **None identified from source alone** regarding behavioral quirks or anti-patterns beyond the above.

View File

@@ -0,0 +1,43 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Serialization/Control/Event/Module/Channel/Channel.cs
generated_at: "2026-04-16T05:00:10.114585+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "9d5060432776d58c"
---
# Channel
## 1. Purpose
This module defines the abstract base class `Channel` for representing event channels within the DTS.Slice.Control.Event.Module hierarchy. It serves as a foundational abstraction for channel-specific event handling logic in the database export subsystem, providing core lifecycle management (via `IDisposable`) and filtering capabilities (via `IFilterable`). As an abstract class, it is intended to be subclassed by concrete channel implementations (e.g., for specific hardware or logical channel types), enabling polymorphic handling of event data associated with different channel configurations.
## 2. Public Interface
- **`public abstract partial class Channel : Exceptional, IFilterable, IDisposable`**
Abstract base class for event channels. Inherits from `Exceptional` (likely a custom base class providing exception-handling or error-state semantics) and implements `IFilterable` (indicating support for filtering operations) and `IDisposable` (indicating resource cleanup).
- **`public void Dispose()`**
Implements `IDisposable.Dispose()`. The method body is empty in this source, indicating either no unmanaged resources are held at this level, or cleanup logic is deferred to subclasses or handled elsewhere (e.g., via finalization or a separate cleanup mechanism not visible here).
## 3. Invariants
- `Channel` is **abstract**, so it cannot be instantiated directly; only concrete subclasses may be instantiated.
- Instances must satisfy `IFilterable` contract (e.g., support filtering logic via methods/properties defined in `IFilterable`, though those are not shown here).
- Instances must properly implement `IDisposable` semantics (i.e., `Dispose()` must be callable multiple times safely, per .NET conventions, though the empty implementation here suggests no cleanup is performed at this level).
- Inheritance chain: `Channel``Exceptional` (implied base for error handling), and `Channel` is nested within `Event.Module`, implying a hierarchical organization of event data.
## 4. Dependencies
- **Internal dependencies**:
- `Exceptional` (base class, likely defined elsewhere in the codebase; purpose inferred from name).
- `IFilterable` (interface, likely defined elsewhere; purpose inferred from name).
- `IDisposable` (standard .NET interface).
- **Namespace context**: `DatabaseExport` — suggests integration with database export functionality.
- **Nested structure**: Part of a partial class hierarchy (`Event.Module.Channel`), implying related definitions exist in `DTS.Slice.Control.Event.cs`, `DTS.Slice.Control.Event.Module.cs`, and potentially other files (as referenced in comments).
- **No external imports**: No `using` statements beyond the standard `System` namespace, indicating minimal external dependencies at this level.
## 5. Gotchas
- **Empty `Dispose()` implementation**: The `Dispose()` method has no body, which may indicate incomplete implementation, deferred cleanup in subclasses, or reliance on garbage collection for resource management. Developers must verify whether subclasses or outer containers handle actual resource disposal.
- **Partial class ambiguity**: The class is `partial`, and comments reference other files (`DTS.Slice.Control.Event.cs`, `DTS.Slice.Control.Event.Module.cs`). The full behavior (e.g., abstract members, concrete methods) may reside in those files and is not visible here.
- **Missing `IFilterable` details**: Since `IFilterable` is implemented but its members are not shown, the filtering contract (e.g., `bool Matches(Filter criteria)`) is unknown. Developers must inspect the `IFilterable` interface definition.
- **No constructor visibility**: The constructor is not shown; if private/internal, instantiation may be restricted (e.g., via factory methods in parent classes).
- **No method/property definitions**: This snippet shows only the class signature and `Dispose()`; other critical functionality (e.g., channel-specific event accessors) may exist in other partial definitions.
*None identified from source alone.*

View File

@@ -0,0 +1,37 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Serialization/SliceRaw/SliceRaw.File.PersistentChannel.cs
generated_at: "2026-04-16T04:59:57.519402+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "65d596a038308be3"
---
# SliceRaw
1. **Purpose**
This file defines a partial class `PersistentChannel` within the `DatabaseExport.File` namespace, intended to represent a channel whose state changes are immediately persisted to an associated channel file. Based on the summary comment and the commented-out interface implementations (`ExceptionalList<short>`, `ILargeDataAware`, `IChannelHeader`, `IDisposable`), the class is designed to serve as a live, file-backed abstraction over channel data—likely used for exporting or interfacing with legacy database versions (specifically Version 57, per the parent folder path). Its role is to provide a managed, in-memory view of persistent channel data with direct file synchronization semantics.
2. **Public Interface**
No public members (methods, properties, or events) are defined in this source file. The class `PersistentChannel` is declared as `public partial class`, but its body is empty in this file. All public interface members (if any) must be defined in other partial definitions of `PersistentChannel` (e.g., in sibling `.cs` files in the same project), which are not provided here.
3. **Invariants**
No invariants are explicitly stated or inferable from this file alone. However, based on the summary comment, the following is implied:
- Any modification to an instance of `PersistentChannel` must be immediately reflected in the underlying channel file on disk.
- The class likely maintains a file handle or stream to ensure persistence semantics (though not confirmed here).
Since the class declaration includes commented-out interface implementations, it is probable that certain interface contracts (e.g., `IDisposable` for resource cleanup, `IChannelHeader` for metadata access) were intended or previously used, but their enforcement or implementation details are not present in this file.
4. **Dependencies**
- **Internal**: Depends on the `DatabaseExport` namespace and the `File` partial class (defined elsewhere, likely in `SliceRaw.File.cs` or similar).
- **External**: No explicit external dependencies (e.g., no `using` directives) appear in this file. However, the commented-out interfaces (`ExceptionalList<short>`, `ILargeDataAware`, `IChannelHeader`, `IDisposable`) suggest that either:
- These interfaces are defined elsewhere in the same codebase (and their implementations reside in other partial files), or
- They were part of an earlier design and are now obsolete or deferred.
- **Consumers**: Likely consumed by other modules in the `DatabaseExport` namespace, particularly those handling Version 57 database export workflows (e.g., serialization, migration, or export logic in `Version57` folder).
5. **Gotchas**
- **Partial Class Ambiguity**: This file contributes only to a partial class definition; the full behavior of `PersistentChannel` cannot be understood without inspecting other partial definitions.
- **Commented-Out Interfaces**: The presence of commented-out interface implementations (`ExceptionalList<short>`, `ILargeDataAware`, `IChannelHeader`, `IDisposable`) may indicate incomplete refactoring, legacy design artifacts, or pending work. Developers should not assume these interfaces are implemented or enforced in this file.
- **No Implementation Visible**: The absence of any method/property definitions in this file means no behavior (e.g., read/write logic, persistence triggers, disposal semantics) can be verified here—critical functionality may reside elsewhere.
- **No Documentation on File Binding**: The phrase “immediately manifest in the associated channel file” is not elaborated; the mechanism (e.g., file path, locking strategy, flush behavior) is not specified in this source.
None identified beyond the above.

View File

@@ -0,0 +1,104 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SettingsDB/Setting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SettingsDB/GlobalSetting.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/SettingsDB/SettingsDB.cs
generated_at: "2026-04-16T04:58:48.501962+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "f305fd0e552dc54c"
---
# SettingsDB
## Documentation: `SettingsDB` Module (Version 57)
### 1. Purpose
This module provides a centralized, thread-safe mechanism for managing **global application settings** stored in a database. It abstracts database access for reading and writing string-based settings, caching them in-memory via a singleton pattern to avoid repeated DB queries. It is part of a legacy database export module (`Version57`) and is intended for use during migration or export workflows where persistent global configuration is needed. The module does *not* support user-specific settings in the current implementation.
---
### 2. Public Interface
#### `SettingsDB` (Static Class)
A singleton-managed static class for global setting operations.
- **`public static string GetGlobalValue(string id, string defaultValue)`**
Retrieves the global setting value for `id`. If not found in DB or cache, returns `defaultValue` after initializing and caching a `GlobalSetting`.
*Thread-safe via lock.*
- **`public static int GetGlobalValueInt(string id, int defaultValue)`**
Retrieves the global setting as an `int`. Converts the stored string value using `int.TryParse` with `CultureInfo.InvariantCulture`. Returns `defaultValue` on parse failure.
- **`public static bool GetGlobalValueBool(string id, bool defaultValue)`**
Retrieves the global setting as a `bool`. Converts the stored string value using `bool.TryParse`. Returns `defaultValue` on parse failure.
- **`public static void SetGlobalValue(string id, string value)`**
Stores `value` as the global setting for `id`. Updates in-memory cache and calls `SetValue()` on the cached `GlobalSetting`.
*Note: Actual DB persistence is commented out (`//StoreInDB();`) in `Setting.SetValue()` and `GlobalSetting.GetPropertyValue()`.*
- **`public static void SetGlobalValueInt(string id, int value)`**
Stores `value` as a string (using `CultureInfo.InvariantCulture`) for global setting `id`.
- **`public static void SetGlobalValueBoolean(string id, bool value)`**
Stores `value` as a string (`"True"`/`"False"`) for global setting `id`.
#### `Setting` (Abstract Base Class)
- **`public string PropertyId { get; }`**
Read-only identifier for the setting (e.g., `"Theme"`).
- **`public string PropertyValue { get; }`**
Current value of the setting (string). *No length validation is performed.*
- **`protected abstract void GetPropertyValue(string defaultValue)`**
Implemented by subclasses to populate `_propertyValue` from DB or fallback to `defaultValue`.
- **`public void SetValue(string value)`**
Updates `_propertyValue` in-memory. *DB persistence is disabled (commented out).*
#### `GlobalSetting` (Concrete Class)
- **`public GlobalSetting(string id, string defaultPropertyValue)`**
Constructor for global settings. Hardcodes `_userId = "SYSTEM"`.
- **`protected override void GetPropertyValue(string defaultValue)`**
Queries DB table `DbOperations.Settings.Table` for a row matching `PropertyId = @PropertyId AND UserId = "SYSTEM"`.
- On success: sets `_propertyValue` from DB column `PropertyValue`.
- On failure (no row, exception): sets `_propertyValue = defaultValue`.
*DB persistence on write is disabled (commented out).*
---
### 3. Invariants
- **Singleton enforcement**: `SettingsDB.Instance` is lazily initialized and thread-safe via `lock (_MyLock)`.
- **Cache consistency**: `_SettingsLookup` dictionary keys are `PropertyId` strings; each entry is a `Setting` instance (currently only `GlobalSetting` used).
- **Global-only scope**: `_userId` is hardcoded to `"SYSTEM"` in `GlobalSetting`; no user-specific settings are supported.
- **DB schema assumptions**:
- Table name: `DbOperations.Settings.Table`
- Columns: `PropertyId`, `UserId`, `PropertyValue` (all `NVarChar`).
- **No persistence**: `StoreInDB()` calls are commented out in both `Setting.SetValue()` and `GlobalSetting.GetPropertyValue()`. Thus, `SetGlobalValue*` methods *only update the in-memory cache* and do not write to the database.
- **Culture invariance**: All numeric/boolean conversions use `CultureInfo.InvariantCulture`.
---
### 4. Dependencies
- **Internal dependencies**:
- `DbOperations` (namespace/class referenced but not provided): Used for DB access (`GetCommand`, `CreateParam`, `QueryDataSet`, `Settings.Table`, `Settings.UserFields.*`).
- `System`, `System.Collections.Generic`, `System.Data` (explicitly imported).
- **Assumed external contracts**:
- `DbOperations.Settings.UserFields.PropertyId`, `UserId`, `PropertyValue` must correspond to valid column names in the settings table.
- Database table `DbOperations.Settings.Table` must exist with schema matching usage.
- **Depended on by**: Unknown (module is in `PreviousDBVersions/Version57/...` path, suggesting it is legacy/migration code).
---
### 5. Gotchas
- **No DB persistence**: Despite the modules purpose, *all writes are in-memory only*. `StoreInDB()` calls are commented out in both `Setting.SetValue()` and `GlobalSetting.GetPropertyValue()`. This is likely intentional for export/migration workflows but is a critical behavioral constraint.
- **No user-specific settings**: The `UserId` property and related logic are commented out in `Setting`; only `"SYSTEM"` is supported.
- **No validation**: `PropertyValue` accepts arbitrary strings without length checks, despite a "max length" being noted in comments.
- **Thread-safety scope**: Thread-safety applies only to cache access (`_SettingsLookup`), *not* to DB operations (which are not active).
- **Culture sensitivity**: Boolean/integer parsing uses `InvariantCulture`, but string storage does not enforce formatting (e.g., `"True"` vs `"true"`). `bool.TryParse` is case-sensitive (only `"True"`/`"False"` work).
- **Exception swallowing**: `GlobalSetting.GetPropertyValue()` silently falls back to `defaultValue` on any exception, masking DB errors.
- **Hardcoded `"SYSTEM"`**: The string `"SYSTEM"` is duplicated in `GlobalSetting` constructor and `GetPropertyValue`; no constant or enum is used.
- **No cache invalidation**: `SetGlobalValue*` updates the cache but does not clear it on external DB changes.
*None identified beyond these.*

View File

@@ -0,0 +1,230 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Storage/DbOperationsEnum.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Storage/DbVersion.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Storage/IDbTimeStampAware.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Storage/DbOperations.cs
generated_at: "2026-04-16T04:57:49.383657+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "a23af2f838d45bd9"
---
# Documentation: Database Export Module Version 57 (`DatabaseExport`)
---
## 1. Purpose
This module provides infrastructure for exporting and managing database schema and data for **Version 57** of the DataPRO system. It defines core abstractions for database interaction, including table/field metadata constants, stored procedure identifiers, version tracking (`DbVersion`), and timestamp-based concurrency control (`DbTimeStampBase`/`IDbTimeStampAware`). Its primary role is to support migration, export, and synchronization workflows by encapsulating versioned database structure and state management logic—particularly for legacy data exports where schema evolution must be tracked and reconciled.
---
## 2. Public Interface
### `DbOperationsEnum.StoredProcedure`
- **Type**: `enum`
- **Members**:
- `sp_DbVersionGet`: Represents the stored procedure used to retrieve the current database version.
### `DbVersion`
- **Constructor**:
```csharp
public DbVersion(System.Data.DataRow dr)
```
- **Behavior**: Initializes a `DbVersion` instance by extracting values from a `DataRow` expected to contain columns: `"Version"`, `"Step"`, `"Date"`, `"Remarks"`, and `"UserField"`.
- **Properties**:
- `int Version { get; set; }`
- Database version number.
- `int Step { get; set; }`
- Step within the version (e.g., migration step).
- `DateTime Date { get; set; }`
- Timestamp of the version/step.
- `string Remarks { get; set; }`
- Optional notes about the version/step.
- `string UserField { get; set; }`
- Arbitrary user-defined field.
### `IDbTimeStampAware` Interface & `DbTimeStampBase` Abstract Class
- **Interface**:
```csharp
public interface IDbTimeStampAware
{
long GetTimeStampMemory();
void SetTimeStampMemory(long value);
long GetTimeStampDb();
bool IsOutOfDate();
}
```
- **Abstract Base Class**: `DbTimeStampBase`
- **Properties**:
- `public abstract string LookupTable { get; }`
- Name of the database table used to look up the timestamp.
- `public abstract ConstraintHelper[] GetConstraints();`
- Returns an array of `ConstraintHelper` objects defining the primary key or unique constraints for the record.
- **Methods**:
- `long GetTimeStampMemory()`
- Returns the in-memory timestamp (`DbTimeStamp` field).
- `void SetTimeStampMemory(long value)`
- Sets the in-memory timestamp.
- `void SetTimeStampMemory(System.Data.DataRow row)`
- Sets in-memory timestamp to `0` (currently unimplemented beyond that).
- `void SetTimeStampMemory(System.Data.IDataReader reader)`
- Sets in-memory timestamp to `0` (currently unimplemented beyond that).
- `long GetTimeStampDb()`
- **Currently returns `0`** (implementation is commented out). Intended to fetch the database timestamp for the current record.
- `long GetTimeStampDb(Dictionary<string, long> lookup)`
- **Currently returns `0`** (implementation is commented out). Intended to fetch timestamp via lookup table.
- `Dictionary<string, long> GetAllTimeStampDb()`
- **Currently returns an empty dictionary** (implementation is commented out). Intended to fetch all timestamps from the database.
- `bool IsNotInDb()`
- Returns `true` if `GetTimeStampDb() == 0`.
- `bool IsOutOfDate()`
- Compares DB and memory timestamps:
- Returns `false` if DB timestamp is `0`.
- If memory timestamp is `0` and DB is non-zero, sets memory to DB and returns `false`.
- Otherwise returns `true` if DB ≠ memory.
- **Nested Types**:
- `ConstraintHelper`:
```csharp
public class ConstraintHelper
{
public string ColumnName { get; set; }
public System.Data.SqlDbType DbType { get; set; }
public object DbValue { get; set; }
}
```
- **Exception**:
- `DbItemOutOfDateException : Exception`
- Thrown when an item is detected as out-of-date (not used in current code, but defined).
### `DbOperations`
- **Nested Abstract Classes (Table/Field Constants)**:
- `Tags`:
- `Table = "tblTags"`, `TagFields` enum (`TagId`, `TagText`, `Obsolete`).
- `TAGASSIGNMENTS_TABLE = "TagAssignments"`, `TagAssignmentFields`.
- `DbVersions`:
- `DbVersionFields` enum (`Version`, `Step`, `Date`, `Remarks`, `UserField`).
- `Settings`, `Users`, `SensorDB`, `CalculatedChannels`, `LevelTriggers`, `TestSetups`, `TestObjectChannelSettings`, `DigitalOutputSettings`, `Squib`, `MMETables`, `DAS`, `DigitalInputSettings`
- All define table names and field enums (e.g., `TestSetups.TestSetupsTable = "tblTestSetups"`).
- `DbTypeAttr`:
- Custom attribute for mapping enum fields to SQL types (used in reflection via `GetDbType()`).
- `CustomChannelFieldSizeAttribute`:
- Custom attribute for specifying max field size (e.g., `[CustomChannelFieldSizeAttribute(50)]`).
- **Static Methods**:
- `SqlCommand GetSQLCommand(bool newCommand = false)`
- Returns a `SqlCommand` with an open connection (uses `Connection.GetLocalConnectionString()`). Clears parameters.
- `void CreateParam(IDbCommand icmd, string name, SqlDbType type, object value)`
- Adds a parameter to `icmd`. Special handling for `DateTime` (formats as `"yyyy-MM-dd HH:mm:ss"`).
- `DataSet QueryDataSet(IDbCommand icmd)`
- Executes `icmd` and returns results as `DataSet`. Supports both SQL Server (`_usingMSSQL == true`) and SQLite (fallback).
- `int ExecuteCommand(IDbCommand icmd)`
- Executes `icmd` (non-query) and returns affected rows. Supports both SQL Server and SQLite.
- `IDbCommand GetISOCommand()`
- Returns a new `SqlCommand` connected to the ISO database.
- `IDbCommand GetCommand()`
- Returns a new `SqlCommand` or `SQLiteCommand` depending on `_usingMSSQL`.
- **Static Properties**:
- `bool _usingCentralizedDB`, `_usingMSSQL`, `_usingNTLMAuthentication`, `_previousDir`
- `DbOperations Connection { get; }`
- Singleton instance of `DbOperations`.
- `bool LastConnectionStatus { get; set; }`
- Tracks last connection success/failure.
- `ConnectionStatusChangedDelegate ConnectionStatusChanged { get; set; }`
- Event for connection status changes.
- **Instance Properties**:
- `string Server`, `DBName`, `Username`, `Password`
- Connection configuration.
- `string GetLocalConnectionString()`, `GetLocalISOConnectionString()`
- Builds connection strings based on auth mode and settings.
---
## 3. Invariants
- **`DbVersion`**:
- All fields (`Version`, `Step`, `Date`, `Remarks`, `UserField`) are required in the source `DataRow`; nulls or missing columns will cause `InvalidCastException` or `NullReferenceException`.
- `Date` is parsed via `Convert.ToDateTime`, so culture-sensitive formatting may cause failures.
- **`DbTimeStampBase`**:
- `LookupTable` and `GetConstraints()` must be implemented by subclasses; otherwise, runtime errors occur.
- `GetTimeStampDb()` and `GetAllTimeStampDb()` currently **always return `0` or empty**, indicating incomplete implementation. No functional timestamp comparison occurs.
- `IsNotInDb()` and `IsOutOfDate()` rely on `GetTimeStampDb()` returning `0` for missing records—currently true by design (but not correctness, since `GetTimeStampDb()` is unimplemented).
- `SetTimeStampMemory(DataRow)` and `SetTimeStampMemory(IDataReader)` do **not** populate `DbTimeStamp`; they unconditionally set it to `0`.
- **`DbOperations`**:
- `_usingMSSQL` and `_usingCentralizedDB` control runtime behavior (e.g., which DB provider is used). Changing them mid-execution may cause inconsistent behavior.
- `GetLocalConnectionString()` throws `Exception("db connection not initialized")` if `Server` is `null`.
- `QueryDataSet` and `ExecuteCommand` throw `SystemException` with message `"NoConnection"` on connection failure.
- `CreateParam` for `DateTime` normalizes to `"yyyy-MM-dd HH:mm:ss"` format—potentially losing precision.
---
## 4. Dependencies
### This Module Depends On:
- **`System.Data`** (ADO.NET): `DataRow`, `DataSet`, `SqlDataAdapter`, `SqlCommand`, `SqlDbType`, `SqlDataReader`, `SqlException`, `ConnectionState`.
- **`System.Data.SqlClient`**: For SQL Server connectivity.
- **`System.Data.SQLite`**: For SQLite fallback (used when `_usingMSSQL == false`).
- **`System.ComponentModel`**: `INotifyPropertyChanged` (used by `DbTimeStampBase`).
- **`System.Reflection`**: Used in `DbTypeAttr.GetDbType()`.
### This Module Is Used By:
- Other modules in `DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/` (inferred from namespace).
- Likely consumed by migration scripts, export utilities, or data sync components that need to:
- Track DB version (`DbVersion`).
- Synchronize state with DB via timestamps (`DbTimeStampAware`).
- Access table/field metadata (`DbOperations.Tags`, `DbOperations.TestSetups`, etc.).
---
## 5. Gotchas
- **`GetTimeStampDb()` and `GetAllTimeStampDb()` are stubbed**:
All timestamp-related logic is non-functional. The implementations are commented out, so `IsOutOfDate()` and `IsNotInDb()` will always behave as if the record is missing or in-memory is authoritative. **Do not rely on timestamp concurrency control in this module.**
- **`SetTimeStampMemory(DataRow)` and `SetTimeStampMemory(IDataReader)` are no-ops**:
They set `DbTimeStamp = 0` regardless of input—likely placeholder code.
- **`DbOperations.Connection` is a singleton but mutable**:
`Connection.Server`, `DBName`, etc., can be set externally, potentially causing race conditions if accessed concurrently.
- **`CreateParam` for `DateTime` truncates precision**:
Converts `DateTime` to `"yyyy-MM-dd HH:mm:ss"` (no milliseconds), risking data loss.
- **`DbVersion` constructor lacks null/invalid column checks**:
Assumes `dr["Version"]`, `dr["Step"]`, etc., exist and are non-null. Will throw on schema mismatches.
- **`MMETables` field name inconsistencies**:
Notes that `"MyType"` → `"CustomChannelType"` → `"TYPE"` and `"Id"` → `"ID"` were used across versions. Code using these must handle historical schema differences.
- **`DbOperations.QueryDataSet` and `ExecuteCommand` have duplicated logic for SQL Server/SQLite**:
Code paths for both providers are interleaved, increasing maintenance risk. SQLite fallback uses `_previousDir` and `"db/datapro.db"`.
- **No error handling in `GetTimeStampDb`/`GetAllTimeStampDb` stubs**:
The commented-out code had `try/catch` blocks and logging (`APILogger.Log(ex)`), but the active code silently returns `0`.
- **`DbOperations.Connection` uses `GetLocalConnectionString()` which is not thread-safe outside the `lock`**:
While the singleton initialization is locked, `GetLocalConnectionString()` itself is not re-entrant safe (though `lock(dbLock)` is used internally).
- **`_usingMSSQL` and `_usingNTLMAuthentication` are static flags**:
Changing them after `Connection` is instantiated may not affect existing connections.
- **`DbItemOutOfDateException` is defined but never thrown**:
Its purpose is unclear; no usage found in the provided files.
---
*End of Documentation*

View File

@@ -0,0 +1,133 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Users/IUIItems.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Users/ITagAware.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Users/Tags.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Users/User.cs
generated_at: "2026-04-16T04:58:34.034818+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "d08339a454aa8af1"
---
# Users
## Documentation: `DatabaseExport.Users` Module (Version 57)
---
### 1. Purpose
This module provides data models and utilities for representing and persisting user account information in a legacy database export context (specifically for database version 57). It defines core abstractions for users (`User`), tag-aware entities (`TagAwareBase`), UI item identification (`IUIItems`), and centralized tag management (`Tags`). Its primary role is to enable serialization of user data—including permissions, visibility settings, and tags—into XML-compatible formats, while leveraging an in-memory cache of tags for efficient lookup. It supports default system users (e.g., `Admin`, `Guest`) and enforces immutability constraints on default users roles.
---
### 2. Public Interface
#### Interface: `IUIItems`
- **`string GetName()`**
Returns a unique string identifier for a UI item (e.g., tab or module name). Used as the key in permission/visibility dictionaries.
#### Abstract Class: `TagAwareBase`
- **`byte[] TagsBlobBytes { get; set; }`**
Serializes/deserializes the `TagIDs` array to/from a byte array using `Buffer.BlockCopy`. Setter includes a `try/catch` that silently discards exceptions (no logging in source).
- **`int[] TagIDs { get; set; }`**
Stores the list of tag IDs associated with the entity. Setter replaces with empty array if `null`.
- **`string GetTagsCommaSeperatedString()`**
Returns a comma-separated string of tag *text* values (e.g., `"Role:Admin,Version:1"`), derived from `TagIDs` via `GetTagsArray()`.
- **`virtual string[] GetTagsArray()`**
Converts `TagIDs` to human-readable tag strings using `Tags.GetTagTextFromIDs()`. Overridable.
#### Class: `Tags`
- **`class Tag`**
Represents a single tag with `ID`, `Text`, and `IsObsolete` fields. Includes:
- `const int INVALID_ID = -1`
- Constructor from `DataRow` (populates fields from DB columns; exceptions silently ignored).
- `Clone()` implementation (returns a new `Tag` instance with copied values).
- **`static Tags TagsInstance { get; }`**
Singleton accessor (lazy-initialized on first access).
- **`static string GetTagTextFromID(int tagID)`**
Returns the tag text for a given ID from the in-memory cache. Returns `null` if `tagID < 0`, `INVALID_ID`, or not found.
- **`static string[] GetTagTextFromIDs(int[] tagID)`**
Converts an array of tag IDs to an array of tag texts, skipping `INVALID_ID` and `null`/whitespace results.
- **`private void UpdateList()`**
Populates/refreshes the `_tagsLookup` dictionary by querying the database (`SELECT * FROM [Tags table]`). Uses `lock(MyLock)` for thread safety.
#### Class: `User`
- **Nested Enums**
- `DefaultRoles`: `Administrator`, `PowerUser`, `User`, `Guest`
- `UserPermissionLevels`: `Deny`, `Read`, `ReadAndExecute`, `Edit`, `Admin`
- `Tags`: Enumerates tag names used for user metadata (e.g., `Role`, `UserName`, `Password`)
- `XmlFields`: Enumerates XML element names for serialization (e.g., `ID`, `UserName`, `IUIItemPermissions`)
- **Constants**
- `DEFAULT_LAST_MODIFIED_BY = "---"`
- `DEFAULT_ADMIN_USERNAME = "Admin"`, `DEFAULT_GUEST_USERNAME = "Guest"`, etc.
- `INVALID_ID = -1`
- **Properties**
- `bool IsADefaultUser``true` if `UserName` matches `GetDefaultUserName(Role)`.
- `string Name`, `string UserName`, `int Id`, `DefaultRoles Role`, `int Version`, `DateTime LastModified`, `string LastModifiedBy`, `bool LocalOnly`
- `private readonly Dictionary<IUIItems, UserPermissionLevels> _tabPermissions`
- `private readonly Dictionary<IUIItems, bool> _showTabs`
- **Methods**
- **`public override ConstraintHelper[] GetConstraints()`**
Returns a constraint for `UserName` (used for uniqueness validation).
- **`public override string LookupTable => DbOperations.Users.USERS_TABLE`**
Specifies the database table name.
- **`public User(DataRow row)`**
Constructor that initializes all properties from a database `DataRow`.
- **`public string GetPermissionSerialized()`**
Serializes `_tabPermissions` as `"UIItemName=PermissionLevelInt,..."` (thread-safe via `lock(TabPermissionsLock)`).
- **`public static string GetDefaultUserName(DefaultRoles role)`**
Maps `DefaultRoles` to default usernames (e.g., `Administrator``"Admin"`).
- **`public string GetVisibilitySerialized()`**
Serializes `_showTabs` as `"UIItemName=1/0,..."`.
- **`public Dictionary<string, string> GetValues()`**
Returns a dictionary of XML field names to values for serialization, including:
- Basic fields (`ID`, `UserName`, `DisplayName`, `Password`, `Role`, etc.)
- Serialized permissions (`IUIItemPermissions`)
- Serialized visibility (`IUIItemVisibility`)
- Tag string (`UserTags` via `GetTagsCommaSeperatedString()`)
---
### 3. Invariants
- **`TagIDs` must be non-null**: The `TagIDs` setter replaces `null` with `new int[0]`.
- **`INVALID_ID = -1` is excluded from tag lookups**: `GetTagTextFromID` and `GetTagTextFromIDs` explicitly skip `INVALID_ID`.
- **Default users are immutable by role**: Setting `Role` on a `User` where `IsADefaultUser == true` throws `NotSupportedException` if the role changes.
- **Tag text lookup is case-sensitive and text-based**: `_tagsLookup` uses `Tag.Text` as the dictionary key (in `UpdateList()`), but `GetTagTextFromId` searches by `Tag.ID` (linear scan).
- **`TagsInstance` is a singleton**: Initialized once on first access; `_tagsLookup` is populated only at construction and via `UpdateList()` (not auto-refreshed).
- **`TagsBlobBytes` size must be divisible by `sizeof(int)`**: The setter assumes `value.Length % sizeof(int) == 0`; otherwise, `Buffer.BlockCopy` may throw (caught silently).
---
### 4. Dependencies
- **Imports/Usings**:
- `System`, `System.Text`, `System.Collections.Generic`, `System.Linq`, `System.Data`
- **External Types Referenced (from source)**:
- `DbOperations.Tags` (static class with `TagFields` enum and `Table` property)
- `DbOperations.Users` (static class with `UserFields` enum and `USERS_TABLE` property)
- `DbOperations.Connection` (provides `QueryDataSet`)
- `DbOperations.GetCommand()` (returns `IDbCommand`)
- `DbTimeStampBase` (base class of `TagAwareBase`; not shown, assumed to provide timestamp fields)
- `ConstraintHelper` (used in `GetConstraints()`)
- **Depended Upon By**:
- `User` is used by export/serialization logic (e.g., `GetValues()` implies integration with XML export).
- `Tags.TagsInstance` is used by `TagAwareBase.GetTagsArray()` and `User.GetValues()`.
- `IUIItems` is used as a key in `User`s permission/visibility dictionaries (implementations not in this source).
---
### 5. Gotchas
- **Silent exception handling**: Multiple `catch (Exception)` blocks (in `TagAwareBase.TagsBlobBytes`, `Tag` constructor, `Tags.UpdateList`) log nothing—only commented-out logging stubs exist. Errors may go unnoticed.
- **Inefficient tag lookup**: `GetTagTextFromId` performs a linear scan over `_tagsLookup` to find by ID, despite `_tagsLookup` being keyed by `Text`. This is O(n) per lookup.
- **`TagsBlobBytes` setter is fragile**: Assumes input byte array length is divisible by `sizeof(int)`; otherwise, `Buffer.BlockCopy` throws (caught silently).
- **`TagsInstance` not thread-safe during initialization**: `_tagsInstance` is assigned without double-checked locking (only `null == _tagsInstance` check), risking multiple instantiations in multi-threaded scenarios.
- **`IsADefaultUser` is role-dependent but role change is restricted**: A users default status is computed at runtime, but changing the role of a default user is blocked—this may cause confusion if default usernames are reassigned.
- **`GetTagsCommaSeperatedString()` has typo**: Method name uses "Seperated" (missing 'a'), consistent with legacy naming.
- **`TagsBlobBytes` and `TagIDs` are redundant**: `TagsBlobBytes` is a byte-level serialization of `TagIDs`, but only `TagIDs` is used in `GetTagsArray()`. `TagsBlobBytes` may be legacy or for external compatibility.
- **No validation of `UserName` uniqueness**: While `GetConstraints()` defines a uniqueness constraint, enforcement is external (e.g., in DB or caller), and the `User` class does not validate this itself.
None identified beyond these.

View File

@@ -0,0 +1,116 @@
---
source_files:
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Utilities/DiskUtility.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Utilities/Exceptional.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Utilities/ExceptionalList.cs
- DataPRO/Modules/PreviousDBVersions/Version57/DatabaseExport/Utilities/AttributeCoder.cs
generated_at: "2026-04-16T04:58:12.148784+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "290a5af10b3d9412"
---
# Documentation: `DatabaseExport.Utilities` Module
## 1. Purpose
This module provides foundational utilities for the `DatabaseExport` subsystem, specifically supporting attribute-based encoding/decoding of enum values and basic file/path name validation. It enables a consistent pattern for associating metadata (attributes) with enum members and mapping between those metadata values and the enums themselves. The module also establishes a base class hierarchy (`Exceptional`, `ExceptionalList<T>`) for type-specific exception handling, allowing callers to catch exceptions by their originating class type. This module is part of a legacy codebase targeting database version 57 export functionality.
## 2. Public Interface
### `DiskUtility`
A static utility class for validating file and path names.
- **`ValidateFileAndPathNameChars(string nameToValidate)`**
- **Signature**: `public static bool ValidateFileAndPathNameChars(string nameToValidate)`
- **Behavior**: Returns `true` if `nameToValidate` contains no characters from `Path.GetInvalidFileNameChars()` or `Path.GetInvalidPathChars()`, has non-zero length after trimming, and does **not** contain a period (`.`). Returns `false` otherwise.
- **Note**: Explicitly rejects any string containing `.` (e.g., file extensions), beyond standard OS-invalid characters.
### `Exceptional`
An abstract base class for enabling type-specific exception handling.
- **No public methods or properties**.
- **Purpose**: Serves as a marker base class. Derived classes may define nested `Exception` types (as shown in the remarks), but the base class itself provides no runtime behavior beyond being serializable.
### `ExceptionalList<T>`
A generic list class inheriting from `List<T>` for type-specific exception handling.
- **No public methods or properties beyond those inherited from `List<T>`**.
- **Purpose**: Provides a base type that can be subclassed to define custom exception types (e.g., `MyList : ExceptionalList<int> { public class Exception : System.Exception { ... } }`), per the pattern described in the remarks.
### `AttributeCoder<TargetType, AttributeType, AttributeValueType>`
A generic helper for mapping between enum values (`TargetType`), their associated attributes (`AttributeType`), and extracted values (`AttributeValueType`).
- **Delegates**:
- `AttributeValueExtractionMethod(AttributeType attribute) → AttributeValueType`
Defines how to extract an `AttributeValueType` from an `AttributeType` instance.
- `AttributeValueEqualityComparisonMethod(AttributeValueType, AttributeValueType) → bool`
Defines custom equality logic for `AttributeValueType`. If `null`, defaults to `Equals()`.
- **Constructors**:
- `AttributeCoder(AttributeValueExtractionMethod, AttributeValueEqualityComparisonMethod = null)`
Initializes the coder. Throws `Exception` if `attributeValueExtractionMethod` is `null`. Stores both delegates.
- **Methods**:
- **`DecodeAttributeValue(TargetType target) → AttributeValueType`**
Extracts the *single* `AttributeValueType` from the attribute attached to `target`.
- Internally calls `DecodeAttributeValues(target)` and asserts exactly one value exists.
- Throws `Exception` if no attributes found or if multiple attributes exist.
- **`DecodeAttributeValues(TargetType target) → List<AttributeValueType>`**
Extracts *all* `AttributeValueType`s from attributes of type `AttributeType` attached to `target`.
- Uses reflection: `target.GetType().GetField(target.ToString())` to get the `FieldInfo` of the enum field named by `target.ToString()`.
- Retrieves custom attributes of type `AttributeType` on that field.
- Applies `_extractAttributeValue` to each attribute to produce the list.
- **`EncodeAttributeValue(AttributeValueType attributeValue) → TargetType`**
Returns the *single* `TargetType` enum value whose attribute has `attributeValue`.
- Internally calls `DehashAttributeValue(attributeValue)` and asserts exactly one match.
- Throws `Exception` if zero or multiple matches.
- **`DehashAttributeValue(AttributeValueType attributeValue) → List<TargetType>`**
Returns *all* `TargetType` enum values whose attributes match `attributeValue`.
- Enumerates all values of `TargetType` via `Enum.GetValues(typeof(TargetType))`.
- For each, calls `DecodeAttributeValue(target)` and compares to `attributeValue` using either `_areAttributeValuesEqual` (if provided) or `Equals()`.
- Throws `Exception` if no matches found.
## 3. Invariants
- **`DiskUtility.ValidateFileAndPathNameChars`**:
- A valid name must be non-empty after trimming, contain no invalid filename/path characters (per `Path.GetInvalidFileNameChars()`/`Path.GetInvalidPathChars()`), and contain no `.` characters.
- **Critical constraint**: The presence of `.` alone causes rejection, regardless of other validity.
- **`AttributeCoder`**:
- `DecodeAttributeValue` and `EncodeAttributeValue` assume *exactly one* attribute per enum field and *exactly one* enum field per attribute value, respectively. They throw if this is violated.
- `DecodeAttributeValues` and `DehashAttributeValue` do *not* assume uniqueness and return lists.
- `DecodeAttributeValues` relies on the `TargetType` being an `enum` and that `target.ToString()` yields a valid field name on the enum type.
- The `AttributeType` must be applied as a custom attribute on the enum *field* (not the value itself), and `GetField(target.ToString())` must succeed.
- `AttributeValueExtractionMethod` must be non-null; `AttributeValueEqualityComparisonMethod` may be `null` (defaults to `Equals`).
## 4. Dependencies
### This module depends on:
- `System.IO` (for `Path.GetInvalidFileNameChars()`, `Path.GetInvalidPathChars()`)
- `System.Linq` (for `Cast<T>()`, `Where()`, `Select()`, `ToList()`)
- `System.Diagnostics` (for `Debug.Assert`)
- `System.Collections.Generic` (for `List<T>`)
- `System` (for `Exception`, `SerializableAttribute`, `Enum`)
### This module is depended upon by:
- **Inferred**: Other modules in `DatabaseExport` (not visible here) likely use `AttributeCoder` to map between enums and metadata (e.g., database column types, export options).
- `DiskUtility` is likely used by export logic that constructs file paths dynamically.
- `Exceptional`/`ExceptionalList<T>` are base types; specific subclasses (not provided) are used throughout the codebase for typed exceptions.
## 5. Gotchas
- **`DiskUtility.ValidateFileAndPathNameChars`**:
- The explicit ban on `.` is non-standard and may conflict with typical file naming conventions (e.g., `.txt`, `data.csv`). This is likely intentional to prevent extension confusion in internal naming, but is a critical constraint.
- Validation is case-sensitive for content (e.g., `..` is invalid, but `..` is not explicitly checked beyond `.` presence).
- **`AttributeCoder`**:
- **Fragile reflection usage**: `target.GetType().GetField(target.ToString())` assumes the `TargetType` is an `enum` and that `ToString()` returns the exact field name. If `TargetType` is not an enum, or if custom `ToString()` overrides exist, this will fail.
- **No support for multiple attributes per field**: `DecodeAttributeValues` collects all attributes of `AttributeType`, but `DecodeAttributeValue` expects exactly one and throws otherwise.
- **Equality semantics**: If `_areAttributeValuesEqual` is `null`, `Equals()` is used. Value types (e.g., `int`, `string`) usually work, but reference types may require custom equality (e.g., for case-insensitive strings).
- **Exception messages are not localized**: Commented-out `Resources.*` strings indicate localization was intended but not implemented. All exceptions use hardcoded English strings.
- **No null-safety on `target`**: Passing `null` to `DecodeAttributeValue`/`DecodeAttributeValues` will throw `NullReferenceException` before reaching intended error handling.
- **`EncodeAttributeValue`/`DehashAttributeValue` are inverses only if the mapping is bijective**: If multiple enum values map to the same attribute value, `EncodeAttributeValue` will fail.
- **`Exceptional`/`ExceptionalList<T>`**:
- These classes provide *no runtime behavior* beyond inheritance. Their utility relies on subclasses defining nested `Exception` types (as shown in remarks), which are not present in the provided source. Callers must infer usage from comments.
- `ExceptionalList<T>` adds no functionality beyond `List<T>`; it is only a marker for exception hierarchy.