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,87 @@
---
source_files:
- Common/DTS.Common.CPU/CPUModule.cs
generated_at: "2026-04-16T11:34:07.271819+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5a3256f83f5993a9"
---
# Documentation: DTS.Common.CPU.CPUModule
## 1. Purpose
This module serves as the initialization logic for the "CPU" component within a modular WPF application built on the Microsoft Prism framework. It is responsible for registering the `CPUEngine` implementation with the Unity dependency injection container and providing assembly-level metadata (name and image) used by the main application shell to display available components.
## 2. Public Interface
### Class: `CPUModule`
Implements `IModule` (from `Microsoft.Practices.Prism.Modularity`). This is the entry point for the module logic.
* **Constructor**: `CPUModule(IUnityContainer unityContainer)`
* Accepts a Unity container instance via constructor injection.
* **Method**: `void Initialize()`
* Registers type mappings in the Unity container.
* **Registration**: `ICPUEngine` maps to `CPUEngine`.
* **Commented Code**: Contains a commented-out registration for `IPropertyViewModel`.
### Class: `CPUNameAttribute`
Inherits from `TextAttribute`. Provides the assembly name metadata.
* **Constructor**: `CPUNameAttribute()` / `CPUNameAttribute(string s)`
* The string argument `s` is accepted but ignored.
* **Property**: `string AssemblyName` (read-only)
* Returns the hardcoded string `"CPUAsssembly"`.
* **Method**: `Type GetAttributeType()`
* Returns `typeof(TextAttribute)`.
* **Method**: `string GetAssemblyName()`
* Returns the value of the `AssemblyName` property.
### Class: `CUPImageAttribute`
Inherits from `ImageAttribute`. Provides assembly image and categorization metadata. Note the class name spelling "CUP".
* **Constructor**: `CUPImageAttribute()` / `CUPImageAttribute(string s)`
* The string argument `s` is accepted but ignored. Initializes the image resource.
* **Property**: `BitmapImage AssemblyImage` (read-only)
* Retrieves an image using `AssemblyInfo.GetImage(AssemblyNames.CPU.ToString())`.
* **Property**: `string AssemblyName` (read-only)
* Returns `AssemblyNames.CPU.ToString()`.
* **Property**: `string AssemblyGroup` (read-only)
* Returns `eAssemblyGroups.Viewer.ToString()`.
* **Property**: `eAssemblyRegion AssemblyRegion` (read-only)
* Returns `eAssemblyRegion.NotAssigned`.
* **Methods**:
* `Type GetAttributeType()`: Returns `typeof(ImageAttribute)`.
* `BitmapImage GetAssemblyImage()`: Returns `AssemblyImage`.
* `string GetAssemblyName()`: Returns `AssemblyName`.
* `eAssemblyRegion GetAssemblyRegion()`: Returns `AssemblyRegion`.
* `string GetAssemblyGroup()`: Returns `AssemblyGroup`.
## 3. Invariants
* **Hardcoded Name**: The `CPUNameAttribute` always returns the string `"CPUAsssembly"`, regardless of constructor arguments.
* **Fixed Group/Region**: The `CUPImageAttribute` always defines the module group as `"Viewer"` and the region as `NotAssigned`.
* **Singleton Registration**: The `CPUModule` class comment implies the intent to register components as singletons, though `RegisterType` (used for `ICPUEngine`) typically registers a transient mapping by default in Unity unless a `ContainerControlledLifetimeManager` is specified. The specific lifetime manager is not visible in the source, so the "singleton" behavior mentioned in comments is not strictly enforced by the code shown.
## 4. Dependencies
### Internal Dependencies
* **`DTS.Common.Interface`**: Required for `ICPUEngine`, `TextAttribute`, `ImageAttribute`, `IUnityContainer` (if defined there), and `IModule` (if abstracted).
* **`DTS.Common.CPU`**: The namespace itself contains `CPUEngine` (referenced in `Initialize` but not defined in the file).
* **`AssemblyInfo`**: Used statically to fetch images (source not provided, assumed to be a helper class).
* **`AssemblyNames`**: An enum or constant class used to identify the CPU module (source not provided).
* **`eAssemblyGroups`**: An enum defining module groups (source not provided).
* **`eAssemblyRegion`**: An enum defining UI regions (source not provided).
### External Dependencies
* **`System.ComponentModel.Composition`**: Used for the `[Export]` attribute.
* **`System.Windows.Media.Imaging`**: Used for `BitmapImage`.
* **`Microsoft.Practices.Prism.Modularity`**: Used for `IModule` and `[Module]` attribute.
* **`Microsoft.Practices.Unity`**: Used for `IUnityContainer` and dependency injection APIs.
## 5. Gotchas
* **Typo in Attribute Class Name**: The class is named `CUPImageAttribute` (C-U-P) instead of `CPUImageAttribute`. The assembly attribute usage at the top `[assembly: CUPImage()]` matches this typo, so it functions correctly, but the naming is inconsistent.
* **Typo in Assembly Name String**: `CPUNameAttribute` returns the string `"CPUAsssembly"` (with three 's' characters). This may cause issues if other parts of the system expect "CPUAssembly" or "CPU".
* **Ignored Constructor Parameters**: Both attribute constructors accept a string parameter `s` but do not use it. This creates a misleading API where a developer might assume they can set a custom name or value.
* **Side Effects in Property Getters**: The `AssemblyImage` property getter in `CUPImageAttribute` modifies the private field `_img` (`_img = AssemblyInfo.GetImage(...)`). This is a side effect inside a getter, which violates standard C# property guidelines and could lead to unexpected behavior or performance hits during property access.
* **Commented Code**: The `Initialize` method contains commented-out code for `IPropertyViewModel`, suggesting incomplete features or tech debt regarding property view registration.

View File

@@ -0,0 +1,125 @@
---
source_files:
- Common/DTS.Common.Calculations/ChannelData.cs
- Common/DTS.Common.Calculations/Integral.cs
- Common/DTS.Common.Calculations/Resultant.cs
- Common/DTS.Common.Calculations/HeadInjuryCriterion.cs
generated_at: "2026-04-16T11:35:26.354514+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2d2deac012cb62cf"
---
# DTS.Common.Calculations Module Documentation
## 1. Purpose
This module provides mathematical calculation utilities for signal processing, specifically focused on biomechanical injury analysis. It contains a data container class (`ChannelData`) for holding filtered time-series data with associated engineering units, and implements algorithms for numerical integration (`Integral`), vector resultant calculation (`Resultant`), and Head Injury Criterion computation (`HeadInjuryCriterion`). The module is designed to work with pre-filtered sensor data, particularly acceleration channels used in impact testing.
---
## 2. Public Interface
### `ChannelData` Class
A data container for holding filtered channel data with associated engineering units.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `ChannelData(string units)` | Constructs a new `ChannelData` instance with the specified engineering units. |
| `Units` | `string Units { get; }` | Read-only property returning the engineering units of the data. |
| `FilteredEU` | `double[] FilteredEU { get; set; }` | Gets or sets the pre-filtered engineering unit data array. |
---
### `Integral` Static Class
Provides numerical integration methods.
| Method | Signature | Description |
|--------|-----------|-------------|
| `DefiniteIntegral` | `static double DefiniteIntegral(double[] input, int start, int end, double SPS)` | Computes the definite integral of `input` from index `start` to `end` (both inclusive) using trapezoidal summation. `SPS` is samples per second (sample rate). Returns the integrated value. |
---
### `Resultant` Static Class
Provides vector resultant calculation from multiple input channels.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GenerateResultantChannel` | `static ChannelData GenerateResultantChannel(List<ChannelData> channels)` | Generates a resultant channel by computing the square root of the sum of squares across all input channels at each sample index. Returns a new `ChannelData` with the resultant values. |
---
### `HeadInjuryCriterion` Static Class
Provides Head Injury Criterion (HIC) calculation for biomechanical analysis.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetHeadInjuryCriterion` | `static HICResult GetHeadInjuryCriterion(ChannelData resultant, double SPS, int clipLengthMS)` | Calculates the maximum Head Injury Criterion over the input `resultant` acceleration channel for the specified `clipLengthMS` duration. `SPS` is the actual sample rate in samples per second. Returns an `HICResult` containing the maximum HIC value and its location. |
#### `HICResult` Nested Class
A result container for HIC calculations.
| Property | Type | Description |
|----------|------|-------------|
| `StartSample` | `int` | The starting sample index of the maximum HIC window. |
| `EndSample` | `int` | The ending sample index of the maximum HIC window. |
| `HicLengthMS` | `int` | The HIC clip length in milliseconds. |
| `HIC` | `double` | The calculated maximum HIC value. |
| Constructor | Signature |
|-------------|-----------|
| `HICResult` | `HICResult(double hic, int hicLength, int startSample, int endSample)` |
---
## 3. Invariants
- **`Integral.DefiniteIntegral`**: The input data must be tightly time-aligned (uniform sampling interval). The method assumes constant spacing between samples, allowing division by `SPS` rather than computing variable time deltas.
- **`Resultant.GenerateResultantChannel`**: All channels in the input list must have:
- Identical `FilteredEU` array lengths
- Identical `Units` values
These constraints are enforced via `Trace.Assert` calls.
- **`HeadInjuryCriterion.GetHeadInjuryCriterion`**:
- `SPS` must be greater than 0
- `clipLengthMS` must be greater than 0
- The `resultant.FilteredEU` array must contain at least `clipLengthMS` worth of data (specifically, at least `maxclip` samples where `maxclip = Ceiling(clipLengthMS * SPS / 1000)`)
---
## 4. Dependencies
### This module depends on:
- `System` (for `Math`, `Convert`, `DateTime`-related types)
- `System.Collections.Generic` (for `List<T>`)
- `System.Linq` (for `Distinct()`, `Max()`, `First()`, `Count()`, `Select()`)
- `System.Diagnostics` (for `Trace.Assert`)
### What depends on this module:
- **Unclear from source alone** — no consumers are shown in the provided files. This appears to be a foundational calculation library intended for use by higher-level analysis modules.
---
## 5. Gotchas
1. **Assertion behavior in production**: All validation is performed using `System.Diagnostics.Trace.Assert`. By default, `Trace.Assert` only triggers a dialog in debug builds and may be silently ignored in release configurations depending on trace listener configuration. Invalid inputs may produce incorrect results rather than explicit failures in production.
2. **Brute-force HIC algorithm**: The `GetHeadInjuryCriterion` method uses an exhaustive brute-force approach, recalculating integrals repeatedly. The source explicitly acknowledges this inefficiency with the comment: *"we are exhaustively recalculating sums, we can do this much better without a doubt."* Performance may be poor for large datasets.
3. **Documentation typo in `HICResult` constructor**: The XML documentation comments for the constructor parameters have the descriptions for `endSample` and `startSample` swapped:
```csharp
/// <param name="endSample">start sample of HIC</param>
/// <param name="startSample">end sample of HIC</param>
```
The actual parameter order is `(hic, hicLength, startSample, endSample)`.
4. **Future unit conversion not implemented**: The `ChannelData` class stores units but provides no unit conversion functionality. The comment indicates this is planned for future implementation.
5. **Potential parallelization opportunity**: The `Resultant.GenerateResultantChannel` method contains a comment indicating parallelization is planned for a future version, but the current implementation is single-threaded.

View File

@@ -0,0 +1,45 @@
---
source_files:
- Common/DTS.Common.Core/DTSConstants.cs
generated_at: "2026-04-16T11:28:44.689683+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "481b6b8f305c2ca6"
---
# Documentation: DTS.Common.Core.DTSConstants
## 1. Purpose
This module provides a centralized container for constant values used within the DTS system. Specifically, it defines compile-time constant file paths for application configuration files. It exists to decouple configuration file locations from the main application logic, although the current implementation suggests a development-centric or hardcoded approach.
## 2. Public Interface
### Class: `DTSConstants`
**Type:** `public static class`
**Namespace:** `DTS.Common.Core`
This class exposes the following public constants:
* **`CustomConfigPath`**
* **Signature:** `public const string`
* **Value:** `C:\dev\DTS.Viewer\bin\Debug\DTS.Viewer.exe.config`
* **Description:** Defines a hardcoded absolute path to a specific configuration file.
* **`ViewerConfigPath`**
* **Signature:** `public const string`
* **Value:** `C:\dev\DTS.Viewer\bin\Debug\DTS.Viewer.exe.config`
* **Description:** Defines a hardcoded absolute path to the viewer's configuration file.
## 3. Invariants
* **Compile-time Evaluation:** Because the fields are defined as `const string`, their values are embedded directly into calling assemblies at compile time. Changing these values requires recompilation of all dependent code.
* **Value Equality:** As currently defined, `CustomConfigPath` and `ViewerConfigPath` always hold identical string values.
## 4. Dependencies
* **Internal Dependencies:** None. The file contains no `using` statements and relies only on default system types.
* **External Consumers:** Any project referencing `DTS.Common.Core` may access `DTSConstants`. Specific consumer modules cannot be determined from this file alone.
## 5. Gotchas
* **Hardcoded Absolute Paths:** Both constants point to `C:\dev\...`. This code will likely fail or behave unexpectedly on any machine that does not have this exact directory structure. It appears to be configured specifically for a local development environment.
* **Debug Build Reference:** The paths explicitly reference `\bin\Debug\`, implying these constants are not intended for production release builds without modification.
* **Redundancy:** `CustomConfigPath` and `ViewerConfigPath` are currently identical. It is unclear if this is intentional (two names for the same file) or a copy-paste error where `CustomConfigPath` should point to a different location.
* **Naming Suppression:** The file includes a ReSharper annotation `// ReSharper disable InconsistentNaming` to suppress naming warnings, likely regarding the "DTS" prefix or capitalization rules.

View File

@@ -0,0 +1,104 @@
---
source_files:
- Common/DTS.Common.Core/Config/DTSConfig.cs
generated_at: "2026-04-16T11:41:16.907673+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2693b2d1a0d0acee"
---
# Documentation: DTSConfig.cs
## 1. Purpose
`DTSConfig` is a static utility class that provides centralized access to application configuration settings from an alternate configuration file. It exists to allow the application to read settings from a custom `.config` file path rather than the default application configuration, supporting scenarios where configuration needs to be externalized or shared across components. The class acts as a configuration facade, wrapping `System.Configuration.ConfigurationManager` functionality with thread-safe access and logging for missing keys or sections.
---
## 2. Public Interface
### `AltConfigPathGet()`
**Signature:** `public static string AltConfigPathGet()`
Returns the currently set alternate configuration file path. Thread-safe via locking on `MyLock`.
---
### `AltConfigPathSet(string path)`
**Signature:** `public static void AltConfigPathSet(string path)`
Sets the alternate configuration file path. Updates `AltConfigPath` only; does not reload the configuration. Thread-safe via locking on `MyLock`.
---
### `DTSConfigInit(string path)`
**Signature:** `public static void DTSConfigInit(string path)`
Initializes the configuration system by calling `SetAltConfigPath(path)`. This is the primary entry point for setting up the alternate configuration at application startup.
---
### `GetAltConfig()`
**Signature:** `public static Configuration GetAltConfig()`
Returns the `System.Configuration.Configuration` object representing the loaded alternate configuration file. Thread-safe via locking on `MyLock`.
---
### `SetAltConfigPath(string path)`
**Signature:** `public static void SetAltConfigPath(string path)`
Sets the alternate configuration path and immediately loads the configuration file. If `path` is null or empty, falls back to `DTSConstants.CustomConfigPath`. Creates an `ExeConfigurationFileMap` and opens the configuration via `ConfigurationManager.OpenMappedExeConfiguration`. Thread-safe via locking on `MyLock`.
---
### `GetAppSetting(string key)`
**Signature:** `public static string GetAppSetting(string key)`
Retrieves an application setting value by key from the alternate configuration's `AppSettings` section. Returns `string.Empty` if the key is not found (logs a warning via `APILogger.Log`). Does not throw exceptions for missing keys.
---
### `GetSection(string sectionName)`
**Signature:** `public static object GetSection(string sectionName)`
Retrieves a configuration section by name from the alternate configuration. Returns `null` if the section is not found (logs a warning via `APILogger.Log`). Used by plugin code to retrieve plugin library sections.
---
## 3. Invariants
- **Thread Safety:** All access to static fields (`AltConfigPath`, `AltConfig`) is protected by a lock on `MyLock`.
- **Configuration Initialization:** `AltConfig` is populated when `SetAltConfigPath()` is called; calling `GetAppSetting()` or `GetSection()` before initialization will result in a `NullReferenceException` (not guarded against in source).
- **Fallback Path:** When `SetAltConfigPath(string path)` receives a null or empty path, it uses `DTSConstants.CustomConfigPath` as the configuration file location.
- **Missing Key Handling:** `GetAppSetting()` returns `string.Empty` for missing keys rather than `null` or throwing an exception.
- **Missing Section Handling:** `GetSection()` returns `null` for missing sections and logs the absence.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Utilities.Logging` — Uses `APILogger.Log()` for warning messages
- `System.Configuration` — Uses `Configuration`, `ConfigurationManager`, `ExeConfigurationFileMap`, `KeyValueConfigurationElement`, `ConfigurationUserLevel`
- `System.Linq` — Uses `Cast<>()` and `FirstOrDefault()`
- `DTSConstants.CustomConfigPath` — Referenced constant (defined elsewhere, location not shown in source)
### What depends on this module:
- **Unclear from source alone** — No consumers are shown in this file. The `GetSection()` method documentation mentions "plugin code" as a consumer.
---
## 5. Gotchas
1. **Redundant API Surface:** Both `DTSConfigInit()` and `SetAltConfigPath()` perform the same operation. `DTSConfigInit()` simply delegates to `SetAltConfigPath()` with no additional logic.
2. **Inconsistent Naming Convention:** The class exposes both `AltConfigPathGet()/AltConfigPathSet()` (Java-style) and `SetAltConfigPath()` (C#-style) methods for similar operations, creating potential confusion.
3. **Uninitialized State Not Guarded:** Calling `GetAppSetting()` or `GetSection()` before `SetAltConfigPath()` or `DTSConfigInit()` will throw a `NullReferenceException` since `AltConfig` starts as `null`.
4. **Empty Static Constructor:** The static constructor is explicitly defined but empty, which is unnecessary.
5. **Silent Failure on Missing Keys:** Missing configuration keys return `string.Empty` rather than throwing, which may mask configuration errors. Consumers must check for empty string rather than null.
6. **ReSharper Suppressions:** The file suppresses `InconsistentNaming` warnings, suggesting naming conventions in this file deviate from project standards.

View File

@@ -0,0 +1,73 @@
---
source_files:
- Common/DTS.Common.Core/EventManager/EventManager.cs
generated_at: "2026-04-16T11:42:05.172295+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "59cbfaadaa1e572f"
---
# Documentation: DTS.Common.Core.EventManager
## 1. Purpose
The `EventManager` class provides a static, global implementation of the Publish/Subscribe (Pub/Sub) pattern. It enables decoupled communication between system components, allowing publishers to emit events without knowledge of subscribers, and subscribers to react to events without direct coupling to publishers. Additionally, it provides a diagnostic infrastructure to monitor the event system's activity, such as tracking subscription counts and event publication flow.
## 2. Public Interface
### Delegates
* **`SubscriberCallbackDelegate<in T>(T item)`**
* The signature required for methods subscribing to events.
* Constraint: `T` must be a reference type (`class`).
* **`DiagnosticCallbackDelegate(EventDiagnosticType eventType, Type t, object eventData, string listener)`**
* The signature required for methods subscribing to diagnostic events regarding the EventManager's internal operations.
### Static Class: `EventManager`
#### Methods
* **`void Publish(T eventData) where T : class`**
* Publishes an event of type `T` to all registered subscribers.
* Iterates through the subscriber list for type `T`. If a subscriber has an `EventFilter`, the filter is evaluated; the callback is invoked only if the filter returns `true`.
* If no subscribers exist for type `T`, the method returns immediately without throwing an exception.
* **`void Subscribe(SubscriberCallbackDelegate listener) where T : class`**
* Registers a listener for event type `T` without a filter.
* Overload: `void Subscribe(SubscriberCallbackDelegate listener, Predicate eventFilter) where T : class`
* Registers a listener with a predicate filter. The callback will only be invoked if `eventFilter(eventData)` returns `true`.
* **`void UnSubscribe(SubscriberCallbackDelegate listener) where T : class`**
* Removes a specific listener from the subscriber list for type `T`.
* Uses the `Callback` delegate equality to find and remove the matching `EventMetaData`.
* **`void Clear()`**
* Removes all listeners for all event types from the `SubscriberList`.
* **`void SubscribeToDiagnosticEvents(DiagnosticCallbackDelegate listener)`**
* Registers a listener to receive diagnostic events (e.g., when items are added or removed).
* **`void UnSubscribeToDiagnosticEvents(DiagnosticCallbackDelegate listener)`**
* Removes a specific listener from the diagnostic events list.
* **`void ClearDiagnosticEvents()`**
* Removes all listeners from the diagnostic events list.
### Enum: `EventDiagnosticType`
Defines the types of diagnostic events generated by the system.
* `AddListener` (0)
* `AddListenerDiagnostic` (1)
* `PublishEvent` (2)
* `RemoveListenerDiagnostic` (3)
* `RemoveListener` (4)
## 3. Invariants
* **Type Constraint:** All event types `T` used in `Publish`, `Subscribe`, and `UnSubscribe` must be reference types (`class`).
* **Thread Safety:** The source code does not contain any locking mechanisms (e.g., `lock`, `Monitor`) around the static `Dictionary` or `List` collections. The module assumes a single-threaded execution context or requires external synchronization by the caller.
* **Reference Equality:** Unsubscription relies on delegate reference equality. A subscriber must pass the exact same delegate instance used during `Subscribe` to successfully `UnSubscribe`.
* **Internal Storage:** Listeners are stored internally as `EventMetaData` objects within a `List<object>`, despite the dictionary value type being `List<object>`.
## 4. Dependencies
* **Internal Dependencies:**
* `System.Collections.Generic` (for `Dictionary`, `List`, `Predicate`)
* `System.Reflection` (for `MemberInfo`, `Type` used in diagnostics)
* **External Dependencies:**
* None identified from the source file alone. As a core utility, it is likely widely depended upon by higher-level application modules.
## 5. Gotchas
* **Thread Safety Risk:** The `SubscriberList` and `DiagnosticList` are static and mutable. Concurrent calls to `Subscribe`/`Publish` from different threads will cause race conditions and likely throw exceptions (e.g., `InvalidOperationException` on the list enumerator during `Publish`).
* **Diagnostic "Clear" Behavior:** The `ClearDiagnosticEvents()` method clears the `DiagnosticList` *before* sending the final `RemoveListenerDiagnostic` event. Consequently, the final diagnostic event is sent to an empty list and will effectively be lost/ignored.
* **Diagnostic Noise during Publish:** The `Publish` method sends a `PublishEvent` diagnostic message *inside* the loop for every single subscriber. If one event has 10 subscribers, 10 diagnostic events are fired for a single `Publish` call.
* **Memory Leaks:** Because `SubscriberList` is static and holds references to delegate targets, failing to call `UnSubscribe` will prevent the subscriber objects from being garbage collected.
* **Silent Failures:** `Publish` silently ignores the event if no subscribers are registered. `UnSubscribe` silently does nothing if the listener is not found.

View File

@@ -0,0 +1,149 @@
---
source_files:
- Common/DTS.Common.Core/PluginLib/PluginConfigData.cs
- Common/DTS.Common.Core/PluginLib/PluginConfig.cs
- Common/DTS.Common.Core/PluginLib/PluginConfigSectionHandler.cs
- Common/DTS.Common.Core/PluginLib/PluginManager.cs
generated_at: "2026-04-16T11:42:06.536831+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "698a84042cfeb418"
---
# PluginLib Module Documentation
## 1. Purpose
The `PluginLib` module provides a Managed Extensibility Framework (MEF)-based plugin infrastructure for the DTS system. It handles discovery, loading, and retrieval of plugins from configurable directories, supporting both single-plugin resolution and multiple implementations of the same interface. The module abstracts configuration management through custom configuration section handlers and provides thread-safe singleton access to the plugin catalog and container.
---
## 2. Public Interface
### `PluginManager` (Class)
The primary entry point for plugin operations.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetPluginManager` | `public static PluginManager GetPluginManager(string appPath)` | Returns the singleton instance of `PluginManager`. Initializes the plugin system on first call with the provided `appPath`. Thread-safe via lock on `THREAD_LOCK`. |
| `GetPlugin<T>` | `public static T GetPlugin<T>() where T : class` | Retrieves a single MEF export of type `T`. Returns `null` if no export exists. Throws if multiple exports exist for the same type. |
| `GetPlugin<T>` | `public static T GetPlugin<T>(string configPluginSetting) where T : class` | Retrieves a specific plugin from multiple exports by matching `configPluginSetting` against the plugin's `ToString()` value. |
| `GetPlugins<T>` | `public static IEnumerable<Lazy<T>> GetPlugins<T>() where T : class` | Returns all MEF exports of type `T` as lazy-initialized references. |
| `GetPluginList<T>` | `public List<Assembly> GetPluginList<T>() where T : class` | Returns a list of distinct `Assembly` objects from all loaded directory catalogs. Note: The generic type parameter `T` is not used in the implementation. |
| Property | Type | Description |
|----------|------|-------------|
| `PluginCatalog` | `AggregateCatalog` | The MEF aggregate catalog containing all loaded plugin directories. |
---
### `PluginConfig` (Static Class)
Provides configuration helper methods.
| Member | Signature | Description |
|--------|-----------|-------------|
| `DTSPlugins` | `public const string DTSPlugins = "DTSPlugins"` | Constant for the app setting key name. |
| `GetDTSPluginsSetting` | `public static string GetDTSPluginsSetting(string setting)` | Concatenates the app setting value for `DTSPlugins` with the provided `setting` parameter using `.` as separator. |
---
### `PluginConfigSectionHandler` (Class)
Configuration section handler for `DTS.Common.Core.PluginLib.Config`.
| Property | Type | Description |
|----------|------|-------------|
| `HashKeys` | `FilterHashKeyCollection` | Returns the collection of plugin folder elements from the configuration section. |
---
### `FilterHashKeyCollection` (Class)
Collection class for configuration elements.
| Member | Signature | Description |
|--------|-----------|-------------|
| `this[int idx]` | `public FilterHashElement this[int idx]` | Indexer to access elements by position. |
---
### `FilterHashElement` (Class)
Represents a single plugin folder configuration entry.
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `Key` | `string` | Yes | The key identifier for the element. |
| `Value` | `string` | No | The plugin directory path. |
---
### `PluginConfigData` (Class)
XML serialization support class for legacy configuration format.
| Field | Type | Description |
|-------|------|-------------|
| `PluginFolders` | `string[]` | Array of plugin folder paths. Serialized with `XmlArrayItem("Folder")` attribute. |
---
## 3. Invariants
1. **Singleton Pattern**: `_pluginManager` is a static singleton; once initialized, subsequent calls to `GetPluginManager` return the existing instance regardless of the `appPath` parameter passed.
2. **Thread Safety**: All access to the singleton initialization is protected by `THREAD_LOCK` object.
3. **Configuration Requirement**: The configuration section `"DTS.Common.Core.PluginLib.Config"` must exist in the application configuration file, or the `PluginManager` constructor throws an `Exception`.
4. **Directory Existence**: All plugin directories specified in `FilterHashElement.Value` must exist at initialization time, or an `IOException` is thrown.
5. **Assembly Exclusion**: Assemblies with names starting with `"DTS.Common"`, `"C1"`, or `"Xceed"` are explicitly excluded from manual assembly loading in the constructor.
6. **MEF Export Uniqueness**: `GetPlugin<T>()` (the parameterless overload) expects exactly zero or one export of type `T`; MEF throws an exception if multiple exports exist.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Core.Config` - For `DTSConfig.GetSection()`, `DTSConfig.GetAppSetting()`, and `DTSConfig.DTSConfigInit()`
- `DTS.Common.Utilities.Logging` - For `APILogger.Log()` static method
- `System.ComponentModel.Composition.Hosting` - MEF container and catalog types
- `System.ComponentModel.Composition.ReflectionModel` - For `ReflectionModelServices.GetPartType()`
- `System.Configuration` - For configuration section infrastructure
- `System.Xml.Serialization` - For `PluginConfigData` XML serialization
### Consumers:
- Any module requiring plugin extensibility via MEF exports
- Code calling `PluginManager.GetPlugin<T>()` or `PluginManager.GetPlugins<T>()`
---
## 5. Gotchas
1. **Unused Assembly Resolve Handler**: The method `CurrentDomain_AssemblyResolve` is defined but **never wired up** to `AppDomain.CurrentDomain.AssemblyResolve`. It will never be called unless external code attaches it.
2. **Configuration Section Name Inconsistency**: `PluginConfigData` is decorated with `[XmlRoot(ElementName = "DatPro.Core.PluginLib.Config")]` (legacy "DatPro" naming), while `PluginManager` looks for `"DTS.Common.Core.PluginLib.Config"`. These are different section names; `PluginConfigData` appears to be legacy/unused code.
3. **Unused Parameter in GetPluginList**: The generic type parameter `T` in `GetPluginList<T>()` is declared but never used in the method body. The method returns all assemblies regardless of type.
4. **Dead Code Before Lock**: In `GetPluginManager()`, a `DirectoryInfo` object is created from `appPath` before the lock but never used:
```csharp
if (!string.IsNullOrWhiteSpace(appPath))
{
var directoryInfo = new DirectoryInfo(appPath);
}
```
5. **Empty Loop Bodies**: The singleton check contains loops with empty bodies:
```csharp
foreach (var catalog in _pluginManager.PluginCatalog.Catalogs)
{
var directoryCatalog = catalog as DirectoryCatalog;
if (directoryCatalog == null) continue;
}
```
This appears to be vestigial code with no effect.
6. **Plugin Matching via ToString()**: `GetPlugin<T>(string configPluginSetting)` matches plugins by comparing `item.Value.ToString()` to `configPluginSetting`. This relies on the plugin's `ToString()` override returning a meaningful identifier.
7. **Null Return Possible**: `GetPlugin<T>()` returns `null` if no export is found, not an exception. Callers must handle null.
8. **Hardcoded Assembly Exclusions**: The exclusion list (`"DTS.Common"`, `"C1"`, `"Xceed"`) is hardcoded in the constructor and not configurable.

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.Core/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:42:40.333369+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f157b2a2cacdeb5d"
---
# Documentation: DTS.Common.Core Assembly Metadata
## 1. Purpose
This file provides assembly-level metadata and configuration for the `DTS.Common.Core` library. It defines the assembly's identity, version information, and COM visibility settings using .NET attributes. This module exists to embed standard manifest information into the compiled DLL, facilitating identification, versioning, and interop configuration within the larger DTS system.
## 2. Public Interface
This file does not contain public classes or methods. It defines the following assembly-level attributes:
* **`AssemblyTitle`**: Set to `"DTS.Common.Core"`.
* **`AssemblyDescription`**: Set to an empty string.
* **`AssemblyConfiguration`**: Set to an empty string.
* **`AssemblyCompany`**: Set to an empty string.
* **`AssemblyProduct`**: Set to `"DTS.Common.Core"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2016"`.
* **`AssemblyTrademark`**: Set to an empty string.
* **`AssemblyCulture`**: Set to an empty string (indicates the assembly is culture-neutral).
* **`ComVisible`**: Set to `false`. This makes types in the assembly invisible to COM components.
* **`Guid`**: Set to `"bdf5ad7a-51db-4ad0-8186-d1ead7405848"`. This is the unique identifier for the typelib if exposed to COM.
* **`AssemblyVersion`**: Set to `"1.0.0.0"`.
* **`AssemblyFileVersion`**: Set to `"1.0.0.0"`.
## 3. Invariants
* **COM Visibility:** Types within this assembly are explicitly non-visible to COM components unless individually overridden.
* **Culture Neutrality:** The assembly is marked with an empty `AssemblyCulture`, indicating it is not a satellite assembly and is culture-neutral.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `1.0.0.0`.
## 4. Dependencies
* **Internal Dependencies:** This file imports `System.Reflection`, `System.Runtime.CompilerServices`, and `System.Runtime.InteropServices`.
* **External Consumers:** Cannot be determined from this source file alone. Any project referencing the compiled `DTS.Common.Core.dll` depends on this metadata.
## 5. Gotchas
* **Hardcoded Versions:** The version numbers (`1.0.0.0`) are hardcoded strings. If the project uses CI/CD pipelines to auto-increment versions, this file may need to be updated or the build process configured to overwrite these attributes.
* **Missing Metadata:** `AssemblyDescription`, `AssemblyCompany`, and `AssemblyConfiguration` are empty. This may lack context for developers inspecting the DLL properties.
* **Legacy Format:** This file structure suggests an older .NET Framework project style (non-SDK style). Modern .NET Core/5+ projects often embed this information in the `.csproj` file, potentially leading to duplication or confusion if the project is ever migrated.

View File

@@ -0,0 +1,68 @@
---
source_files:
- Common/DTS.Common.Core/ServiceManager/IServicePublishedEvent.cs
- Common/DTS.Common.Core/ServiceManager/ServicePublishedEvent.cs
- Common/DTS.Common.Core/ServiceManager/ServiceManager.cs
generated_at: "2026-04-16T11:43:09.898125+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "a01f75e5b963dd9f"
---
# Documentation: DTS.Common.Core.ServiceManager
## 1. Purpose
This module implements a service locator pattern via a static `ServiceManager` class. It allows components to publish implementations of interfaces (services) into a global container and retrieve them elsewhere without direct coupling to the implementation. It acts as a runtime registry for singleton services, supporting publication, retrieval, existence checks, and un-publication, while broadcasting state changes via an event system.
## 2. Public Interface
### `IServicePublishedEvent` (Interface)
Defines the contract for events fired when a service state changes.
* `Type ServiceType { get; }` — Gets the type of the service being published or unpublished.
* `bool IsPublished { get; }` — Returns `true` if the service is being published; `false` if it is being unpublished.
### `ServicePublishedEvent` (Class)
Concrete implementation of `IServicePublishedEvent`.
* `Type ServiceType { get; internal set; }` — The service type. The setter is `internal`.
* `bool IsPublished { get; internal set; }` — The publication state. The setter is `internal`.
### `ServiceManager` (Static Class)
The static gateway for managing service registration.
* `public static void Publish(T item) where T : class`
* Registers a service implementation `item` under the interface type `T`.
* Throws `ArgumentException` if `T` is already registered.
* `public static void Publish(object item, IEnumerable<Type> interfaceList, bool skipPublishedInterfaces)`
* Registers a single object `item` as the implementation for multiple interfaces defined in `interfaceList`.
* If `skipPublishedInterfaces` is `false`, throws `ArgumentException` if any interface in the list is already registered.
* If `skipPublishedInterfaces` is `true`, silently skips already registered interfaces.
* `public static bool Exists() where T : class`
* Returns `true` if a service of interface type `T` is currently registered; otherwise `false`.
* `public static bool Exists(Type t)`
* Non-generic overload. Returns `true` if the specified `Type t` is registered; otherwise `false`.
* `public static T Get() where T : class`
* Retrieves the registered service implementation for interface type `T`.
* Throws `ArgumentException` if `T` has not been published.
* `public static void Clear() where T : class`
* Un-registers the service for interface type `T`. Fires an "unpublished" event.
* `public static void Clear(IEnumerable<Type> interfaceList)`
* Un-registers all services for the types specified in `interfaceList`. Fires "unpublished" events for each removed service.
## 3. Invariants
* **Uniqueness:** The `ServiceManager` enforces a one-to-one mapping between a `Type` and a service instance. A `Type` cannot be published twice unless the previous instance is cleared or the batch publish method is used with `skipPublishedInterfaces` set to `true`.
* **Reference Types Only:** All generic methods (`Publish`, `Exists`, `Get`, `Clear`) constrain the type parameter `T` to `class`.
* **Event Ordering:** When clearing a service, the `IServicePublishedEvent` (with `IsPublished = false`) is fired **before** the service is removed from the internal dictionary.
* **Exception Consistency:** Both `Publish<T>` and `Get<T>` throw `ArgumentException` (not a custom exception type) for invalid states (already exists / not found).
## 4. Dependencies
* **Dependencies (Internal):**
* `ServiceManager` depends on `ServicePublishedEvent` to create event payloads.
* `ServicePublishedEvent` depends on `IServicePublishedEvent`.
* **Dependencies (External):**
* `ServiceManager` depends on `EventManager.EventManager`. The private method `SendServicePublishedEvent` calls `EventManager.EventManager.Publish<IServicePublishedEvent>(...)`. The location/assembly of `EventManager` is not defined in the provided source but is required for this module to compile and run.
* **Standard Libraries:** `System`, `System.Collections.Generic`.
## 5. Gotchas
* **Thread Safety:** The internal storage `Dictionary<Type, object> Services` uses standard `System.Collections.Generic.Dictionary`. There are no locks or synchronization mechanisms in `ServiceManager`. This module is **not thread-safe**. Concurrent calls to `Publish`, `Get`, or `Clear` may result in race conditions or corruption.
* **Event Manager Coupling:** The `ServiceManager` is tightly coupled to a specific `EventManager.EventManager` class. If that event manager is not initialized or accessible, the `Publish` and `Clear` methods will fail at runtime when attempting to broadcast events.
* **Silent Failures in Batch Publish:** When calling `Publish(object, IEnumerable<Type>, bool)` with `skipPublishedInterfaces` set to `true`, the method will silently ignore interfaces that are already registered. This could lead to stale service instances remaining active if the caller assumed the new `item` would replace them.
* **Clear Event Timing:** Because the "unpublished" event fires before the item is removed from the dictionary, an event subscriber handling `IServicePublishedEvent` with `IsPublished == false` could technically still call `ServiceManager.Exists(type)` and receive `true` inside their event handler.

View File

@@ -0,0 +1,114 @@
---
source_files:
- Common/DTS.Common.Core/Settings/SettingsChangedEventArgs.cs
- Common/DTS.Common.Core/Settings/SettingsCollection.cs
generated_at: "2026-04-16T11:41:07.381293+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "e48bcdd1082dba01"
---
# Documentation: DTS.Common.Core.Settings
## 1. Purpose
This module provides an observable dictionary implementation that notifies subscribers when settings change. It consists of `SettingsCollection<TKey, TItem>`, a generic dictionary wrapper that implements `IDictionary<TKey, TItem>` and fires events on modifications, and `SettingsChangedEventArgs<TKey, TItem>`, the event payload describing what changed. This enables reactive patterns where consumers can respond to configuration or settings changes without polling.
---
## 2. Public Interface
### `SettingsCollection<TKey, TItem>`
A generic dictionary implementation that raises events on mutation.
**Event:**
- `event EventHandler<SettingsChangedEventArgs<TKey, TItem>> CollectionItemPropertyChanged` — Fired after any add, remove, modify, or clear operation.
**Constructors:**
- None explicitly defined; uses default constructor.
**Properties:**
- `ICollection<TKey> Keys { get; }` — Returns all keys in the collection. Delegates to internal dictionary.
- `ICollection<TItem> Values { get; }` — Returns all values in the collection. Delegates to internal dictionary.
- `TItem this[TKey key] { get; set; }` — Indexer. Getter returns value for key; setter assigns value and fires `ChangeSettingType.Add` event.
- `int Count { get; }` — Returns count of items.
- `bool IsReadOnly { get; }` — Always returns `false`.
**Methods:**
- `void Add(TKey key, TItem value)` — Adds key-value pair; fires `ChangeSettingType.Add` event.
- `void Add(KeyValuePair<TKey, TItem> item)` — Adds key-value pair; fires `ChangeSettingType.Add` event.
- `bool ContainsKey(TKey key)` — Returns `true` if key exists.
- `bool Contains(KeyValuePair<TKey, TItem> item)` — Returns `true` if both key and value match an entry.
- `bool Remove(TKey key)` — Removes by key; fires `ChangeSettingType.Remove` event if successful. Returns success boolean.
- `bool Remove(KeyValuePair<TKey, TItem> item)` — Removes by key (ignores value); fires `ChangeSettingType.Remove` event if successful. Returns success boolean.
- `bool TryGetValue(TKey key, out TItem value)` — Attempts to retrieve value for key.
- `void Clear()` — Clears all items; fires `ChangeSettingType.ClearAll` event.
- `void CopyTo(KeyValuePair<TKey, TItem>[] array, int arrayIndex)`**Throws `NotImplementedException`.**
- `IEnumerator<KeyValuePair<TKey, TItem>> GetEnumerator()` — Returns enumerator.
- `IEnumerator IEnumerable.GetEnumerator()` — Returns non-generic enumerator.
---
### `SettingsChangedEventArgs<TKey, TItem>`
Event arguments describing a settings change.
**Constructors:**
- `SettingsChangedEventArgs(ChangeSettingType changeType)` — Initializes with change type only.
- `SettingsChangedEventArgs(ChangeSettingType changeType, TKey key)` — Initializes with change type and key.
- `SettingsChangedEventArgs(ChangeSettingType changeType, TKey key, TItem item)` — Initializes with change type, key, and item.
**Properties:**
- `ChangeSettingType ChangeType { get; }` — The type of change (read-only).
- `TKey Key { get; }` — The key associated with the change (read-only).
- `TItem Item { get; }` — The value associated with the change (read-only).
---
### `ChangeSettingType` (enum)
Defines the type of settings change.
| Value | Name | Numeric Value |
|-------|------|---------------|
| `Add` | Item added | 0 |
| `Remove` | Item removed | 1 |
| `Modified` | Item modified | 3 |
| `ClearAll` | Collection cleared | 4 |
---
## 3. Invariants
- **Event firing occurs after mutation:** Events are fired only after the underlying dictionary has been successfully modified (e.g., `Remove` fires only if removal succeeded).
- **Key and Item properties may be default/uninitialized:** Depending on which constructor is used, `Key` and `Item` may be `default(TKey)` or `default(TItem)` respectively. Consumers should check `ChangeType` to determine which properties are meaningful.
- `IsReadOnly` always returns `false`.
- The internal `_items` dictionary is never null (initialized at declaration).
---
## 4. Dependencies
**This module depends on:**
- `System` (for `EventArgs`, `EventHandler<T>`)
- `System.Collections` (for `IEnumerable`)
- `System.Collections.Generic` (for `IDictionary<TKey, TItem>`, `Dictionary<TKey, TItem>`, `ICollection<T>`, `KeyValuePair<TKey, TItem>`)
**Consumers (inferred):**
- Any module requiring observable settings/configuration storage.
- Cannot determine specific consumers from source alone.
---
## 5. Gotchas
1. **Indexer setter uses `ChangeSettingType.Add`, not `Modified`:** The indexer `this[TKey key]` setter always fires `ChangeSettingType.Add`, even when overwriting an existing key. The `Modified` enum value (3) is never used in this implementation.
2. **`CopyTo` is not implemented:** Calling `CopyTo(KeyValuePair<TKey, TItem>[] array, int arrayIndex)` throws `NotImplementedException`. This will cause runtime failures if the collection is used with APIs that call `CopyTo`.
3. **`Remove(KeyValuePair<TKey, TItem>)` ignores the value:** The `Remove(KeyValuePair<TKey, TItem> item)` method only checks and removes by key, ignoring `item.Value`. This differs from typical `IDictionary` implementations that verify the value matches before removal.
4. **Enum has a gap:** `ChangeSettingType` has values 0, 1, 3, 4 — value 2 is skipped. This may indicate a removed/renamed value or historical artifact.
5. **No validation on constructor arguments:** `SettingsChangedEventArgs` constructors do not validate that `Key` and `Item` are provided when `ChangeType` would logically require them (e.g., `Add` without a key/item).

View File

@@ -0,0 +1,83 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/AvailableArmModes.cs
- Common/DTS.Common.DAS.Concepts/ArmStatus.cs
- Common/DTS.Common.DAS.Concepts/ITriggerable.cs
- Common/DTS.Common.DAS.Concepts/IDataCollectionEnabled.cs
- Common/DTS.Common.DAS.Concepts/ILargeDataAware.cs
- Common/DTS.Common.DAS.Concepts/ICalibratable.cs
- Common/DTS.Common.DAS.Concepts/IGpioEnabled.cs
- Common/DTS.Common.DAS.Concepts/IRealtimeable.cs
- Common/DTS.Common.DAS.Concepts/DataScaler.InvalidExcitationVoltageException.cs
- Common/DTS.Common.DAS.Concepts/ShuntModeType.cs
- Common/DTS.Common.DAS.Concepts/TsrEvent.cs
- Common/DTS.Common.DAS.Concepts/IDownloadEnabled.cs
- Common/DTS.Common.DAS.Concepts/IArmable.cs
- Common/DTS.Common.DAS.Concepts/LinearizationFormula.cs
generated_at: "2026-04-16T11:28:27.362404+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c415f64680b9e4be"
---
# Documentation: DTS.Common.DAS.Concepts
## 1. Purpose
This module defines the core contracts, data structures, and enumerations for the Data Acquisition System (DAS). It provides an abstraction layer for hardware interaction, defining standard interfaces for device capabilities such as arming, triggering, calibration, real-time data streaming, and data downloading. It also includes logic for sensor linearization and event metadata management, serving as a shared vocabulary between hardware implementations (e.g., TSR, SLICE, HEADS) and higher-level application logic.
## 2. Public Interface
### Namespaces: `DTS.Common.DAS.Concepts` & `DTS.DAS.Concepts`
*Note: This module splits types across two namespaces. `DTS.DAS.Concepts` appears to be the primary namespace for interfaces, while `DTS.Common.DAS.Concepts` contains data structures and enums.*
#### Enumerations
* **`AvailableArmModes`**: Defines arm modes.
* `LowPower`
* `CircularBuffer`
* *Defined in both namespaces.*
* **`ArmStatus`**: Defines the state machine for device arming.
* `Disarming`, `Disarmed`, `Arming`, `Armed`, `Recording`
* *Defined in both namespaces.*
* **`DTS.DAS.Concepts.GPIOPin.Directions`**: Defines GPIO pin directions.
* `Output` (0x00), `Peripheral` (0x01), `Input` (0x02), `InputPulledUp` (0x03), `InputPulledDown` (0x04)
* **`DTS.Common.DAS.Concepts.Test.Module.Channel.Sensor.ShuntModeType`**: Defines shunt calibration modes.
* `Internal`, `External`, `Emulation`, `None`
#### Interfaces
* **`IArmable`** (`DTS.DAS.Concepts`)
* `void Arm()`: Initiates the arming sequence.
* `void Disarm()`: Initiates the disarming sequence.
* `ArmStatus ArmStatus { get; }`: Current status of the arm state machine.
* `AvailableArmModes ArmMode { get; }`: Current arm mode.
* **`ITriggerable`** (`DTS.DAS.Concepts`)
* `void Trigger()`: Triggers the object (e.g., starts recording).
* **`IDownloadEnabled`** (`DTS.DAS.Concepts`)
* `TsrEvent[] EventList { get; }`: List of events available for download.
* `double[][] GetEventData(TsrEvent Event, UInt64 FirstSample, UInt64 LastSample)`: Retrieves sample data for a specific event range.
* `bool DataHasBeenDownloaded { get; }`: Indicates if data has been downloaded.
* **`IDataCollectionEnabled`** (`DTS.DAS.Concepts`) : `IArmable`, `ITriggerable`, `IDownloadEnabled`
* `double[] AvailableSampleRates { get; }`
* `double SampleRate { get; set; }`
* **`ICalibratable`** (`DTS.DAS.Concepts`)
* Properties: `SerialNumber`, `Sensitivity`, `BatteryVolts`, `VddVolts`, `SignalConditioningVolts`.
* **`IGpioEnabled`** (`DTS.DAS.Concepts`)
* `void SetGpio(uint Port, uint Pin, GPIOPin.Directions Direction, bool State)`
* `bool GetGpio(uint Port, uint Pin)`
* **`IRealtimeable`** (`DTS.DAS.Concepts`)
* `void StartRealtime(double sampleRate)`
* `void StopRealtime()`
* `RealtimeSample[] GetRealtimeSamples()`
* **`ILargeDataAware`** (`DTS.DAS.Concepts.DAS.Channel`)
* `bool IsDataArraySized { get; }`: Indicates if data fits safely in an array for slice applications.
#### Classes
* **`TsrEvent`** (`DTS.Common.DAS.Concepts` & `DTS.DAS.Concepts`) : `Exceptional`, `ICloneable`
* Abstract base class for event metadata.
* Properties: `EventId` (UInt64, 1-based), `TimeStamp` (DateTime), `SerialNumber`, `AlternateSerialNumber`, `DurationSeconds`, `MaxSampleRate`, `TemperatureC`, `PreTriggerSeconds`.
* `abstract object Clone()`: Creates a shallow copy.
* **`RealtimeSample`** (`DTS.DAS.Concepts`)
* `double[] DataEU`: Data indexed by channel.
* `UInt64 SampleNumber`
* **`LinearizationFormula`** (`DTS.Common.DAS.Concepts`)
* Handles conversion of raw voltage to Engineering Units (EU).
* **Properties**: `NonLinearStyle`, `PolynomialSensitivity`, `LinearizationExponent`, `MMPerV`, `MVAt0MM`, `Slope`, `Intercept`, `CalibrationFactor`, `ZeroPositionIntercept`, `UsemVOverVForPolys`, `PolynomialCoeff

View File

@@ -0,0 +1,311 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.IIsoCodeAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.ISerialNumberAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.IEngineeringUnitAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DecimationMethod.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.IInversionAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DTS.DAS.Concepts.IVoltageInsertAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.ILevelTriggerable.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.Data.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.DAS.Concepts.IShuntAware.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Channel.IDecimatable.cs
- Common/DTS.Common.DAS.Concepts/DAS/DAS.Id.cs
generated_at: "2026-04-16T11:38:29.974640+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f40aa120b967ad3e"
---
# DAS Concepts Module Documentation
## 1. Purpose
This module defines the core domain abstractions for a Data Acquisition System (DAS). It provides the foundational type hierarchy for representing DAS channels, their data containers, and various optional capabilities (metadata, calibration, triggering, decimation) that can be attached to channels via interfaces. The module serves as the conceptual model layer, establishing contracts and base types that concrete DAS implementations would extend.
---
## 2. Public Interface
### Classes
#### `Channel<DataType>` (Abstract)
**Namespace:** `DTS.DAS.Concepts.DAS`
**File:** `DAS.Channel.cs`
```csharp
public abstract class Channel<DataType> : Exceptional
```
- Abstract generic base class representing a DAS channel.
- Generic type parameter `DataType` defines the data type contained by channels of this DAS.
- Extends `Exceptional` from `DTS.Utilities`.
---
#### `Data<DatumType>` (Abstract)
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.Data.cs`
```csharp
public abstract class Data<DatumType> : ExceptionalList<DatumType>
```
- Abstract generic base class representing a list of channel data.
- Extends `ExceptionalList<DatumType>` from `DTS.Utilities`.
- **Constructors:**
- `protected Data()` — Default constructor.
- `protected Data(int capacity)` — Initializes with specified capacity.
- `protected Data(IEnumerable<DatumType> collection)` — Initializes from an existing collection.
---
#### `Id` (Sealed)
**Namespace:** `DTS.Common.DAS.Concepts.DAS`
**File:** `DAS.Id.cs`
```csharp
public sealed class Id : Exceptional, IComparable<Id>, IEquatable<Id>
```
- Represents a DAS identifier, encapsulating a string value.
- **Constructor:** `public Id(string value)`
- **Properties/Methods:**
- `public static implicit operator string(Id id)` — Implicit conversion to string.
- `public static implicit operator Id(string id)` — Implicit conversion from string.
- `public override bool Equals(object obj)` — Equality check; compares strings ordinally case-insensitive.
- `public bool Equals(Id that)` — Typed equality check.
- `public int CompareTo(Id that)` — IComparable implementation.
- `public override string ToString()` — Returns the underlying string value.
- `public override int GetHashCode()` — Returns hash of the string value.
- **Operators:** `==`, `!=`, `<`, `>`, `<=`, `>=` — All use case-insensitive string comparison.
---
### Interfaces
#### `IIsoCodeAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.IIsoCodeAware.cs`
```csharp
public interface IIsoCodeAware
{
string IsoCode { get; set; }
}
```
- Defines ISO code awareness with a string property.
---
#### `ISerialNumberAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.ISerialNumberAware.cs`
```csharp
public interface ISerialNumberAware
{
string SerialNumber { get; set; }
}
```
- Defines serial number awareness with a string property.
---
#### `IEngineeringUnitAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.IEngineeringUnitAware.cs`
```csharp
public interface IEngineeringUnitAware
{
string EngineeringUnits { get; set; }
}
```
- Defines engineering unit awareness with a string property.
---
#### `IInversionAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.IInversionAware.cs`
```csharp
public interface IInversionAware
{
bool IsInverted { get; set; }
}
```
- Defines inversion state awareness with a boolean property.
---
#### `ILinearized`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.IInversionAware.cs`
```csharp
public interface ILinearized
{
LinearizationFormula LinearizationFormula { get; set; }
}
```
- Defines linearization formula awareness. (Note: `LinearizationFormula` type is not defined in provided sources.)
---
#### `IVoltageInsertionAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DTS.DAS.Concepts.IVoltageInsertAware.cs`
```csharp
public interface IVoltageInsertionAware
{
double ExpectedGain { get; set; }
double MeasuredGain { get; set; }
}
```
- Defines shunt-check/voltage insertion awareness with gain properties.
---
#### `ILevelTriggerable`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.ILevelTriggerable.cs`
```csharp
public interface ILevelTriggerable
{
double? TriggerBelowThresholdEu { get; set; } // Set to null to deactivate
double? TriggerAboveThresholdEu { get; set; } // Set to null to deactivate
LevelTriggerTypes LevelTriggerType { get; set; }
}
```
- Defines level trigger capability with nullable threshold properties.
---
#### `IShuntAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.DAS.Concepts.IShuntAware.cs`
```csharp
public interface IShuntAware
{
double MeasuredShuntDeflectionMv { get; set; }
double TargetShuntDeflectionMv { get; set; }
}
```
- Defines shunt-check awareness with deflection values in millivolts.
---
#### `ICalSignalAware`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.DAS.Concepts.IShuntAware.cs`
```csharp
public interface ICalSignalAware
{
double MeasuredCalSignalMv { get; set; }
double TargetCalSignalMv { get; set; }
}
```
- Defines cal-signal awareness with values in millivolts.
---
#### `IDecimatable<out T>`
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.IDecimatable.cs`
```csharp
public interface IDecimatable<out T>
{
uint PointsPerPoint { get; set; }
DecimationMethod DecimationType { get; set; }
T[] ToDecimatedArray();
T this[long i] { get; } // Returns decimated value at index
}
```
- Defines decimation capability for DAS channels.
- The indexer returns values from the decimated set based on `PointsPerPoint` and `DecimationType`.
---
### Enumerations
#### `DecimationMethod`
**Namespace:** `DTS.DAS.Concepts.DAS` (in `DecimationMethod.cs`)
**Namespace:** `DTS.DAS.Concepts.DAS.Channel` (in `DAS.Channel.IDecimatable.cs`)
```csharp
public enum DecimationMethod
{
Point, // Use PointsPerPoint-th point as representative
Average, // Use average of PointsPerPoint values
PeakMagnitude // Use peak magnitude of PointsPerPoint values
}
```
- **Note:** This enum is defined in two files with different namespaces. See Gotchas.
---
#### `LevelTriggerTypes` (Flags)
**Namespace:** `DTS.DAS.Concepts.DAS.Channel`
**File:** `DAS.Channel.ILevelTriggerable.cs`
```csharp
[Flags]
public enum LevelTriggerTypes
{
NONE = 0x00,
OutsideWindow = 0x01,
InsideWindow = 0x02,
LessThan = 0x04,
GreaterThan = 0x08
}
```
- Bitwise combinable flags for level trigger types.
---
## 3. Invariants
1. **`Id` immutability:** The `value` field in `Id` is `readonly`; once constructed, the underlying string cannot be changed.
2. **Case-insensitive comparison:** All `Id` equality and comparison operations use `StringComparison.OrdinalIgnoreCase`.
3. **Null handling in `Id`:** The `Id` class handles null values gracefully in `GetHashCode()` (returns 0) and comparison operators.
4. **Abstract instantiation prevention:** Both `Channel<DataType>` and `Data<DatumType>` are abstract and cannot be instantiated directly.
5. **Decimation indexer contract:** Implementing `IDecimatable<T>` implies the indexer returns decimated values, not raw values.
6. **Trigger deactivation:** Setting `TriggerBelowThresholdEu` or `TriggerAboveThresholdEu` to `null` deactivates that trigger threshold.
---
## 4. Dependencies
### This Module Depends On:
| Dependency | Usage |
|------------|-------|
| `DTS.Utilities.Exceptional` | Base class for `Channel<DataType>` and `Id` |
| `DTS.Utilities.ExceptionalList<T>` | Base class for `Data<DatumType>` |
| `DTS.Common.Utilities` | Referenced in `DAS.Id.cs` (specific type usage unclear from source) |
| `System.Collections.Generic.IEnumerable<T>` | Used in `Data<DatumType>` constructor |
| `System.IComparable<T>` | Implemented by `Id` |
| `System.IEquatable<T>` | Implemented by `Id` |
| `System.FlagsAttribute` | Applied to `LevelTriggerTypes` |
### What Depends On This Module:
*Cannot be determined from the provided source files alone.*
---
## 5. Gotchas
1. **Duplicate `DecimationMethod` enum definition:** This enum is defined in two separate files:
- `DecimationMethod.cs` in namespace `DTS.Common.DAS.Concepts.DAS`
- `DAS.Channel.IDecimatable.cs` in namespace `DTS.DAS.Concepts.DAS.Channel`
This may cause ambiguity or require explicit namespace qualification.
2. **Namespace inconsistency across files:**
- `DAS.Channel.cs` uses `DTS.DAS.Concepts.DAS`
- `DAS.Id.cs` and `DecimationMethod.cs` use `DTS.Common.DAS.Concepts.DAS`
- Interface files use `DTS.DAS.Concepts.DAS.Channel`
This suggests possible refactoring history or assembly boundary issues.
3. **`ILinearized` placement:** The `ILinearized` interface is defined in `DAS.Channel.IInversionAware.cs` rather than its own file, breaking the one-type-per-file pattern used elsewhere. The referenced `LinearizationFormula` type is not defined in any provided source.
4. **Developer comments questioning design:** The `Id` class contains comments: *"DTM - why does this class exist? it's only encapsulating a string"* and *"why does this class even exist?"* — indicating possible tech debt or design uncertainty.
5. **XML comment mismatch in `IVoltageInsertionAware`:** The interface summary mentions "shunt-check awareness" but the properties are named `ExpectedGain` and `MeasuredGain`, which may be confusing.
6. **File naming inconsistency:** `DTS.DAS.Concepts.IVoltageInsertAware.cs` uses a different naming pattern than other interface files (missing the `DAS.Channel.` prefix and has a typo: "Insert" vs "Insertion" in the interface name).

View File

@@ -0,0 +1,109 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/DAS/Channel/LevelTriggerTypes.cs
- Common/DTS.Common.DAS.Concepts/DAS/Channel/Channel.cs
- Common/DTS.Common.DAS.Concepts/DAS/Channel/TimestampPartTypes.cs
- Common/DTS.Common.DAS.Concepts/DAS/Channel/Data.cs
generated_at: "2026-04-16T11:40:17.653590+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "0f3b00d01b342d9f"
---
# Documentation: DTS.Common.DAS.Concepts.DAS.Channel
## 1. Purpose
This module provides core domain abstractions for a Data Acquisition System (DAS). It defines the foundational types for representing DAS channels, their data payloads, and associated metadata enums for trigger conditions and timestamp parsing. The module serves as the conceptual layer for the "Slice control app's internal abstract representation" of DAS hardware channels, enabling type-safe channel definitions via generics and supporting bitwise flag operations for trigger and timestamp configurations.
---
## 2. Public Interface
### `Channel<TDataType>` (abstract class)
**Namespace:** `DTS.Common.DAS.Concepts.DAS`
**Signature:** `public abstract class Channel<TDataType> : Exceptional`
Abstract base class representing a DAS channel. Generic parameter `TDataType` defines the data type contained by channels of this DAS. Inherits from `Exceptional` (from `DTS.Common.Utilities`). No public members are defined in this source file.
---
### `Data<TDatumType>` (abstract class)
**Namespace:** `DTS.Common.DAS.Concepts.DAS.Channel`
**Signature:** `public abstract class Data<TDatumType> : ExceptionalList<TDatumType>`
Abstract base class representing a list of channel data. Inherits from `ExceptionalList<TDatumType>` (from `DTS.Common.Utilities`).
**Constructors:**
| Signature | Description |
|-----------|-------------|
| `protected Data()` | Default constructor. |
| `protected Data(int capacity)` | Initializes with specified initial capacity. |
| `protected Data(IEnumerable<TDatumType> collection)` | Initializes with elements copied from the provided collection. |
---
### `LevelTriggerTypes` (flags enum)
**Namespace:** `DTS.Common.DAS.Concepts.DAS.Channel`
**Signature:** `[Flags] public enum LevelTriggerTypes`
Bitwise flags enum defining trigger conditions for level monitoring.
| Member | Value | Hex |
|--------|-------|-----|
| `NONE` | 0 | `0x00` |
| `OutsideWindow` | 1 | `0x01` |
| `InsideWindow` | 2 | `0x02` |
| `LessThan` | 4 | `0x04` |
| `GreaterThan` | 8 | `0x08` |
---
### `TimestampPartTypes` (flags enum)
**Namespace:** `DTS.Common.DAS.Concepts.DAS.Channel`
**Signature:** `[Flags] [TypeConverter(typeof(EnumDescriptionTypeConverter))] public enum TimestampPartTypes`
Bitwise flags enum defining components of a timestamp structure. Decorated with `EnumDescriptionTypeConverter` for UI/data-binding scenarios.
| Member | Value | Description Attribute |
|--------|-------|----------------------|
| `Marker` | `1 << 0` (1) | "Marker" |
| `Seconds_High` | `1 << 1` (2) | "Seconds" |
| `Seconds_Low` | `1 << 2` (4) | "Seconds" |
| `Nanoseconds_High` | `1 << 3` (8) | "Nanoseconds" |
| `Nanoseconds_Low` | `1 << 4` (16) | "Nanoseconds" |
| `Reserved` | `1 << 5` (32) | "Reserved" |
---
## 3. Invariants
- **`LevelTriggerTypes`** is a flags enum; values are designed to be combined via bitwise OR operations. The `NONE` member has value `0x00` and represents the absence of any trigger condition.
- **`TimestampPartTypes`** is a flags enum using bit-shift notation (`1 << n`); each value occupies a distinct bit position enabling arbitrary combinations.
- **`Channel<TDataType>`** and **`Data<TDatumType>`** are both abstract classes; they cannot be instantiated directly and must be subclassed.
- **`Data<TDatumType>`** constructors are `protected`, restricting instantiation to derived classes.
- The `OutsideWindow` and `InsideWindow` flags in `LevelTriggerTypes` are mutually exclusive conceptually (values `0x01` and `0x02`), but this is not enforced at the type level.
- Similarly, `LessThan` and `GreaterThan` in `LevelTriggerTypes` are conceptually mutually exclusive but can technically be combined.
---
## 4. Dependencies
### This module depends on:
- **`DTS.Common.Utilities`** — Provides base classes `Exceptional` and `ExceptionalList<T>` used by `Channel<TDataType>` and `Data<TDatumType>` respectively.
- **`DTS.Common.Converters`** — Provides `EnumDescriptionTypeConverter` used by `TimestampPartTypes`.
- **`System`** — For `FlagsAttribute`.
- **`System.Collections.Generic`** — For `IEnumerable<T>` used in `Data<TDatumType>` constructor.
- **`System.ComponentModel`** — For `TypeConverterAttribute` used by `TimestampPartTypes`.
### What depends on this module:
- Unknown from source alone. The abstract nature of `Channel<TDataType>` and `Data<TDatumType>` indicates they are intended to be subclassed by other modules in the DAS system.
---
## 5. Gotchas
- **`TimestampPartTypes` has duplicate Description attributes:** Both `Seconds_High` and `Seconds_Low` have the description "Seconds", and both `Nanoseconds_High` and `Nanoseconds_Low` have the description "Nanoseconds". When displayed via `EnumDescriptionTypeConverter`, these will appear identically, potentially causing UI confusion.
- **`LevelTriggerTypes.NONE` vs. no value set:** The `NONE` member is explicitly defined as `0x00`. Code checking for "no triggers" should compare against `NONE` or `0` consistently.
- **Abstract classes with no visible members:** Both `Channel<TDataType>` and `Data<TDatumType>` appear to be empty shells in this source, suggesting their behavior is defined entirely in derived classes or partial definitions not shown here.
- **Bitwise flag combinations:** The flags design allows semantically invalid combinations (e.g., `OutsideWindow | InsideWindow` or `LessThan | GreaterThan`). Validation logic, if any, is not present in these source files.

View File

@@ -0,0 +1,184 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Interfaces/ITriggerable.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/IDataCollectionEnabled.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/ICalibratable.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/ILargeDataAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/IRealtimeable.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/IGpioEnabled.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/IDownloadEnabled.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/IArmable.cs
generated_at: "2026-04-16T11:39:26.463455+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "097989360eebf93b"
---
# Documentation: DTS.Common.DAS.Concepts Interfaces
## 1. Purpose
This module defines a set of interfaces that describe the core capabilities of Data Acquisition System (DAS) hardware devices. It provides an abstraction layer for common operations such as arming, triggering, calibration, real-time data capture, GPIO control, and data download. These interfaces enable polymorphic treatment of different hardware models (TSR, HEADS, NASCAR variants) while exposing consistent behavioral contracts.
---
## 2. Public Interface
### Interfaces
#### `ITriggerable`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `Trigger` | `void Trigger()` | Triggers the object to begin data capture or perform its primary action. |
---
#### `IArmable`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `Arm` | `void Arm()` | Arms the device for data capture. |
| `Disarm` | `void Disarm()` | Disarms the device. |
| `ArmStatus` | `ArmStatus ArmStatus { get; }` | Returns the current arming status. Type `ArmStatus` is not defined in these source files. |
| `ArmMode` | `AvailableArmModes ArmMode { get; }` | Returns the available/configured arm mode. Type `AvailableArmModes` is not defined in these source files. |
---
#### `IDownloadEnabled`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `EventList` | `TsrEvent[] EventList { get; }` | Returns a list of `TsrEvent` objects available for download. Type `TsrEvent` is not defined in these source files. |
| `GetEventData` | `double[][] GetEventData(TsrEvent Event, ulong FirstSample, ulong LastSample)` | Retrieves event data for the specified sample range. Returns an array of data arrays per channel. |
| `DataHasBeenDownloaded` | `bool DataHasBeenDownloaded { get; }` | Indicates whether data has been downloaded from this entity. |
---
#### `IDataCollectionEnabled`
**Namespace:** `DTS.Common.DAS.Concepts`
**Inherits:** `IArmable`, `ITriggerable`, `IDownloadEnabled`
| Member | Signature | Description |
|--------|-----------|-------------|
| `AvailableSampleRates` | `double[] AvailableSampleRates { get; }` | Returns the array of supported sample rates. |
| `SampleRate` | `double SampleRate { get; set; }` | Gets or sets the current sample rate. |
---
#### `ICalibratable`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `SerialNumber` | `string SerialNumber { get; set; }` | Device serial number for calibration tracking. |
| `Sensitivity` | `double Sensitivity { get; set; }` | Calibration sensitivity value. |
| `BatteryVolts` | `double BatteryVolts { get; set; }` | Battery voltage reading. |
| `VddVolts` | `double VddVolts { get; set; }` | Vdd supply voltage reading. |
| `SignalConditioningVolts` | `double SignalConditioningVolts { get; set; }` | Signal conditioning voltage reading. |
---
#### `IRealtimeable`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `StartRealtime` | `void StartRealtime(double sampleRate)` | Begins real-time data capture at the specified sample rate. |
| `StopRealtime` | `void StopRealtime()` | Stops real-time data capture. |
| `GetRealtimeSamples` | `RealtimeSample[] GetRealtimeSamples()` | Retrieves accumulated real-time samples. |
---
#### `ILargeDataAware`
**Namespace:** `DTS.Common.DAS.Concepts.DAS.Channel`
| Member | Signature | Description |
|--------|-----------|-------------|
| `IsDataArraySized` | `bool IsDataArraySized { get; }` | Indicates whether the data set is small enough to safely fit in an array for slice operations (filtering, viewer display, etc.). |
---
#### `IGpioEnabled`
**Namespace:** `DTS.Common.DAS.Concepts`
| Member | Signature | Description |
|--------|-----------|-------------|
| `SetGpio` | `void SetGpio(uint Port, uint Pin, Directions Direction, bool State)` | Configures a GPIO pin with specified port, pin number, direction, and state. |
| `GetGpio` | `bool GetGpio(uint Port, uint Pin)` | Reads the state of a GPIO pin at the specified port and pin. |
---
### Classes
#### `RealtimeSample`
**Namespace:** `DTS.Common.DAS.Concepts`
| Field | Type | Description |
|-------|------|-------------|
| `DataEU` | `double[]` | Engineering unit data indexed by channel. **Note:** This is a public field, not a property. |
| `SampleNumber` | `ulong` | The sample number identifier. **Note:** This is a public field, not a property. |
---
### Enums
#### `Directions`
**Namespace:** `DTS.Common.Common.DAS.Concepts.GPIOPin`
| Value | Hex | Description |
|-------|-----|-------------|
| `Output` | `0x00` | GPIO configured as output. |
| `Peripheral` | `0x01` | GPIO configured for peripheral function. |
| `Input` | `0x02` | GPIO configured as input (floating). |
| `InputPulledUp` | `0x03` | GPIO configured as input with pull-up resistor. |
| `InputPulledDown` | `0x04` | GPIO configured as input with pull-down resistor. |
---
## 3. Invariants
- **`IDataCollectionEnabled`** requires implementation of `IArmable`, `ITriggerable`, and `IDownloadEnabled` simultaneously—a data collection device must support all three capabilities.
- **`IGpioEnabled.SetGpio`**: When `Direction` is set to an input mode (`Input`, `InputPulledUp`, `InputPulledDown`), the `State` parameter is effectively a no-op (per source comments).
- **`IDownloadEnabled.GetEventData`**: The sample range is inclusive, specified by `FirstSample` and `LastSample` indices.
- **`RealtimeSample.DataEU`**: Array is indexed by channel number.
- **`ILargeDataAware.IsDataArraySized`**: Must accurately reflect whether data can safely fit in memory for processing operations.
---
## 4. Dependencies
### This module depends on:
- **`System`** namespace (used in `IRealtimeable.cs` and `IDownloadEnabled.cs` for `UInt64` and other base types)
- **`DTS.Common.Common.DAS.Concepts.GPIOPin`** namespace (defines `Directions` enum used by `IGpioEnabled`)
### External types referenced but not defined in these sources:
- `ArmStatus` — referenced by `IArmable.ArmStatus`
- `AvailableArmModes` — referenced by `IArmable.ArmMode`
- `TsrEvent` — referenced by `IDownloadEnabled.EventList` and `GetEventData` parameter
### What depends on this module:
- Cannot be determined from source alone; these are interface definitions intended to be implemented by concrete hardware abstraction classes.
---
## 5. Gotchas
1. **Missing Type Definitions**: The types `ArmStatus`, `AvailableArmModes`, and `TsrEvent` are referenced but not defined in the provided source files. Their definitions must exist elsewhere in the codebase.
2. **Namespace Inconsistency**: The `Directions` enum is defined in `DTS.Common.Common.DAS.Concepts.GPIOPin` (note the double "Common"), while the interfaces are in `DTS.Common.DAS.Concepts`. This appears to be a naming inconsistency.
3. **Public Fields in `RealtimeSample`**: The `DataEU` and `SampleNumber` members are public fields, not properties—unlike the rest of the API which uses properties consistently.
4. **`IGpioEnabled` TODO**: Source contains a TODO comment: *"Well have to bring these in as soon as we figure out where to get that enum from."* suggesting the `Directions` enum location was unsettled at time of writing.
5. **`IDownloadEnabled` Commented Members**: The interface contains commented-out properties (`MaximumStoredEventSizeSeconds`, `DownloadIncrementSamples`, `ChannelDescription`, `TimeOffsetMilliseconds`) with a TODO questioning their universal applicability.
6. **Calibration Interface Design Uncertainty**: Source comments indicate the `ICalibratable` interface design is unresolved: *"The question of a good interface for Calibration is still unanswered... I have a feeling that this is a place where we'll be hooking in model checks."*
7. **Arm State Granularity**: Comments suggest the arm state model may be incomplete: *"We need to think about the arm states a bit more. There have been a couple of cases where having a Disarming state, in addition to Disarmed, has been nice."*
8. **Multi-Rate Data Handling**: Extensive comments in `IArmable.cs` describe complex multi-sample-rate scenarios (e.g., BlastTestTSR with 4 channels at 40ksps and 3 channels at 1ksps) where interpolation is performed at the lower level, potentially creating edge cases for download chunk sizing.

View File

@@ -0,0 +1,174 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/ITimestampAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/ILinearized.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IIsoCodeAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/ISerialNumberAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IInversionAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IEngineeringUnitAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/ICalSignalAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IVoltageInsertAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IShuntAware.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/ILevelTriggerable.cs
- Common/DTS.Common.DAS.Concepts/Interfaces/DAS/Channel/IDecimatable.cs
generated_at: "2026-04-16T11:40:36.287986+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b4d2ceb184c9ded4"
---
# Documentation: DAS Channel Concept Interfaces
## 1. Purpose
This module defines a set of granular interfaces representing behavioral "concepts" for Data Acquisition System (DAS) channels within the `DTS.Common.DAS.Concepts.DAS.Channel` namespace. These interfaces follow a mixin-style composition pattern, allowing channel implementations to adopt specific capabilities—such as timestamp handling, linearization, calibration awareness, and decimation—by implementing the relevant interfaces. This design enables flexible channel configuration without requiring deep inheritance hierarchies.
---
## 2. Public Interface
### `ITimestampAware`
Defines timestamp configuration capability for a channel.
| Member | Type | Description |
|--------|------|-------------|
| `TimestampPartType` | `TimestampPartTypes` (get/set) | Gets or sets the timestamp part type configuration. |
---
### `ILinearized`
Defines linearization capability for sensor data.
| Member | Type | Description |
|--------|------|-------------|
| `LinearizationFormula` | `DTS.Common.Classes.Sensors.LinearizationFormula` (get/set) | Gets or sets the linearization formula to be applied. |
---
### `IIsoCodeAware`
Defines ISO code awareness for an object.
| Member | Type | Description |
|--------|------|-------------|
| `IsoCode` | `string` (get/set) | Gets or sets the ISO code identifier. |
---
### `ISerialNumberAware`
Defines serial number awareness for an object.
| Member | Type | Description |
|--------|------|-------------|
| `SerialNumber` | `string` (get/set) | Gets or sets the serial number identifier. |
---
### `IInversionAware`
Defines inversion state awareness for a channel.
| Member | Type | Description |
|--------|------|-------------|
| `IsInverted` | `bool` (get/set) | Gets or sets the inversion state. |
---
### `IEngineeringUnitAware`
Defines engineering unit awareness for a channel.
| Member | Type | Description |
|--------|------|-------------|
| `EngineeringUnits` | `string` (get/set) | Gets or sets the engineering unit description. |
---
### `ICalSignalAware`
Defines calibration signal awareness for shunt calibration operations.
| Member | Type | Description |
|--------|------|-------------|
| `MeasuredCalSignalMv` | `double` (get/set) | Gets or sets the measured shunt deflection value in millivolts. |
| `TargetCalSignalMv` | `double` (get/set) | Gets or sets the target shunt deflection value in millivolts. |
---
### `IVoltageInsertionAware`
Defines voltage insertion/gain awareness for calibration operations.
| Member | Type | Description |
|--------|------|-------------|
| `ExpectedGain` | `double` (get/set) | Gets or sets the expected gain value. |
| `MeasuredGain` | `double` (get/set) | Gets or sets the measured gain value. |
---
### `IShuntAware`
Defines shunt-check awareness for calibration verification.
| Member | Type | Description |
|--------|------|-------------|
| `MeasuredShuntDeflectionMv` | `double` (get/set) | Gets or sets the measured shunt deflection value in millivolts. |
| `TargetShuntDeflectionMv` | `double` (get/set) | Gets or sets the target shunt deflection value in millivolts. |
---
### `ILevelTriggerable`
Defines level trigger capability for a channel.
| Member | Type | Description |
|--------|------|-------------|
| `SampleAverageADC` | `double?` (get/set) | Cached ADC value for use when calculating already level-triggered state (created for Flash Clear feature). |
| `TriggerBelowThresholdEu` | `double?` (get/set) | Gets or sets the "trigger below" threshold in engineering units. Set to `null` to deactivate. |
| `TriggerAboveThresholdEu` | `double?` (get/set) | Gets or sets the "trigger above" threshold in engineering units. Set to `null` to deactivate. |
| `LevelTriggerType` | `LevelTriggerTypes` (get/set) | Gets or sets the level trigger type configuration. |
---
### `IDecimatable<T>`
Defines decimation capability for channel data. Generic interface with covariant type parameter `T`.
| Member | Type | Description |
|--------|------|-------------|
| `PointsPerPoint` | `uint` (get/set) | Gets or sets the number of points to be compressed into a single index point. |
| `DecimationType` | `DecimationMethod` (get/set) | Gets or sets the decimation method to be applied. |
| `ToDecimatedArray()` | `T[]` | Generates a decimated array using the configured `DecimationMethod`. |
| `this[long i]` | `T` (get-only indexer) | Gets the value at the specified post-decimation index. |
---
## 3. Invariants
- **Nullable Thresholds**: For `ILevelTriggerable`, setting `TriggerBelowThresholdEu` or `TriggerAboveThresholdEu` to `null` explicitly deactivates that trigger threshold. Implementations must treat `null` as "inactive" rather than "uninitialized."
- **Indexer Behavior**: For `IDecimatable<T>`, the indexer `this[long i]` must return values from the **decimated** dataset, not the raw data. The index `i` refers to the post-decimation index.
- **Covariance**: `IDecimatable<out T>` uses covariant generic parameter, meaning `IDecimatable<DerivedType>` can be assigned to `IDecimatable<BaseType>` if `DerivedType` inherits from `BaseType`.
- **Decimation Configuration**: `PointsPerPoint` is a `uint`, implying it must be at least 1. Behavior when set to 0 is undefined from the source alone.
---
## 4. Dependencies
### External Types Referenced (not defined in provided source):
- `DTS.Common.Classes.Sensors.LinearizationFormula` — Used by `ILinearized`
- `TimestampPartTypes` — Used by `ITimestampAware`
- `DecimationMethod` — Used by `IDecimatable<T>`
- `LevelTriggerTypes` — Used by `ILevelTriggerable`
### Namespace:
All interfaces reside in `DTS.Common.DAS.Concepts.DAS.Channel`.
### Consumers:
Unknown from source alone. These are interface definitions intended to be implemented by concrete channel classes elsewhere in the codebase.
---
## 5. Gotchas
1. **Historical Comment in `ILevelTriggerable`**: The `SampleAverageADC` property includes a comment referencing "14042 Flash Clear turns off excitation for s6." This suggests the property was added for a specific workaround or feature related to hardware excitation control, and may have specialized usage not obvious from the interface alone.
2. **Indexer Semantics in `IDecimatable<T>`**: The indexer returns post-decimation values. Developers might incorrectly assume it indexes raw data. The remarks explicitly call this out, but it remains a potential source of confusion.
3. **Naming Inconsistency in `IVoltageInsertionAware`**: The filename is `IVoltageInsertAware.cs` (note: "Insert" without "ion"), but the XML summary refers to "shunt-check awareness" (copied from `IShuntAware`), while the interface name and properties relate to gain values. The summary documentation appears to be copy-paste residue and does not accurately describe the interface's purpose.
4. **Missing XML Comments**: `ITimestampAware` and `ILinearized` lack XML documentation comments present on other interfaces in this set.

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:38:34.097314+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b609c89cbf8012d6"
---
# Documentation: DTS.Common.DAS.Concepts Assembly Metadata
## 1. Purpose
This file provides assembly-level metadata configuration for the `DTS.DAS.Concepts` library. It exists to embed version information, copyright details, and COM visibility settings into the compiled assembly during the build process. It does not contain executable application logic.
## 2. Public Interface
This file does not expose any public classes, methods, or functions. It applies the following assembly-level attributes:
* **`AssemblyTitle`**: Set to `"DTS.DAS.Concepts"`.
* **`AssemblyDescription`**: Empty.
* **`AssemblyConfiguration`**: Empty.
* **`AssemblyCompany`**: Set to `"DTS"`.
* **`AssemblyProduct`**: Set to `"DTS.DAS.Concepts"`.
* **`AssemblyCopyright`**: Set to `"Copyright © DTS 2008"`.
* **`AssemblyTrademark`**: Empty.
* **`AssemblyCulture`**: Empty.
* **`ComVisible`**: Set to `false`.
* **`Guid`**: Set to `"9b6f7402-27d3-4cc9-9ff3-3cfe16e0b429"`.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
## 3. Invariants
* **COM Visibility**: The assembly is explicitly marked with `ComVisible(false)`, meaning types within this assembly are not visible to COM components by default.
* **Versioning**: Both the assembly version and file version are pinned to the specific build string `"1.06.0081"`. Automatic versioning (e.g., using wildcards) is not utilized for the revision or build numbers.
## 4. Dependencies
* **Internal Dependencies**: This file depends on `System.Reflection` and `System.Runtime.InteropServices` namespaces to define the attributes.
* **External Dependencies**: None identified from this source alone. As an assembly info file, it is a leaf node in the dependency graph; other projects may depend on the compiled `DTS.DAS.Concepts` assembly, but this specific file does not depend on other internal modules.
## 5. Gotchas
* **Naming Discrepancy**: The `AssemblyTitle` is defined as `"DTS.DAS.Concepts"`, but the file path indicates the project folder is named `DTS.Common.DAS.Concepts`. This may cause confusion when referencing the assembly by name versus the project or namespace structure.
* **Manual Versioning**: The `AssemblyVersion` and `AssemblyFileVersion` are hardcoded strings (`"1.06.0081"`). Developers must manually update these values for new releases; they will not auto-increment.
* **Legacy Format**: This uses the older `AssemblyInfo.cs` mechanism for defining metadata. In newer SDK-style projects, this is often implicit or generated automatically, which could lead to conflicts if the project style is upgraded without removing this file.

View File

@@ -0,0 +1,159 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.Sensor.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.Sensor.Bridge.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.Sensor.SensorUnits.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.Sensor.ZeroMethod.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.RecordingMode.cs
- Common/DTS.Common.DAS.Concepts/Test/Test.Module.Channel.Sensor.ExcitationVoltage.cs
generated_at: "2026-04-16T11:38:00.583082+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f6582d95b5debe26"
---
# Documentation: DTS.DAS.Concepts.Test Module Hierarchy
## 1. Purpose
This module provides a hierarchical container structure for Data Acquisition System (DAS) test-related concepts, specifically defining configuration enums and types for hardware modules, channels, and sensors. It serves as a static type definitions library for sensor configurations (bridge types, coupling modes, excitation voltages, sensitivity units, zero methods) and recording modes. The architecture uses nested partial classes (`Test.Module.Channel.Sensor`) as organizational containers—none of which are instantiable—to group related enums and their associated helper methods within the `DTS.DAS.Concepts` namespace.
---
## 2. Public Interface
### Container Classes (Non-instantiable)
| Class | Location | Description |
|-------|----------|-------------|
| `Test` | `DTS.DAS.Concepts` | Outer partial class container |
| `Test.Module` | `DTS.DAS.Concepts` | Container for DTS generic module concepts; private constructor |
| `Test.Module.Channel` | `DTS.DAS.Concepts` | Container for DTS generic channel concepts; private constructor |
| `Test.Module.Channel.Sensor` | `DTS.DAS.Concepts` | Container for DTS generic sensor concepts; private constructor |
### Enums
#### `Test.Module.Channel.Sensor.CouplingModes`
IEPE coupling modes.
- `AC` — Description: "AC"
- `DC` — Description: "AC/DC"
#### `Test.Module.Channel.Sensor.BridgeType`
Sensor bridge configuration types. Values are bitwise flags.
- `IEPE` = `1 << 0` (1) — Sensor uses IEPE setup
- `QuarterBridge` = `1 << 1` (2) — Quarter bridge setup
- `HalfBridge` = `1 << 2` (4) — Half bridge setup
- `FullBridge` = `1 << 3` (8) — Full bridge setup
- `DigitalInput` = `1 << 4` (16)
- `SQUIB` = `1 << 5` (32)
- `TOMDigital` = `1 << 6` (64)
#### `Test.Module.Channel.Sensor.SensUnits`
Sensitivity unit types.
- `NONE` = 0 — No sensitivity units (Polynomial Sensor)
- `mV` = 1 — Sensitivity in mV with output at Capacity EU
- `mVperV` = 2 — Excitation proportional sensitivity in mV/V at Capacity EU
- `mVperVperEU` = 3 — Excitation proportional sensitivity in mV/V/EU
- `mVperEU` = 4 — Sensitivity in mV/EU
#### `Test.Module.Channel.Sensor.ZeroMethodType`
Zero calculation methods. **Explicit values are critical for legacy compatibility.**
- `AverageOverTime` = 0 — Calculate electrical zero using average over time
- `UsePreEventDiagnosticsZero` = 1 — Calculate zero using time in pre-event
- `None` = 2 — Calculate zero using injected value (Absolute Zero)
#### `Test.Module.Channel.Sensor.OriginalZeroMethodType`
Legacy version of zero method types (for compatibility, e.g., importing GM ISF).
- `AverageOverTime` — (implicit 0)
- `UsePreCalZero` — (implicit 1)
- `None` — (implicit 2)
#### `Test.Module.RecordingMode`
Recording mode options for modules.
- `InvalidArmMode` = 0 — Invalid mode
- `CircularBuffer` = 1 — Circular buffer mode (constant recording, trigger)
- `RecorderMode` = 2 — Recorder mode (start, trigger)
- `AutoCircularBufferMode` = 4 — Circular buffer with auto-rearm
- `AutoRecorderMode` = 5 — Recorder mode with auto-rearm
- `ImmediateMode` = `0x06`
- `HighPowerRecorderMode` = `0x07`
- `LowPowerRecorderMode` = `0x08`
- `ContinuousRecorderMode` = `0x09`
- `HybridRecorderMode` = `0x0A`
- `MultiHybridRecorderMode` = `0x0B`
#### `Test.Module.Channel.Sensor.ExcitationVoltageOption`
Excitation voltage options with associated magnitude attributes.
- `Undefined` = 1 — `[VoltageMagnitude(0.0)]`
- `Volt2` = 2 — `[VoltageMagnitude(2.0)]`
- `Volt2_5` = 4 — `[VoltageMagnitude(2.5)]`
- `Volt3` = 8 — `[VoltageMagnitude(3.0)]`
- `Volt5` = 16 — `[VoltageMagnitude(5.0)]`
- `Volt10` = 32 — `[VoltageMagnitude(10.0)]`
- `Volt1` = 64 — `[VoltageMagnitude(1.0)]`
### Static Methods
#### `Test.Module.GetRecordingModeFromString(string recordingMode) → RecordingMode`
Converts a string representation to its corresponding `RecordingMode` enum value. Throws `Exception` if parsing fails or input is invalid.
#### `Test.Module.Channel.Sensor.GetExcitationVoltageMagnitudeFromEnum(ExcitationVoltageOption target) → double`
Extracts the numeric voltage magnitude from an `ExcitationVoltageOption` enum value by decoding the `VoltageMagnitudeAttribute`. Throws `Exception` on failure.
#### `Test.Module.Channel.Sensor.GetExcitationVoltageEnumFromMagnitude(double magnitude) → ExcitationVoltageOption`
Converts a voltage magnitude to the corresponding `ExcitationVoltageOption` enum. Throws `NotSupportedException` if no matching enum exists.
### Nested Types
#### `Test.Module.Channel.Sensor.VoltageMagnitudeAttribute`
Custom attribute for associating a numeric voltage magnitude with enum fields.
- **Property**: `Value` (double) — Returns the voltage magnitude.
- **Constructor**: `VoltageMagnitudeAttribute(double value)`
#### `Test.Module.Channel.Sensor.VoltageMagnitudeAttributeCoder`
Inherits from `AttributeCoder<ExcitationVoltageOption, VoltageMagnitudeAttribute, double>`. Used to encode/decode voltage magnitudes to/from `ExcitationVoltageOption` enum values.
- **Constructor**: `VoltageMagnitudeAttributeCoder()` — Initializes with extractor `attribute => attribute.Value`.
---
## 3. Invariants
1. **Non-instantiability**: `Test`, `Test.Module`, `Test.Module.Channel`, and `Test.Module.Channel.Sensor` are container classes with private constructors and cannot be instantiated.
2. **BridgeType bitwise flags**: `BridgeType` enum values are designed as bitwise flags (powers of 2), allowing combination via bitwise OR operations.
3. **ExcitationVoltageOption enum values are NOT bitwise flags**: Despite using powers of 2, these values represent mutually exclusive voltage options; the numeric values appear to be legacy bit positions rather than combinable flags.
4. **ZeroMethodType value stability**: The explicit integer values (0, 1, 2) for `ZeroMethodType` must remain unchanged for legacy compatibility with GM ISF imports.
5. **RecordingMode value gaps**: `RecordingMode` enum has non-contiguous values (e.g., 3 is missing between 2 and 4); code should not assume sequential ordering.
---
## 4. Dependencies
### This module depends on:
- `System` — For `Exception`, `NotSupportedException`, `Attribute` base class, `Enum.Parse`
- `System.ComponentModel` — For `DescriptionAttribute` used on enum members
- `DTS.Utilities` — For `AttributeCoder<TEnum, TAttribute, TValue>` base class (used by `VoltageMagnitudeAttributeCoder`)
### What depends on this module:
- **Unclear from source alone** — The source files contain no references to external consumers. The comment referencing "GM ISF" suggests integration with General Motors Import/Export functionality, but this is not visible in the provided sources.
---
## 5. Gotchas
1. **Legacy ZeroMethodType enum values are critical**: The comment in `Test.Module.Channel.Sensor.ZeroMethod.cs` explicitly warns: *"Lots of legacy compatibility (e.g. importing GM ISF) depends on the order/value of this enum."* Modifying these values will break backward compatibility.
2. **Duplicate zero method enums exist**: Both `ZeroMethodType` and `OriginalZeroMethodType` exist with slightly different member names (`UsePreEventDiagnosticsZero` vs `UsePreCalZero`). The relationship between them and which to use for new code is unclear from source alone.
3. **ExcitationVoltageOption enum values are non-sequential and start at 1**: The values (1, 2, 4, 8, 16, 32, 64) appear to be legacy bit positions but are not combinable flags. Code should not cast arbitrary integers to this enum.
4. **RecordingMode documentation gaps**: Several enum members (`ImmediateMode`, `HighPowerRecorderMode`, `LowPowerRecorderMode`, `ContinuousRecorderMode`, `HybridRecorderMode`, `MultiHybridRecorderMode`) have XML comments containing only `"???"`, indicating incomplete documentation.
5. **File header comment mismatch**: `Test.Module.Channel.Sensor.SensorUnits.cs` has a file header comment referencing `"Test.Module.Channel.Sensor.ExcitationVoltage.cs"` — appears to be a copy-paste error.
6. **Sensor class visibility inconsistency**: In `Test.Module.Channel.Sensor.cs`, the `Sensor` class is declared as `sealed partial class Sensor` (no explicit accessibility, defaulting to `private`), whereas in `Test.Module.Channel.Sensor.Bridge.cs` it is `public partial class Sensor`. This may cause compilation issues or indicate partial class visibility conflicts.

View File

@@ -0,0 +1,278 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Test/Module/RecordingMode.cs
- Common/DTS.Common.DAS.Concepts/Test/Module/TiltAxes.cs
generated_at: "2026-04-16T11:39:41.280506+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "d40daed59089dfb4"
---
# Documentation: DTS.Common.DAS.Concepts.Test.Module
## 1. Purpose
This module provides utilities for handling tilt sensor data and recording mode configurations within the DTS data acquisition system. It contains classes and methods for converting raw ADC tilt sensor readings into engineering units (degrees), managing tilt axis configurations and polarities, and parsing string representations of enumeration values. The module serves as a bridge between hardware-level sensor data and application-level tilt calculations, supporting multiple axis orientations and calibration parameters.
---
## 2. Public Interface
### Classes
#### `Test.Module.TiltAxis`
A data container class representing a single tilt axis configuration.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `AxisNumber` | `int` | - | The axis identifier number |
| `CurrentTilt` | `double` | - | The current tilt value |
| `Label` | `string` | - | The axis label (e.g., "X", "Y", "Z") |
| `Inversion` | `int` | `1` | Polarity multiplier (-1 or 1) |
| `IsIgnored` | `bool` | `false` | Whether this axis is excluded from calculations |
| `MountedOffset` | `double` | `0.0` | Mount offset in degrees |
| `TargetOffset` | `double` | `0.0` | Target offset in degrees |
#### `Test.Module.TiltAxesHelper`
A helper class for managing tilt axis configurations parsed from firmware attributes.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `AxisConfigurations` | `Dictionary<int, TiltAxis>` | Empty dict with keys 0,1,2 | Collection of axis configurations |
| `AxisOne` | `TiltAxis` | - | Reference to the first active axis |
| `AxisTwo` | `TiltAxis` | - | Reference to the second active axis |
| `LevelTolerance` | `double` | `0.5` | Tolerance for level detection |
**Constructors:**
- `TiltAxesHelper()` - Default constructor initializing 3 axis configurations
- `TiltAxesHelper(string TiltAxes, double MountOffsetAxisOne, double MountOffsetAxisTwo, double TargetAxisOne, double TargetAxisTwo, double LevelTolerance, int AxisIgnored, bool UseForTiltCalculation)` - Constructs from firmware attributes
**Methods:**
- `string AxesToString()` - Returns a string representation of axis labels with polarity indicators (e.g., "IXPYP")
---
### Enumerations
#### `Test.Module.TiltAxesSimple`
Simplified tilt axis orderings (6 permutations).
| Value | Name |
|-------|------|
| 0 | `XYZ` |
| 1 | `XZY` |
| 2 | `YXZ` |
| 3 | `YZX` |
| 4 | `ZXY` |
| 5 | `ZYX` |
#### `Test.Module.TiltAxesPolarity`
Polarity combinations for three axes (8 combinations).
| Value | Name |
|-------|------|
| 0 | `PPP` |
| 1 | `PPN` |
| 2 | `PNP` |
| 3 | `PNN` |
| 4 | `NPP` |
| 5 | `NPN` |
| 6 | `NNP` |
| 7 | `NNN` |
#### `Test.Module.TiltSensorCalAttributes`
18 calibration attribute indices for tilt sensor calibration data.
| Value | Name |
|-------|------|
| 0 | `TILTSENSOR_CAL_1_GainAxis1` |
| 1 | `TILTSENSOR_CAL_2_ZeroAxis1` |
| 2 | `TILTSENSOR_CAL_3_ZeroDomAxis2PosAxis1` |
| 3 | `TILTSENSOR_CAL_4_ZeroDomAxis2NegAxis1` |
| ... | (continues through index 17) |
| 17 | `TILTSENSOR_CAL_18_ZeroDomAxis2NegAxis3` |
#### `Test.Module.AxisLabel`
| Value | Name |
|-------|------|
| 0 | `X` |
| 1 | `Y` |
| 2 | `Z` |
---
### Static Methods
#### Recording Mode Methods
```csharp
public static DFConstantsAndEnums.RecordingMode GetRecordingModeFromString(string recordingMode)
```
Converts a string representation to a `DFConstantsAndEnums.RecordingMode` enum value. Throws `Exception` with descriptive message if parsing fails.
---
#### Tilt Axes Parsing Methods
```csharp
public static TiltAxes GetTiltAxesFromString(string tiltAxes)
```
Converts a string representation to a `TiltAxes` enum value. Throws `Exception` with descriptive message if parsing fails.
```csharp
public static TiltAxesSimple SimplifyTiltAxes(TiltAxes axes)
```
Converts a `TiltAxes` enum to its simplified form by removing "I" (inversion) prefixes.
```csharp
public static int[] GetPolaritiesFromTiltAxes(TiltAxes ta)
```
Returns an array of polarity values (-1 or 1) for each axis based on the `TiltAxes` enum.
```csharp
public static bool[] GetBoolPolaritiesFromTiltAxes(TiltAxes tiltAxes)
```
Returns a boolean array indicating inversion state for each axis. `true` indicates inverted.
```csharp
public static AxisLabel[] GetAxisLabelFromTiltAxes(TiltAxes tiltAxes)
public static AxisLabel[] GetAxisLabelFromTiltAxes(string tiltAxes)
```
Extracts axis labels from a `TiltAxes` enum or string representation.
---
#### Tilt Calculation Methods
```csharp
public static double[] GetTiltDegreesEU(short[] tiltSensorADC, double[] tiltSensorCals)
```
Overload that uses default parameters: `TiltAxes.IXYZ`, ignored axis 3, and zero mount offsets.
```csharp
public static double[] GetTiltDegreesEU(short[] tiltSensorADC, double[] tiltSensorCals, TiltAxes axes, int ignoredAxis, float[] mountOffsetAxis)
```
Converts raw ADC tilt sensor readings to engineering units (degrees). Returns a `double[3]` containing X, Y, Z tilt values in degrees. The ignored axis value is set to `double.NaN`.
```csharp
public static double[] GetTiltZeroData(short[] tiltSensorADC, double[] tiltSensorCals, int dominantAxis)
```
Calculates zero offset data based on the dominant axis and its polarity.
```csharp
public static int GetDominantTiltAxis(short[] tiltSensorADC)
```
Returns the index of the axis with the largest absolute ADC value.
```csharp
public static double[] GetTiltGains(double[] tiltSensorCals)
```
Extracts gain values from calibration data. Returns `1.0` for any gain that is `0.0`.
---
#### Utility Methods
```csharp
public static string ConvertBoolToInvertString(bool isInverted)
```
Returns `"I"` if `isInverted` is true, otherwise empty string.
```csharp
public static string GetOrientationLabelFromAxisInfo(string[] axisLabels, bool[] invertAxis)
```
Builds an orientation label string from axis labels and inversion flags.
```csharp
public static TiltAxes GetTiltAxesFromAxisInfo(string[] axisLabels, bool[] invertAxis)
```
Constructs a `TiltAxes` enum from axis labels and inversion flags.
```csharp
public static float[] GetMountOffsetsOrTargetsFromAxisInfo(float[] perAxisValue, int axisToIgnore)
```
Extracts a 2-element array of values for the non-ignored axes (1-indexed: 1, 2, or 3).
---
## 3. Invariants
1. **Array Size Requirements:**
- `tiltSensorADC` must be a 3-element array (indices 0, 1, 2 correspond to axes)
- `tiltSensorCals` must be an 18-element array (indexed by `TiltSensorCalAttributes`)
- `mountOffsetAxis` must be a 2-element array
- `perAxisValue` in `GetMountOffsetsOrTargetsFromAxisInfo` must be a 3-element array
2. **Ignored Axis Values:**
- Valid values are 1, 2, or 3 (1-indexed)
- A value of 0 is silently converted to 3 in `GetTiltDegreesEU`
3. **Gain Default Behavior:**
- Any gain value of `0.0` is replaced with `1.0` in `GetTiltGains`
4. **Output Format:**
- `GetTiltDegreesEU` returns degrees rounded to 3 decimal places (via `SIGNIFICANT_DIGITS = 1000`)
- Ignored axis values are set to `double.NaN`
5. **TiltAxesHelper Dictionary Keys:**
- The default constructor initializes `AxisConfigurations` with keys 0, 1, 2 (not 1, 2, 3)
---
## 4. Dependencies
### External Dependencies (Imports)
- `DTS.Common.Enums.DASFactory` - Provides `DFConstantsAndEnums.RecordingMode` and `TiltAxes` enumerations
- `DTS.Common.Utilities` - Provides `DegreesFromADC.GetDegrees()` method
- `System` - Core .NET types
- `System.Collections.Generic` - `Dictionary<TKey, TValue>`, `List<T>`
- `System.ComponentModel` - Component model infrastructure
- `System.Linq` - LINQ extension methods (`Max()`, `Min()`, `IndexOf()`)
- `System.Text` - `StringBuilder`
### Consumers
- Unknown from source alone. The partial class structure (`Test.cs`, `Test.Module`) suggests this is part of a larger test configuration system.
---
## 5. Gotchas
### Critical Bugs in `TiltAxesHelper` Constructor
1. **Dictionary Key Mismatch:** The constructor parses `TiltAxes` string using indices 0, 1, 2:
```csharp
for (int i = 0; i < 3; i++)
{
AxisConfigurations[i].Label = TiltAxes[i * 2].ToString();
}
```
However, the conditional logic references keys 1, 2, 3:
```csharp
AxisOne = AxisConfigurations[2];
AxisTwo = AxisConfigurations[3]; // Key 3 does not exist!
```
This will throw a `KeyNotFoundException` at runtime when `AxisIgnored == 1`.
2. **Duplicate Assignment Bug:** In the `else` branch (when `AxisIgnored` is not 1 or 2):
```csharp
AxisOne = AxisConfigurations[1];
AxisOne = AxisConfigurations[2]; // Overwrites previous line
```
`AxisOne` is assigned twice and `AxisTwo` is never assigned (remains `null`).
3. **TargetOffset Assignment Bug:**
```csharp
AxisOne.TargetOffset = TargetAxisOne;
AxisOne.TargetOffset = TargetAxisTwo; // Overwrites previous line
```
`TargetAxisTwo` overwrites `TargetAxisOne`, and `AxisTwo.TargetOffset` is never set.
### Other Issues
4. **Misleading Comments:** Comments in `GetTiltDegreesEU` state "1 decimal place" but the code uses `SIGNIFICANT_DIGITS = 1000` which provides 3 decimal places.
5. **Inconsistent Mount Offset Usage:** In `GetTiltDegreesEU`, some switch cases use `mountOffsetAxisOne` twice for different axes (e.g., case 2 in XYZ uses `mountOffsetAxisOne` for both X and Z calculations). This may be intentional but appears inconsistent.
6. **Silent Normalization:** `ignoredAxis == 0` is silently converted to `3` without documentation or validation of other invalid values.
7. **Unused Property:** `UseForTiltCalculation` property in `TiltAxesHelper` is set in the constructor but never used elsewhere in the visible code.

View File

@@ -0,0 +1,80 @@
---
source_files:
- Common/DTS.Common.DAS.Concepts/Test/Module/Channel/Sensor/SensorUnits.cs
- Common/DTS.Common.DAS.Concepts/Test/Module/Channel/Sensor/ExcitationVoltage.cs
generated_at: "2026-04-16T11:39:55.789807+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "00bbefe8072cdb62"
---
# Documentation: Test.Module.Channel.Sensor
## 1. Purpose
This module defines sensor-related concepts within the DAS (Data Acquisition System) domain model. Specifically, it provides an enumeration for sensitivity unit types (`SensUnits`) and utility methods for converting between excitation voltage enum values and their numeric magnitudes. The module is part of a larger nested class hierarchy representing test configuration concepts for channel/sensor setup.
## 2. Public Interface
### Enum: `Test.Module.Channel.Sensor.SensUnits`
Defines all available sensitivity unit types for sensor configuration.
| Member | Value | Description Attribute | Purpose |
|--------|-------|----------------------|---------|
| `NONE` | 0 | "NONE" | No Sensitivity Units (Polynomial Sensor) |
| `mV` | 1 | "mV" | Sensitivity expressed in mV with output at Capacity EU |
| `mVperV` | 2 | "mV/V" | Excitation proportional sensitivity expressed in mV/V with output at Capacity EU |
| `mVperVperEU` | 3 | "mV/V/EU" | Excitation proportional sensitivity expressed in mV/V/EU |
| `mVperEU` | 4 | "mV/EU" | Sensitivity expressed in mV/EU |
---
### Method: `GetExcitationVoltageMagnitudeFromEnum`
**Signature:**
```csharp
public static double GetExcitationVoltageMagnitudeFromEnum(
ExcitationVoltageOptions.ExcitationVoltageOption target)
```
**Behavior:** Converts an `ExcitationVoltageOptions.ExcitationVoltageOption` enum value to its associated numeric voltage magnitude (in volts) using a `VoltageMagnitudeAttributeCoder`. Throws `ArgumentException` if the conversion fails.
---
### Method: `GetExcitationVoltageEnumFromMagnitude`
**Signature:**
```csharp
public static ExcitationVoltageOptions.ExcitationVoltageOption GetExcitationVoltageEnumFromMagnitude(
double magnitude)
```
**Behavior:** Converts a numeric voltage magnitude to the corresponding `ExcitationVoltageOptions.ExcitationVoltageOption` enum value. On failure, logs the exception via `APILogger.Log` and returns `ExcitationVoltageOptions.ExcitationVoltageOption.Undefined` rather than throwing.
## 3. Invariants
- The `SensUnits` enum values are explicitly assigned sequential integers starting at 0.
- The `Module` class is declared `sealed`, preventing further inheritance.
- The `ExcitationVoltageOptions.ExcitationVoltageOption` type (defined externally in `DTS.Common.Enums`) is expected to have an associated `VoltageMagnitudeAttribute` for each enum member that these methods can decode/encode.
- The two conversion methods have asymmetric error handling: `GetExcitationVoltageMagnitudeFromEnum` throws on failure, while `GetExcitationVoltageEnumFromMagnitude` returns `Undefined` and logs.
## 4. Dependencies
### This module depends on:
- `System` - Core .NET types
- `System.ComponentModel` - `DescriptionAttribute` used on enum members
- `DTS.Common.Enums` - Provides `ExcitationVoltageOptions.ExcitationVoltageOption` and `ExcitationVoltageOptions.VoltageMagnitudeAttributeCoder`
- `DTS.Common.Utilities` - Likely provides the base `AttributeCoder<TEnum, TAttribute, TValue>` pattern (inferred from usage)
- `DTS.Common.Utilities.Logging` - Provides `APILogger` for error logging
### What depends on this module:
- Cannot be determined from source alone. The partial class structure suggests other files extend `Test`, `Test.Module`, `Test.Module.Channel`, and `Test.Module.Channel.Sensor`.
## 5. Gotchas
1. **Commented-out code suggests refactoring:** The `ExcitationVoltage.cs` file contains a fully commented-out `ExcitationVoltageOption` enum and related classes (`VoltageMagnitudeAttribute`, `VoltageMagnitudeAttributeCoder`). The active methods reference `ExcitationVoltageOptions.ExcitationVoltageOption` from `DTS.Common.Enums`, indicating this functionality was moved to a different namespace. The commented code may cause confusion about where the enum is actually defined.
2. **Asymmetric error handling:** The two conversion methods handle errors differently. `GetExcitationVoltageMagnitudeFromEnum` throws an `ArgumentException` (wrapping the inner exception), while `GetExcitationVoltageEnumFromMagnitude` silently logs and returns `Undefined`. Callers must handle both throwing and non-throwing failure modes.
3. **Partial class structure:** The `Test`, `Module`, `Channel`, and `Sensor` classes are all partial, spread across multiple files (indicated by comments like `// *** see Test.cs ***`). The full API surface requires examining all partial file definitions.

View File

@@ -0,0 +1,58 @@
---
source_files:
- Common/DTS.Common.DASResource/Settings.Designer.cs
generated_at: "2026-04-16T11:29:30.800275+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "944279911ea3f393"
---
# Documentation: DTS.Common.DASResource.Settings
## 1. Purpose
This module serves as a strongly-typed wrapper for application and user configuration settings within the `DTS.Common.DASResource` namespace. It is an auto-generated designer file (created by Visual Studio's `SettingsSingleFileGenerator`) that facilitates the retrieval and persistence of runtime configuration values, specifically handling sample rate mappings and a generic string parameter. It abstracts the underlying XML configuration storage mechanism provided by the .NET Framework.
## 2. Public Interface
### Class: `Settings`
**Inherits from:** `global::System.Configuration.ApplicationSettingsBase`
The primary entry point for accessing configuration values in this namespace. It implements the singleton pattern to provide a shared instance.
#### Properties
* **`public static Settings Default`**
* **Type:** `Settings`
* **Behavior:** Provides access to the singleton instance of the settings class. The instance is synchronized for thread safety via `ApplicationSettingsBase.Synchronized`.
* **`public global::System.Collections.Specialized.OrderedDictionary Samplerate2AAFrequency`**
* **Type:** `global::System.Collections.Specialized.OrderedDictionary`
* **Behavior:** Gets or sets a user-scoped setting containing a mapping structure. The use of an `OrderedDictionary` implies the order of entries is significant for this configuration.
* **Scope:** User-scoped (read/write).
* **`public string abcd`**
* **Type:** `String`
* **Behavior:** Gets or sets a user-scoped string setting.
* **Default Value:** `"hdsa askjhsad kjhsad"`
* **Scope:** User-scoped (read/write).
## 3. Invariants
* **Singleton Existence:** The `defaultInstance` field is initialized statically and immediately wrapped via `Synchronized`, ensuring `Settings.Default` is never null upon first access.
* **Type Safety:** The getters for `Samplerate2AAFrequency` and `abcd` perform explicit casts from the underlying object dictionary (`this["PropertyName"]`) to their respective types (`OrderedDictionary`, `string`). If the underlying configuration data is missing or of an incompatible type, an `InvalidCastException` or `NullReferenceException` may occur.
* **User Scope:** Both defined properties are decorated with `[UserScopedSettingAttribute()]`, meaning values are serialized per-user rather than per-application (assuming standard .NET configuration behavior).
## 4. Dependencies
* **Internal Dependencies:**
* `System.Configuration.ApplicationSettingsBase`: The base class providing the configuration persistence mechanism.
* `System.Collections.Specialized.OrderedDictionary`: Used as the data structure for the `Samplerate2AAFrequency` property.
* **External Consumers:**
* Any component within the solution requiring access to the `Samplerate2AAFrequency` mapping or the `abcd` configuration value.
## 5. Gotchas
* **Auto-Generated Code:** This file is marked with `GeneratedCodeAttribute`. Manual modifications to this specific file will be overwritten if the settings are re-saved in the Visual Studio designer. Custom logic should be added to a partial class file (e.g., `Settings.cs`) rather than `Settings.Designer.cs`.
* **Placeholder Data:** The property `abcd` has a default value of `"hdsa askjhsad kjhsad"`. This appears to be placeholder or test data (keyboard mashing) rather than production configuration, suggesting the setting may be unused or requires cleanup.
* **Non-Generic Collection:** The `Samplerate2AAFrequency` property uses `OrderedDictionary`. This is a non-generic collection (it holds `object` types). Developers consuming this property must cast values when enumerating the dictionary, which introduces potential runtime type errors compared to using a generic `Dictionary<TKey, TValue>`.
* **User Scope Persistence:** Because these settings are User-Scoped, calling `Settings.Default.Save()` will write changes to a user-specific configuration file (e.g., in the AppData folder), not the application's `app.config` or `web.config` file. This can cause confusion if the developer expects changes to apply globally to all users.

View File

@@ -0,0 +1,44 @@
---
source_files:
- Common/DTS.Common.DASResource/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:47:41.567489+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "a495054ce85e611b"
---
# Documentation: DTS.Common.DASResource Assembly Metadata
## 1. Purpose
This file provides assembly-level metadata and configuration for the `DTS.Common.DASResource` assembly. It defines the assembly's identity, version, and visibility settings for COM interop. This module exists to embed standard .NET assembly information (such as title, version, and copyright) into the compiled DLL, facilitating version tracking and component identification within the larger DTS system.
## 2. Public Interface
This file contains no public classes, methods, or functions. It applies assembly-level attributes that affect the compiled binary's metadata.
**Defined Attributes:**
* **`AssemblyTitle`**: Set to `"DASResource"`. Specifies the friendly name for the assembly.
* **`AssemblyProduct`**: Set to `"DASResource"`. Specifies the product name this assembly belongs to.
* **`AssemblyCopyright`**: Set to `"Copyright © 2008 - 2009"`. Specifies copyright information.
* **`ComVisible`**: Set to `false`. Makes types in this assembly invisible to COM components by default.
* **`Guid`**: Set to `"E20CF41A-9884-40f4-AD18-4F06A42FE36D"`. Specifies the GUID for the type library ID if the assembly is exposed to COM.
* **`AssemblyVersion`**: Set to `"1.06.0081"`. Specifies the version number used by the common language runtime.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`. Specifies the file version number displayed on the file properties dialog.
## 3. Invariants
* **COM Visibility:** All types within this assembly are explicitly marked as not visible to COM (`ComVisible(false)`) unless a specific type overrides this attribute.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are maintained as identical strings (`"1.06.0081"`).
* **Identity:** The `AssemblyTitle` and `AssemblyProduct` are consistently named `"DASResource"`.
## 4. Dependencies
**Internal Dependencies:**
* `System.Reflection`: Required to access the `Assembly*` attribute classes.
* `System.Runtime.InteropServices`: Required to access the `ComVisible` and `Guid` attribute classes.
**External Dependencies:**
* None inferred from this file alone. As an assembly info file, it is a leaf node in the code dependency graph, though the resulting compiled assembly (`DTS.Common.DASResource.dll`) is likely referenced by other projects in the solution.
## 5. Gotchas
* **Hardcoded Versions:** The version strings (`"1.06.0081"`) are hardcoded. If the build process does not automatically update these values, release versions may not reflect the actual build number or commit hash.
* **Outdated Copyright:** The `AssemblyCopyright` string contains a hardcoded date range ending in 2009. This suggests the metadata has not been updated in over a decade, which may cause confusion regarding the maintenance status of the library.
* **Legacy Project Structure:** The presence of an explicit `AssemblyInfo.cs` file suggests a legacy .NET Framework project structure (non-SDK style). Modern .NET SDK-style projects typically auto-generate this metadata, which can lead to build conflicts (CS0579) if this project is migrated without removing these attributes or disabling auto-generation in the `.csproj` file.

View File

@@ -0,0 +1,93 @@
---
source_files:
- Common/DTS.Common.DBSyncService/ProjectInstaller.cs
- Common/DTS.Common.DBSyncService/Program.cs
- Common/DTS.Common.DBSyncService/DBSyncService.Designer.cs
- Common/DTS.Common.DBSyncService/DBSyncService.cs
- Common/DTS.Common.DBSyncService/ProjectInstaller.Designer.cs
generated_at: "2026-04-16T11:31:44.939659+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5d52988c06d02137"
---
# Documentation: DTS.Common.DBSyncService
## 1. Purpose
This module implements a Windows Service skeleton for database synchronization operations. It provides the foundational infrastructure for running as a Windows Service, including installation support via `ProjectInstaller`, event logging capabilities, a configurable monitoring timer, and custom command handling. The service is designed to perform periodic monitoring activities and respond to custom commands, though the actual synchronization logic is not yet implemented (marked with TODO comments).
---
## 2. Public Interface
### `DBSyncService` (class)
**Inherits from:** `System.ServiceProcess.ServiceBase`
The main Windows Service implementation.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `public DBSyncService()` | Initializes the service, configures event logging from `Settings.Default`, and optionally starts a monitoring timer if `Settings.Default.Monitoring` is enabled. |
| `OnTimer` | `public void OnTimer(object sender, ElapsedEventArgs args)` | Timer callback that writes an informational entry "Monitoring the System" to the event log. |
| `OnStart` | `protected override void OnStart(string[] args)` | Called when the service starts; logs "{ServiceName} started" to the event log. |
| `OnStop` | `protected override void OnStop()` | Called when the service stops; logs "{ServiceName} stopped" to the event log. |
| `OnCustomCommand` | `protected override void OnCustomCommand(int command)` | Handles custom service commands; currently contains empty switch cases for defined commands. |
| `CustomCommands` | `public enum CustomCommands` | Defines custom command identifiers: `SyncDb = 128`, `Command2 = 129`, `Command3 = 130`. |
| `eventLog` | `public System.Diagnostics.EventLog eventLog` | Public field for event logging (defined in designer partial). |
### `ProjectInstaller` (class)
**Inherits from:** `System.Configuration.Install.Installer`
Provides installation support for the Windows Service.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `public ProjectInstaller()` | Initializes the installer via `InitializeComponent()`. |
### `Program` (static class)
Application entry point.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Main` | `static void Main()` | Creates a `DBSyncService` instance and runs it via `ServiceBase.Run()`. |
---
## 3. Invariants
1. **Event Source Creation**: If the event source specified by `Settings.Default.ServiceName` does not exist, it will be created in the constructor with log name from `Settings.Default.Service`.
2. **Timer Behavior**: The monitoring timer is only instantiated and started if `Settings.Default.Monitoring` evaluates to `true`. The interval is determined by `Settings.Default.Interval` (default noted as 60 seconds in comments).
3. **Custom Command Range**: Custom commands use values starting at 128 (`SyncDb`), which is within the valid range for custom Windows Service commands (128-255).
4. **Service Name Consistency**: The service name "DBSyncService" is set in `ProjectInstaller.Designer.cs` via `DBSyncServiceInstaller.ServiceName`. Note: `DBSyncService.Designer.cs` sets `this.ServiceName = "Service1"`, which appears to be a designer default that may be overridden.
---
## 4. Dependencies
### This module depends on:
- `System.ServiceProcess` - Windows Service infrastructure (`ServiceBase`, `ServiceInstaller`, `ServiceProcessInstaller`)
- `System.Diagnostics` - Event logging (`EventLog`, `EventLogEntryType`)
- `System.Timers` - Timer for periodic monitoring
- `System.Configuration.Install` - Service installation framework (`Installer`, `RunInstallerAttribute`)
- `DTS.Common.DBSyncService.Properties` - Application settings (`Settings.Default`)
### What depends on this module:
- Cannot be determined from source alone. This appears to be a top-level executable service.
---
## 5. Gotchas
1. **Unimplemented Logic**: The `OnTimer` method contains a TODO comment: `// TODO: Insert monitoring activities here.` The actual synchronization/monitoring logic is not implemented.
2. **Empty Custom Command Handlers**: All three custom commands (`SyncDb`, `Command2`, `Command3`) have empty switch case bodies in `OnCustomCommand`. They are defined but perform no actions.
3. **Timer Lifetime Issue**: The `Timer` instance in the constructor is a local variable. If no other reference is maintained, it could be eligible for garbage collection, which would stop the timer. The timer should be stored as a class field.
4. **Service Name Mismatch**: `DBSyncService.Designer.cs` sets `this.ServiceName = "Service1"` (default designer value), while `ProjectInstaller.Designer.cs` sets `DBSyncServiceInstaller.ServiceName = "DBSyncService"`. The actual runtime service name comes from `Settings.Default.ServiceName`, making the designer value potentially misleading.
5. **Early Return in Constructor**: If `Settings.Default.Monitoring` is `false`, the constructor returns early, skipping timer setup. This is intentional but could cause confusion if monitoring is expected but not configured.

View File

@@ -0,0 +1,75 @@
---
source_files:
- Common/DTS.Common.DBSyncService/Properties/AssemblyInfo.cs
- Common/DTS.Common.DBSyncService/Properties/Settings.Designer.cs
generated_at: "2026-04-16T11:55:52.072519+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "192083dd898290ec"
---
# Documentation: DTS.Common.DBSyncService
## 1. Purpose
This module provides assembly metadata and application configuration settings for the DTS Database Synchronization Service. Based on the available source files, this appears to be a configuration layer for a Windows service that performs database synchronization operations. The actual service implementation logic is not present in the provided files—only the assembly attributes and auto-generated settings accessor are visible.
---
## 2. Public Interface
### `DTS.Common.DBSyncService.Properties.Settings`
An `internal sealed partial` class that extends `global::System.Configuration.ApplicationSettingsBase`. Provides strongly-typed access to application settings.
| Property | Type | Access | Default Value | Description |
|----------|------|--------|---------------|-------------|
| `Default` | `Settings` | Static getter | N/A | Returns a synchronized singleton instance of the `Settings` class |
| `Monitoring` | `bool` | Instance getter | `False` | Application-scoped setting indicating whether monitoring is enabled |
| `Interval` | `int` | Instance getter | `60000` | Application-scoped setting for the operation interval (presumably milliseconds) |
| `ServiceName` | `string` | Instance getter | `"DTS DB Sync Service"` | Application-scoped setting for the service display name |
| `Service` | `string` | Instance getter | `"DB Sync Service"` | Application-scoped setting for the service identifier |
### Assembly Attributes (AssemblyInfo.cs)
| Attribute | Value |
|-----------|-------|
| `AssemblyTitle` | `"DTS.Common.DBSyncService"` |
| `AssemblyDescription` | `""` (empty) |
| `AssemblyVersion` | `"1.0.0.0"` |
| `AssemblyFileVersion` | `"1.0.0.0"` |
| `ComVisible` | `false` |
| `Guid` | `"5f8e95eb-e89c-4fdc-9bde-3e78dd56ad6f"` |
---
## 3. Invariants
- **Singleton Pattern**: The `Settings` class maintains a single synchronized instance accessible via `Settings.Default`.
- **Application-Scoped Settings**: All settings (`Monitoring`, `Interval`, `ServiceName`, `Service`) are decorated with `ApplicationScopedSettingAttribute`, meaning they are read-only at runtime and must be configured at the application level (e.g., via `app.config`).
- **Thread Safety**: The `Settings` instance is created via `ApplicationSettingsBase.Synchronized()`, providing thread-safe access to settings.
- **Sealed Class**: `Settings` is marked `sealed`, preventing inheritance.
---
## 4. Dependencies
### This Module Depends On:
- `System.Reflection` — For assembly metadata attributes
- `System.Runtime.CompilerServices` — For `CompilerGeneratedAttribute`
- `System.Runtime.InteropServices` — For `ComVisible` and `Guid` attributes
- `System.Configuration` — For `ApplicationSettingsBase`, `ApplicationScopedSettingAttribute`, `DefaultSettingValueAttribute`
- `System.Diagnostics` — For `DebuggerNonUserCodeAttribute`
- `System.CodeDom.Compiler` — For `GeneratedCodeAttribute`
### What Depends On This Module:
**Cannot be determined from source alone.** The provided files contain only configuration and assembly metadata; no consumers are visible.
---
## 5. Gotchas
- **Auto-Generated File**: `Settings.Designer.cs` is generated by `SettingsSingleFileGenerator` (version 15.1.0.0). Manual modifications will be overwritten if the settings are regenerated from the `.settings` file.
- **Missing Implementation**: The actual service logic, entry point, and business logic are not present in the provided files. The module's runtime behavior cannot be fully documented without additional source files.
- **Empty AssemblyDescription**: The assembly description attribute is empty, which may indicate incomplete documentation at the assembly level.
- **Copyright Date**: The `AssemblyCopyright` attribute contains "2017", which may be outdated relative to current development.

View File

@@ -0,0 +1,272 @@
---
source_files:
- Common/DTS.Common.DataModel/ApplicationProperties.cs
- Common/DTS.Common.DataModel/CollectDataProcess.cs
- Common/DTS.Common.DataModel/SysBuiltObjectType.cs
- Common/DTS.Common.DataModel/DataModelSettings.cs
- Common/DTS.Common.DataModel/DataFiles.cs
- Common/DTS.Common.DataModel/ChannelRepresentation.cs
- Common/DTS.Common.DataModel/DASFactory.cs
generated_at: "2026-04-16T11:36:27.833103+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "d315c00965ab6aef"
---
# DTS.Common.DataModel Module Documentation
## 1. Purpose
This module provides the core data model and application-wide state management for the DTS DataPRO system. It contains global application properties, configuration settings, data file management, channel representation logic for hardware abstraction, and the DAS (Data Acquisition System) factory wrapper for device discovery and communication. The module serves as the central hub connecting hardware abstraction, user context, ISO standards integration, and test data management.
---
## 2. Public Interface
### ApplicationProperties (static class)
Global application state container.
| Property | Type | Description |
|----------|------|-------------|
| `CurrentUser` | `User` | Gets or sets the currently logged-in user. |
| `DASFactory` | `DASFactory` | Gets or sets the DAS factory instance for device management. |
| `CurrentView` | `User` | Gets or sets the current view context (distinct from CurrentUser). |
| `IsoDb` | `ISO13499FileDb` | Gets or sets the ISO 13499 database reference. |
| `LicenseValidationResult` | `ValidationResult` | Gets or sets the license validation state. |
| `CanCurrentUserCommitChannelCodes` | `bool` | Gets or sets whether the current user has permission to commit channel codes. |
---
### CollectDataProcess : BasePropertyChanged
Represents a data collection process with visual properties.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `CollectDataProcess(string name, Color color)` | Initializes with name and background color. |
| `Name` | `string` | Gets or sets the process name. |
| `BackgroundColor` | `Color` | Gets or sets the background color. |
| `IsEnabled` | `bool` | Gets or sets whether the process is enabled. |
---
### SysBuiltObjectType
Container for Dynamic Groups of a given test object type (Vehicle 1, Vehicle 2, Sled, etc.).
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `SysBuiltObjectType(string testObjectType)` | Initializes with a test object type string. |
| `TestObject` | `MMETestObjects` | Gets or sets the test object via ISO database lookup. Setter stores `value.Test_Object` internally. |
| `ISOTestObjectType` | `string` | Gets `TestObject.Text_L1`. |
| `ToString()` | `override string` | Returns `TestObject.Text_L1`. |
---
### DataModelSettings (static class)
Application-wide configuration with default values.
**Hardware/Signal Settings:**
- `UseISOCodeForDiadem200`: `bool` (default: `false`)
- `SampleRateAAFilterRatio`: `byte` (default: `5`)
- `RealtimeSampleRateAAFilterRatio`: `byte` (default: `1`)
- `SLICETurnOffAAFRealtime`: `bool` (default: `true`)
- `ShowCompactHardware`: `bool` (default: `true`)
**Error Tolerance Settings:**
- `AllowedVoltageInsertionErrorPercent`: `double` (default: `1`)
- `AllowedExcitationErrorPercent`: `double` (default: `2`)
- `AllowedShuntErrorPercent`: `double` (default: `5`)
- `ShuntToleranceHighOhmPercent`: `double` (default: `10`)
- `AllowedGainErrorPercent`: `double` (default: `2`)
- `AllowedGainErrorPercent_SLICE6andSLICE6A`: `double` (default: `5`)
- `AutoZeroPercentDeviationAllowed`: `double` (default: `5`)
- `ShuntToleranceHighOhmResistance`: `double` (default: `4000`)
**Timing/Network Settings:**
- `CheckUnitsIntervalMillisecond`: `int` (default: `50`)
- `SemaphoreDelay`: `double` (default: `10`)
- `SemaphoreSpots`: `int` (default: `3`)
- `SLICEConcurrentSpots`: `int` (default: `999`)
- `SLICEConcurrentDelayMs`: `int` (default: `0`)
- `MulticastAutoDiscoveryReceiveTimeoutMS`: `int` (default: `1500`)
- `LocalKeepAliveRetryIntervalMS`: `uint` (default: `1000`)
- `LocalKeepAliveTimeOutMS`: `uint` (default: `5000`)
- `RemoteKeepAliveRetryIntervalSeconds`: `uint` (default: `5`)
- `RemoteKeepAliveSeconds`: `uint` (default: `60`)
- `ReceiveBufferSizeBytes`: `int` (default: `65536`)
- `SendBufferSizeBytes`: `int` (default: `65536`)
- `HeartbeatAsyncConnectTimeoutMS`: `int` (default: `10000`)
**File/Path Settings:**
- `DownloadFolder`: `string` (default: `"..\\..\\Data"`)
- `DefaultTDCSensorDatabaseFolder`: `string` (default: `"..\\SensorDatabase"`)
- `DefaultTDCSensorDatabaseFile`: `string` (default: `"SensorDatabase.CSV"`)
- `TDCSensorDatabaseImportEncoding`: `string` (default: `"Shift-JIS"`)
**Other Settings:**
- `SupportedSquibFireModes`: `string` (default: `"CAP,CONSTANT"`)
- `RequireXCrashCompatibilityForISOExports`: `bool` (default: `true`)
- `DisplayDuplicateUDPStreamOutWarning`: `bool` (default: `true`)
- `UseTestChannelOrder`: `bool` (default: `false`)
- `ArmChecklistRequiredIfTOM`: `bool` (default: `true`)
- `TestsRequireLevelTriggers`: `bool` (default: `false`)
- `TDCSensorDatabaseExportUseCurrentLocale`: `bool` (default: `false`)
---
### DataFiles : BasePropertyChanged
Represents metadata for a test data file.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `DataFiles(string expandCollapse, string testName, string id, string allOrROI, string lab, string customer, DateTime dateCreated, string description, string numberOfChannels, string testEngineer, bool isTSRAIR, string roiSuffix = "")` | Initializes all metadata fields. |
| `ExpandCollapse` | `string` | UI state for expand/collapse. |
| `TestName` | `string` | Name of the test. |
| `TestId` | `string` | Unique test identifier. |
| `AllOrROI` | `string` | Indicates "All" or "ROI" data type. |
| `Lab` | `string` | Lab name. |
| `Customer` | `string` | Customer name. |
| `DateCreated` | `DateTime` | Creation timestamp. |
| `Description` | `string` | Test description. |
| `NumberOfChannels` | `string` | Channel count as string. |
| `TestEngineer` | `string` | Test engineer name. |
| `ROISuffix` | `string` | ROI suffix identifier. |
| `DTSFile` | `string` | Location of DTS file (populated in export tab). |
| `IsTSRAIR` | `bool` | Indicates TSR AIR test (default: `false`). |
| `TestSelected` | `bool` | Selection state. |
| `LongString` | `string` | Extended string representation. |
---
### DataFilesList : BasePropertyChanged
Manages discovery and listing of test data files.
| Member | Signature | Description |
|--------|-----------|-------------|
| `DataFileList` | `static DataFilesList` | Singleton instance accessor. |
| `DataFiles` | `DataFiles[]` | Gets or sets the list of data files. |
| `GetAllDataFiles()` | `DataFiles[]` | Returns top-level test folders with file counts. |
| `GetAllFiles(string testName)` | `DataFiles[]` | Returns all data files for a specific test name. |
| `Contract(DataFiles df)` | `DataFiles[]` | Collapses expanded test entries in the list. |
| `DownloadFolder` | `string` | Field storing the download folder path. |
---
### ChannelRepresentation
Handles channel number conversion and display representation for various hardware types.
| Member | Signature | Description |
|--------|-----------|-------------|
| `ChannelTypeEnum` | `enum` | Values: `SQUIB`, `TOMDigital`, `DigitalInput`, `Other`. |
| Constructor | `ChannelRepresentation(DASHardware h, DASChannel c, int startingChannelNumber)` | Creates representation from DAS hardware and channel. |
| Constructor | `ChannelRepresentation(HardwareChannel c, int startingChannelNumber, IDASHardware[] hardwares = null)` | Creates representation from hardware channel. |
| `DASSerialNumber` | `string` | Gets or sets the DAS serial number. |
| `SerialNumber` | `string` | Gets or sets the module serial number. |
| `ChannelNumberString` | `string` | Gets formatted channel display string (e.g., "CH01", "SQ02"). |
| `ChannelNumber` | `int` | Gets the numeric channel number. |
---
### DASFactory
Wrapper around `DTS.DASLib.DASFactory.DASFactory` for device discovery and management.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `DASFactory()` | Initializes factory, semaphores, keep-alive settings, and event handlers. |
| `StartMulticastAutoDiscovery()` | `void` | Starts auto-discovery process if not running. |
| `StopMulticastAutoDiscovery()` | `void` | Stops auto-discovery process. |
| `GetDiscoveredDevices()` | `IDiscoveredDevice[]` | Returns discovered devices. |
| `GetDASFactory()` | `IDASFactory` | Returns the underlying DAS factory interface. |
| `TakeOwnership()` | `void` | Takes ownership of devices. |
| `DetachAllDevices(bool detachUSB = false)` | `void` | Detaches all devices; USB detaching is conditional. |
| `DisposeFactory()` | `void` | Disposes the underlying factory. |
| `Refresh(bool wait)` | `void` | Refreshes device list; optionally waits for completion. |
| `GetActiveDevices()` | `List<IDASCommunication>` | Returns list of active DAS communications. |
| `GetReportedConnections()` | `string[]` | Returns all reported connections from distributors. |
| `AutoDiscoverIfNecessary()` | `void` | Runs auto-discovery for SLICE6/SLICE6Db downstream MAC addresses. |
| `AutoDiscoverMulticast()` | `SortableBindingList<IDiscoveredDevice>` | Performs multicast auto-discovery. |
| `DiscoveryThread(...)` | `void` | Background thread for continuous discovery with filtering. |
| `StartQATSListening()` / `StopQATSListening()` | `void` | Controls QATS UDP listening. |
| `SendQATSRequest()` | `void` | Sends UDP QATS request. |
| `GetQATS()` | `IUDPQATSEntry[]` | Returns and clears waiting QATS entries. |
| `IsStreaming(IDASCommunication das)` | `static bool` | Returns true if SLICE6 Air is streaming. |
| `IsInRealtime(IDASCommunication das)` | `static bool` | Returns true if unit is in realtime or streaming. |
| `AnyInRealtime(List<IDASCommunication> das)` | `static bool` | Returns true if any unit is in realtime or streaming. |
**Properties:**
- `TDASHostNames`: `string[]` - TDAS host names with deduplication on set.
- `SPFDHostNames`: `string[]` - SPFD host names.
- `SDBHostNames`: `string[]` - Slice DB host names.
- `MulticastAutoDiscoveryReceiveTimeoutMS`: `int` - Timeout for multicast discovery.
- `MulticastAutoDiscoveryAddress`: `string` - Multicast address.
- `MulticastAutoDiscoveryPort`: `int` - Transmit port.
- `MulticastAutoDiscoveryResponsePort`: `int` - Receive port.
- `S6ConnectNewTimeout`: `double` - SLICE6 connection timeout.
**Events:**
- `OnDeviceArrived`: `DASFactoryEventHandler` - Fired when a device arrives.
- `OnFactoryChanged`: `DASFactoryEventHandler` - Fired on device arrival, failure, or removal.
- `DiscoveredDAS`: `DiscoveredDASEventHandler` - Fired with discovered devices.
---
## 3. Invariants
1. **ApplicationProperties Global State**: All properties are static and globally accessible. Consumers must ensure `DASFactory` and `IsoDb` are initialized before use.
2. **DataFilesList Singleton**: The `DataFileList` property uses lazy initialization and always returns the same instance.
3. **DASFactory Refresh Concurrency**: The `_bInRefresh` flag guards against overlapping refresh calls. Only one refresh can execute at a time; overlapping calls are logged but do not execute.
4. **ChannelRepresentation Hardware Type Handling**: The `ConvertChannelNumbers` method must receive valid `HardwareTypes` enum values. Unknown types fall through to a default case that uses the starting channel number directly.
5. **Data Folder Structure**: `GetFoldersWithData` expects folders containing both `.dts` and `.chn` files to be considered valid data folders.
6. **SysBuiltObjectType ISO Lookup**: The `TestObject` getter calls `ApplicationProperties.IsoDb.GetTestObjectByIso()``IsoDb` must be initialized before accessing this property.
---
## 4. Dependencies
### This module depends on:
- `DTS.Slice.Users` - User types
- `DTS.Common.ISO` - ISO 13499 database and test objects (`ISO13499FileDb`, `MMETestObjects`)
- `DTS.Common.Licensing.Messages` - `ValidationResult`
- `DTS.Common.Base` - `BasePropertyChanged` for MVVM pattern
- `DTS.DASLib.DASFactory` - Underlying DAS factory implementation
- `DTS.DASLib.Service` - Channel and communication types
- `DTS.Common.Utilities.Logging` - `APILogger`
- `DTS.Common.Interface.DASFactory` - `IDASFactory`, `IDiscoveredDevice`
- `DTS.Common.Interface.DataRecorders` - `IDASHardware`
- `DTS.Common.Enums.Hardware` - `HardwareTypes`
- `DTS.Common.Enums.Sensors` - Sensor enums
- `DTS.Common.Constant.DASSpecific` - `SensorConstants`, `DFConstantsAndEnums`
- `DTS.Common.Converters` - `EnumDescriptionTypeConverter`
- `DTS.Common.SharedResource.Strings` - Localized strings
- `DTS.Serialization` - File reading utilities
- `DTS.Common.Utils` - Utility classes
- `DTS.Common.DataModel.Classes.TestTemplate` - `TSRAIRGoTestSetup`
- `System.Windows.Media` - `Color` type
- `System.Xml.Linq` - XML parsing
### What depends on this module:
- Unclear from source alone — this appears to be a foundational module likely consumed by UI components, test management, and hardware configuration modules.
---
## 5. Gotchas
1. **ApplicationProperties Static State**: All properties are mutable static state with no thread-safety mechanisms. Concurrent access from multiple threads could cause race conditions.
2. **SysBuiltObjectType Null Risk**: The `TestObject` getter calls `ApplicationProperties.IsoDb.GetTestObjectByIso()` without null checks. If `IsoDb` is null, this will throw.
3. **DASFactory Constructor Blocking**: The constructor performs a synchronous `WaitOne()` on a `ManualResetEvent` during refresh, which could block the calling thread indefinitely if the refresh callback never fires.
4. **ChannelRepresentation Type Casting**: The first constructor casts `c` to `DAS.DASLib.Service.AnalogInputDASChannel` without checking type first, which will throw for non-analog channels.
5. **DataFilesList.GetTestInfo Silent Failure**: Returns `false` on any exception during XML parsing, logging the exception but not propagating the error. Callers may receive empty strings without knowing parsing failed.
6. **Hardcoded Strings**: `TSRAIRGoTestSetup.TEST_NAME` is used for TSR AIR detection but the class definition is not in the provided source.
7. **Namespace Inconsistency**: `ApplicationProperties` is in `DTS.Common.DataModel` namespace, while `CollectDataProcess`, `SysBuiltObjectType`, `DataFiles`, and `DASFactory` are in `DataPROWin7.DataModel` namespace.
8. **Refresh Overlap Handling**: When `Refresh` is called while already refreshing, the second call is silently ignored (only logged if `LOG_DEBUG_REFRESH` is defined). This could lead to stale device lists if callers expect refresh to

View File

@@ -0,0 +1,214 @@
---
source_files:
- Common/DTS.Common.ICommunication/IDASConnectedDevice.cs
- Common/DTS.Common.ICommunication/ICommunication.cs
- Common/DTS.Common.ICommunication/Communication.cs
generated_at: "2026-04-16T11:28:10.843855+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b573bb7d2f5d27d0"
---
# Documentation: DTS.Common.ICommunication
## 1. Purpose
This module provides the core communication infrastructure for interacting with DAS (Data Acquisition System) hardware. It defines the contract for DAS-connected devices via `IDASConnectedDevice`, encapsulates device metadata through `Communication_DASInfo`, and implements an asynchronous, callback-driven communication layer via the abstract `Communication<T>` class. The module handles connection lifecycle management, command execution with timeout handling, cancellation support, and receive buffering for networked hardware devices.
---
## 2. Public Interface
### IDASConnectedDevice (Interface)
**Namespace:** `DTS.DASLib.Communication`
Describes a device connected to a DAS (e.g., an S6 connected to an S6DB).
| Property | Type | Description |
|----------|------|-------------|
| `DeviceType` | `HardwareTypes` | The device type of the connected device. |
| `Port` | `int` | The port on the DAS which the device is on (0-based). |
| `SpotOnPort` | `int` | The spot on the chain or port the device is on (0-based). |
| `PhysicalAddress` | `PhysicalAddress` | MAC Address or physical address. |
| `IPAddress` | `string` | The IP address of the device. |
| `SerialNumber` | `string` | The serial number of the device. |
| `Location` | `string` | The location of the device. |
| `Version` | `string` | The version of the device. |
---
### CanceledException (Class)
**Namespace:** `DTS.Common.ICommunication`
Marker exception class extending `ApplicationException`. Used to signal operation cancellation.
---
### Communication_DASInfo (Class)
**Namespace:** `DTS.Common.ICommunication`
Implements `ICommunication_DASInfo`. Holds metadata about a DAS device.
**Properties:**
- `FirstUseDate` (`DateTime?`) — Date of first use; `null` indicates hardware has not been used since calibration. Only valid when `IsFirstUseDateSupported` is `true`.
- `IsFirstUseDateSupported` (`bool`) — Indicates hardware supports first use dates.
- `IsStreamingSupported` (`bool`) — Indicates whether streaming is supported.
- `ConnectedDevices` (`IDASConnectedDevice[]`) — Devices connected to the DAS (currently only used by SLICE6DB).
**Methods:**
- `void SetConnectedDevices(IDASConnectedDevice[] devices)` — Sets the `ConnectedDevices` array.
- `string StackSerialNumber(int devid)` — Returns a stacked serial number string. Returns `"N/A"` if `SerialNumbers` is null/empty; returns `SerialNumbers[0]::SerialNumbers[devid]` if `devid` is non-zero and valid; otherwise returns `SerialNumbers[0]`.
**Constructors:**
- `Communication_DASInfo()` — Default constructor.
- `Communication_DASInfo(string[] serials, string[] fwnums)` — Constructs with cloned serial and firmware version arrays.
---
### Communication\<T\> (Abstract Class)
**Namespace:** `DTS.Common.ICommunication`
Generic abstract base class for DAS communication. Type parameter `T` must implement `IConnection` and have a parameterless constructor.
**Properties:**
- `ErrorInSetup` (`bool`) — Indicates an error occurred during setup.
- `ConnectString` (`string`) — Returns `sock.ConnectString`.
- `Connected` (`bool`) — Returns `sock.Connected`.
- `DASInfo` (`ICommunication_DASInfo`) — DAS information object.
- `Transport` (`IConnection`) — Gets the underlying connection; setter throws `NotSupportedException`.
- `ReceiveBufferSize` (`int`) — Receive buffer size; default is 65536 (2^16).
- `SerialNumber` (`string`) — Device serial number.
- `FirmwareVersion` (`string`) — Firmware version; setter triggers `FirmwareVersionUpdated()`.
- `ProtocolVersion` (`byte`) — Protocol version.
- `MinimumProtocols` (`Dictionary<DFConstantsAndEnums.ProtocolLimitedCommands, byte>`) — Minimum protocol versions for commands.
- `FlushTimeoutMilliSec` (`int`) — Flush timeout; default is 5ms.
- `ExecuteIsBusy` (`bool`) — Thread-safe flag indicating execution lock state.
- `CancelEvent` (`ManualResetEvent`) — Event signaling cancellation.
**Methods:**
- `int CompareTo(ICommunication dev)` — Compares connect strings (case-insensitive ordinal).
- `int CompareTo(string conStr)` — Compares connect string to given string.
- `abstract void InitMinProto()` — Must be implemented to initialize `MinimumProtocols`.
- `bool IsCommandSupported(ProtocolLimitedCommands command)` — Returns `true` if `ProtocolVersion >= GetMinProto(command)`.
- `byte GetMinProto(ProtocolLimitedCommands command)` — Returns minimum protocol version for command; returns `0xFF` if not found; throws if `MinimumProtocols` is null.
- `void Flush(int timeoutMs)` — Flushes `SockDataBuffer` until empty or timeout.
- `byte[] SyncExecute(byte[] byteData, int cbTimeout)` — Throws `NotSupportedException`.
- `void Connect(string connectString, CommunicationCallback callback, object callbackObject, int callbackTimeout, string hostIPAddress)` — Initiates asynchronous connection.
- `void Disconnect(bool reuseSocket, CommunicationCallback callback, object callbackObject, int callbackTimeout)` — Initiates asynchronous disconnect.
- `void ForceCancel()` — Sets cancel state with 250ms sleep on clear.
- `void Cancel()` — Sets cancel state with 500ms sleep on clear.
- `bool IsCanceled()` — Returns current cancel state.
- `void ClearCancel()` — Clears cancel state after sleeping.
- `void PseudoExecute(byte[] byteData, CommunicationCallback cb, object cbObject, int cbTimeout)` — For commands that only receive data (no send). Throws `CanceledException` if canceled, `NotConnectedException` if not connected.
- `void Execute(byte[] byteData, CommunicationCallback cb, object cbObject, int cbTimeout)` — Sends data and processes response. Throws `CanceledException` if canceled, `NotConnectedException` if not connected.
- `void SetupReader()` — Initializes asynchronous receive loop.
- `void Close(int timeout)` — Empty implementation.
**Events:**
- `OnDisconnected` (`EventHandler`) — Raised when the underlying connection disconnects.
**Protected Methods:**
- `void Lock()` — Empty implementation.
- `void Release()` — Empty implementation.
- `virtual void FirmwareVersionUpdated()` — Called when `FirmwareVersion` is set.
---
### Communication.ActionData (Nested Abstract Class)
Base class for async operation tracking with timeout support.
**Constructor:** `ActionData(CommunicationCallback cb, object obj, int to)`
**Methods:**
- `void StartTimer()` — Starts timeout timer.
- `void KillTimer()` — Stops and disposes timer.
- `bool ReportCanceled()` — Invokes callback with `CommunicationResult.Canceled`.
- `abstract bool ReportFailure()` — Must implement failure reporting.
- `abstract bool ReportSuccess()` — Must implement success reporting.
- `abstract CommunicationResult GetTimeoutResult()` — Must return result for timeout.
**Properties:**
- `TimerExpired` (`bool`) — Returns whether timer has fired.
---
### Communication.ExecuteActionData (Nested Class)
Extends `ActionData` for execute operations.
**Additional Methods:**
- `bool ReportReadSuccess(byte[] data)` — Reports successful read with data.
- `bool ReportReadTimeout()` — Reports read timeout.
- `bool ReportReadDisconnected()` — Reports disconnection during read.
---
### CommunicationReport (Class)
**Namespace:** `DTS.Common.ICommunication`
Implements `ICommunicationReport`.
**Properties:**
- `UserState` (`object`) — User-provided state object.
- `Result` (`CommunicationResult`) — Result of the operation.
- `Data` (`byte[]`) — Received data (for read operations).
**Constructor:** `CommunicationReport(object state, CommunicationResult res)`
---
### Communication.PseudoAsyncResult (Nested Class)
Implements `IAsyncResult` for `PseudoExecute`. `IsCompleted` and `CompletedSynchronously` return `true`. `AsyncWaitHandle` throws `NotImplementedException`.
---
## 3. Invariants
1. **Connection State Checks:** `Connect()` throws if `sock` is null or already connected. `Disconnect()` throws if `sock` is null.
2. **Execute Pre-conditions:** Both `Execute()` and `PseudoExecute()` throw `CanceledException` if `IsCanceled()` returns `true`, and `NotConnectedException` if `Connected` is `false`.
3. **ExecuteIsBusy Thread Safety:** The `ExecuteIsBusy` property uses locking (`_executeBusyMtLock`) and asserts on re-entry or extra unlock attempts.
4. **Transport Immutability:** The `Transport` property setter always throws `NotSupportedException`.
5. **MinimumProtocols Requirement:** `GetMinProto()` throws `NotSupportedException` if `MinimumProtocols` is null.
6. **SyncExecute Unavailable:** `SyncExecute()` always throws `NotSupportedException`.
7. **Clone Behavior:** `Communication_DASInfo` constructor clones input arrays for `SerialNumbers` and `FirmwareVersions`.
8. **Port/Spot Indexing:** `Port` and `SpotOnPort` in `IDASConnectedDevice` are explicitly 0-based.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Enums.Hardware``HardwareTypes` enum
- `DTS.Common.Enums.Communication``CommunicationResult`, `CommunicationConstantsAndEnums`
- `DTS.Common.Enums.DASFactory``DFConstantsAndEnums`
- `DTS.Common.Interface.Communication``ICommunication_DASInfo`, `CommunicationCallback` delegate
- `DTS.Common.Interface.Connection``IConnection`
- `DTS.Common.Classes.Connection` — (referenced but implementation not shown)
- `DTS.Common.Utilities.Logging``APILogger`
- `DTS.Common.Utilities``SecureQueue<T>`
- `DTS.Common.Utils``WaitWithCondition`
- `System.Net.NetworkInformation``PhysicalAddress`
- `System.Net.Sockets``SocketException`
- `System.Threading`, `System.Threading.Tasks` — Async primitives
### What depends on this module:
- Cannot be definitively determined from source alone, but `Communication_DASInfo.ConnectedDevices` references `IDASConnectedDevice`, suggesting SLICE6DB implementations depend on this interface.
---
## 5. Gotchas
1. **Empty Lock/Release Methods:** `Lock()` and `Release()` are defined but have empty implementations. Their intended purpose is unclear from source alone.
2. **Close() is a No-Op:** The `Close(int timeout)` method has an empty body. Callers should not rely on it for cleanup.
3. **Cancel Sleep Behavior:** `ClearCancel()` sleeps for either 250ms (after `ForceCancel()`) or 500ms (after `Cancel()`) before clearing the cancel state. This blocking delay may be unexpected in time-sensitive contexts.
4. **Thread ID Check in Receive Callbacks:** Both `ProcessReceivedData` and `SRRecvCallback` check if `Thread.CurrentThread.ManagedThreadId` changes during `WaitWithCondition.Wait()`, logging and returning early if it does. This suggests a historical threading issue.
5. **Transport Setter Always Throws:** Attempting to set `Transport` throws `NotSupportedException` with message "Communication::Transport Can't replace socket".
6. **PseudoAsyncResult.AsyncWaitHandle Throws:** Accessing `AsyncWaitHandle` on `PseudoAsyncResult` throws `NotImplementedException`.
7. **ConnectedDevices Default is Empty Array:** `Communication_DASInfo.ConnectedDevices` initializes to an empty array, not null. Code checking for null will not behave as expected.
8. **StackSerialNumber Index Logic:** `StackSerialNumber(int devid)` returns the stacked format only when `devid != 0 && devid < SerialNumbers.Length`. A `devid` of 0 returns just `SerialNumbers[0]`, not a stacked string.

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.ICommunication/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:40:46.914027+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f8d21de2dda7b77f"
---
# Documentation for `DTS.Common.ICommunication`
## 1. Purpose
This file serves as the assembly manifest configuration for the `DTS.Common.ICommunication` project. It provides standard .NET assembly metadata—such as title, version, and COM visibility—used by the runtime and development tools. Based on the `AssemblyTitle` attribute, the broader module likely defines interfaces or abstractions related to communication, but the specific functional logic is implemented in other files within this assembly.
## 2. Public Interface
This source file does not define any public classes, methods, or constants accessible to consumers of the library. It strictly configures assembly-level attributes.
**Attributes Configured:**
* `AssemblyTitle`: Set to `"ICommunication"`.
* `AssemblyProduct`: Set to `"ICommunication"`.
* `AssemblyVersion`: Set to `"1.06.0081"`.
* `AssemblyFileVersion`: Set to `"1.06.0081"`.
* `ComVisible`: Set to `false`.
## 3. Invariants
* **COM Visibility:** Types within this assembly are not visible to COM components by default (`ComVisible(false)`).
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are synchronized at `"1.06.0081"`.
* **Identity:** The assembly is uniquely identified by the GUID `"11eb7c8b-d4b6-4121-8dcb-1b6ddfe1136f"`.
## 4. Dependencies
**Internal Dependencies (Imports):**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
**External Dependencies:**
* None inferred from this file.
## 5. Gotchas
* **Missing Description:** The `AssemblyDescription` attribute is an empty string, providing no runtime documentation regarding the assembly's specific responsibilities.
* **Legacy Date:** The `AssemblyCopyright` attribute contains the hardcoded year 2008, which may indicate the age of the codebase or a failure to update copyright headers during maintenance.
* **Versioning Scheme:** The version string `"1.06.0081"` uses a non-standard four-part format where the third part (`0081`) appears to represent a build or day number rather than a standard minor revision, which may be relevant for version parsing logic.

View File

@@ -0,0 +1,26 @@
---
source_files:
- Common/DTS.Common.IConnection/IConnection.cs
generated_at: "2026-04-16T11:29:49.435831+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "3e284d4b0962cb4a"
---
# Documentation for `IConnection.cs`
## 1. Purpose
This source file defines the namespace `DTS.Common.IConnection` but currently contains no implementation, type definitions, or logic. Based on the namespace naming convention, it appears intended to house connection-related abstractions (likely interfaces) for the DTS system, but the specific file provided is an empty stub.
## 2. Public Interface
**None.** The file contains no public classes, interfaces, structs, enums, or methods. It consists solely of a namespace declaration and a `using System;` directive.
## 3. Invariants
None identified from source alone. No types exist to enforce constraints upon.
## 4. Dependencies
* **Imports:** `System`
* **Dependents:** Cannot be determined from this file alone. Other projects or files may reference this namespace, but this specific file offers no API for them to consume.
## 5. Gotchas
* **Empty Implementation:** The file is effectively a placeholder. It defines a namespace block but contains no code. Developers should verify if types expected in this namespace are located in other files within the project or if the file is pending implementation.

View File

@@ -0,0 +1,193 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/RESTConnection.cs
- Common/DTS.Common.IConnection/EthernetConnection/EthernetConnection.cs
generated_at: "2026-04-16T11:48:39.886921+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "21dfcca726b35e5d"
---
# Documentation: IConnection Implementations
## 1. Purpose
This module provides two implementations of the `IConnection` interface for network communication within the DTS system. `EthernetConnection` is a full TCP socket wrapper that manages asynchronous socket operations, connection lifecycle, and keep-alive configuration for hardware devices. `RESTConnection` is a stub/skeleton implementation that immediately completes all operations without actual network I/O, designed to satisfy the `IConnection` interface contract for scenarios where REST-based communication replaces traditional socket connections.
---
## 2. Public Interface
### EthernetConnection (DTS.Common)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IsSoftDisconnected { get; private set; }` | Returns `true` if the connection has been soft-disconnected. |
| `bool RequiresKeepAliveReset { get; set; }` | When `true`, `SoftConnect()` performs additional handshake on command port 8200 before connecting. |
| `Socket Sock` | The underlying `System.Net.Sockets.Socket` instance. Publicly accessible. |
| `bool Connected` | Returns `Sock != null && Sock.Connected`. |
| `string ConnectString` | Returns the connection string (format: `"host:port"`). |
| `SocketFlags Flags { get; set; }` | Socket flags used for send/receive operations. |
#### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Raised when `KeepAliveErrorReceived()` is invoked, indicating connection loss. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void Create(string connectString, string hostIPAddress)` | Creates and configures the underlying socket with keep-alive settings. Stores connection parameters. |
| `Socket CreateSock(string connectString, string hostIPAddress)` | Factory method that creates a configured `Socket` with TCP NoDelay, KeepAlive, and buffer sizes from `DFConstantsAndEnums`. Binds to `hostIPAddress` if provided. |
| `void SoftDisconnect()` | If `HardwareConstants.AllowSoftDisconnects` is true, disconnects and disposes the socket, sets `IsSoftDisconnected = true`. |
| `void SoftConnect()` | Reconnects a soft-disconnected socket. Optionally performs keep-alive reset via port 8200 if `RequiresKeepAliveReset` is true. Retries connection up to 3 times. |
| `void KeepAliveErrorReceived()` | Shuts down, closes, and disposes the socket; invokes `OnDisconnected` event. |
| `string GetConnectionData()` | Returns a string with local and remote endpoints, or empty string if unavailable. |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Begins asynchronous connection. Throws if socket is null, `Connect_String` is empty/malformed, or port is invalid. |
| `void EndConnect(IAsyncResult ar)` | Completes the connection. Logs success with endpoints. |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, object state)` | Begins asynchronous disconnect. Throws `SocketException(WSAEISCONN)` if socket is not connected. |
| `void EndDisconnect(IAsyncResult asyncResult)` | Completes the disconnect operation. |
| `IAsyncResult BeginAccept(AsyncCallback callback, object state)` | Begins asynchronous accept for incoming connections. |
| `IConnection EndAccept(IAsyncResult asyncResult)` | Returns a new `EthernetConnection` wrapping the accepted socket. |
| `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Begins asynchronous send. Throws if socket is null, callback is null, or socket is not connected. |
| `int EndSend(IAsyncResult ar)` | Completes the send; returns bytes sent. Sets `Sock = null` on exception. |
| `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Task-based async wrapper over BeginSend/EndSend. |
| `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Begins asynchronous receive. Throws if socket is null or callback is null. |
| `int EndReceive(IAsyncResult ar)` | Completes the receive; returns bytes received. |
| `void Bind(int port)` | Binds socket to local endpoint resolved via DNS. |
| `void Listen(int backlog)` | Starts listening for incoming connections. |
| `void Dispose()` | Disposes the socket and resources. |
---
### RESTConnection (DTS.DASLib.Connection)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IConnection.IsSoftDisconnected` | Always returns `false`. |
| `SocketFlags IConnection.Flags { get; set; }` | Stored value, defaults to `SocketFlags.None`. |
| `string IConnection.ConnectString` | Returns the stored `_ConnectString`. |
| `bool IConnection.Connected` | Returns `_bConnected` (set by `BeginConnect`/`BeginDisconnect`). |
#### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Defined but never invoked in the source. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void IConnection.Create(string connectString)` | Stores `connectString` in `_ConnectString`. |
| `void IConnection.Create(string connectString, string hostIPAddress)` | Stores both parameters in private fields. |
| `IAsyncResult IConnection.BeginConnect(AsyncCallback callback, object callbackObject)` | Sets `_bConnected = true`; returns an already-completed `AsyncNoResult`. |
| `void IConnection.EndConnect(IAsyncResult ar)` | No-op. |
| `IAsyncResult IConnection.BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)` | Sets `_bConnected = false`; returns an already-completed `AsyncNoResult`. |
| `void IConnection.EndDisconnect(IAsyncResult asyncResult)` | No-op. |
| `IAsyncResult IConnection.BeginAccept(AsyncCallback callback, object state)` | Returns an already-completed `AsyncNoResult`. |
| `IConnection IConnection.EndAccept(IAsyncResult asyncResult)` | Returns `this`. |
| `IAsyncResult IConnection.BeginSend(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend, AsyncCallback callback, object callbackObject)` | Returns an already-completed `AsyncNoResult`. |
| `int IConnection.EndSend(IAsyncResult ar)` | Returns `0`. |
| `IAsyncResult IConnection.BeginReceive(byte[] receiveBuffer, int bufferStartOffset, int maxSizeToReceive, AsyncCallback callback, object callbackObject)` | Returns an already-completed `AsyncNoResult`. |
| `int IConnection.EndReceive(IAsyncResult ar)` | Returns `0`. |
| `Task<int> IConnection.SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Task wrapper over BeginSend/EndSend. |
| `void IConnection.Bind(int port)` | No-op (commented as "not really needed"). |
| `void IConnection.Listen(int backlog)` | No-op. |
| `void IConnection.KeepAliveErrorReceived()` | No-op. |
| `void IConnection.SoftConnect()` | No-op. |
| `void IConnection.SoftDisconnect()` | No-op. |
| `string IConnection.GetConnectionData()` | Returns `"$(_ConnectString) - $(_hostIPAddress)"`. |
| `void Dispose()` | Standard dispose pattern; no actual resource cleanup. |
#### Internal Class: AsyncNoResult
An `IAsyncResult` implementation used to represent immediately-completed operations.
| Member | Description |
|--------|-------------|
| `bool IsCompleted` | Returns `true` if `_executionState != PENDING`. |
| `WaitHandle AsyncWaitHandle` | Lazily-created `ManualResetEvent`. |
| `object AsyncState` | Returns the state object passed to constructor. |
| `bool CompletedSynchronously` | Returns `true` if `_executionState == COMPLETED_SYNC`. |
| `void SetCompleted(bool completedSync)` | Transitions from PENDING to COMPLETED_SYNC or COMPLETED_ASYNC; invokes callback. Throws `InvalidOperationException` if already completed. |
---
## 3. Invariants
### EthernetConnection
- **Connect string format**: Must be `"hostname:port"` where port is a valid integer. Validated in `BeginConnect`.
- **Socket creation prerequisite**: `Sock` must be created via `Create()` before calling `BeginConnect`, `BeginSend`, `BeginReceive`, `BeginAccept`, `BeginDisconnect`, `Bind`, or `Listen`. All these methods throw if `Sock` is null.
- **Connection state for send**: `BeginSend` throws if `Sock.Connected` is `false`.
- **Connection state for disconnect**: `BeginDisconnect` throws `SocketException(DFConstantsAndEnums.WSAEISCONN)` if `Sock.Connected` is `false`.
- **Callback requirement**: `BeginSend` and `BeginReceive` throw if callback is null.
- **Soft disconnect gate**: `SoftDisconnect()` and `SoftConnect()` do nothing if `HardwareConstants.AllowSoftDisconnects` is `false`.
- **Keep-alive configuration**: All sockets created via `CreateSock` have keep-alive enabled with values from `DFConstantsAndEnums.LocalKeepAliveTimeOutMS` and `DFConstantsAndEnums.LocalKeepAliveRetryIntervalMS`.
### RESTConnection
- **No actual I/O**: All Begin* methods return immediately with `CompletedSynchronously = true`.
- **Send/Receive return zero**: `EndSend` and `EndReceive` always return `0`.
- **IsSoftDisconnected**: Always `false`.
- **AsyncNoResult state machine**: `SetCompleted` can only be called once; subsequent calls throw `InvalidOperationException`.
---
## 4. Dependencies
### EthernetConnection depends on:
- `DTS.Common.Interface.Connection.IConnection` - Interface being implemented.
- `DTS.Common.Utilities.Logging.APILogger` - Used for logging throughout.
- `DTS.Common.DASResource.DFConstantsAndEnums` - Provides `SendBufferSizeBytes`, `ReceiveBufferSizeBytes`, `LocalKeepAliveTimeOutMS`, `LocalKeepAliveRetryIntervalMS`, `WSAEISCONN`.
- `DTS.Common.Enums.DASFactory` - Namespace imported but no direct usage visible in source.
- `DTS.Common.Enums.Hardware.HardwareConstants.AllowSoftDisconnects` - Controls soft disconnect behavior.
- `System.Net.Sockets.Socket` - Core socket functionality.
- `System.Net.Dns`, `System.Net.IPEndPoint`, `System.Net.IPAddress` - Network addressing.
### RESTConnection depends on:
- `DTS.Common.Interface.Connection.IConnection` - Interface being implemented.
- `DTS.Common.Utilities.Logging` - Namespace imported but no direct usage visible in source.
- `System.Net.Sockets.SocketFlags` - Used for the `Flags` property.
- `System.Threading` - `ManualResetEvent`, `Interlocked`, `Thread.VolatileRead`.
### What depends on these modules:
- Unclear from source alone. Both implement `IConnection`, suggesting consumers depend on that interface rather than concrete types directly.
---
## 5. Gotchas
### EthernetConnection
1. **Dead code in `Create(string connectString)`**: The single-parameter overload contains a commented-out recursive call with the comment `"this is recursive!"`. The method body is effectively empty and does nothing.
2. **Counterintuitive error code in `BeginDisconnect`**: When the socket is *not* connected, `BeginDisconnect` throws `SocketException(WSAEISCONN)`. The constant name suggests "is connected" which is the opposite of the actual condition being checked.
3. **SoftConnect has hardcoded command port logic**: When `RequiresKeepAliveReset` is true, `SoftConnect()` connects to port 8200 and sends `<60,5,4>` before connecting to the actual target port. This appears to be device-specific protocol behavior embedded in the connection class.
4. **Socket is public and mutable**: The `Sock` field is public, allowing external code to modify or replace it, potentially bypassing the class's invariants.
5. **EndSend nullifies socket on exception**: If `EndSend` throws, it sets `Sock = null` before re-throwing. This is not documented and could surprise callers.
6. **Thread.Sleep in SoftConnect/SoftDisconnect**: Both methods use `Thread.Sleep` (50ms and 100ms/1000ms respectively), which blocks the calling thread.
### RESTConnection
1. **No-op implementations**: Most methods do nothing or return immediately. This is by design but could cause confusion if developers expect actual network behavior.
2. **OnDisconnected never raised**: The event is declared but never invoked anywhere in the class.
3. **Namespace mismatch**: The file path suggests `DTS.Common.IConnection` but the namespace is `DTS.DASLib.Connection`. This may indicate a historical refactoring or organizational inconsistency.
4. **Unused imports**: `System.CodeDom`, `System.Collections.Specialized`, `System.Runtime.Remoting.Messaging` are imported but not used in the source.

View File

@@ -0,0 +1,40 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:20.386594+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "21f98ce79850642b"
---
# Documentation: EthernetConnection Assembly Metadata
## 1. Purpose
This source file defines the assembly metadata for the `EthernetConnection` component, which appears to be part of the `DTS.Common.IConnection` subsystem. Its role is to establish the assembly's identity, version, and visibility configuration within the larger application. It provides the manifest information required by the .NET runtime to locate and bind this specific library.
## 2. Public Interface
This file does not contain executable logic or public classes. It strictly defines assembly-level attributes.
* **`AssemblyTitle`**: Set to `"EthernetConnection"`.
* **`AssemblyProduct`**: Set to `"EthernetConnection"`.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
* **`ComVisible`**: Set to `false`. This prevents types within this assembly from being visible to COM components by default.
* **`Guid`**: Set to `"355ff6bb-d823-4853-93aa-4c12fd8c350e"`. This serves as the unique identifier for the assembly if exposed to COM.
## 3. Invariants
* **COM Visibility:** Types within this assembly are not COM-visible by default (`ComVisible(false)`). To expose a specific type to COM, that type must be explicitly marked with `ComVisible(true)`.
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `"1.06.0081"`.
* **Identity:** The `Guid` attribute provides a unique, immutable identifier for the assembly's type library.
## 4. Dependencies
* **Framework Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **System Context:** Based on the file path (`Common/DTS.Common.IConnection/...`), this assembly likely implements an `IConnection` interface or related contracts defined elsewhere in the `DTS.Common` namespace, but the specific implementation details are not present in this file.
## 5. Gotchas
* **Hardcoded Versions:** The version numbers (`1.06.0081`) are hardcoded. While the comments suggest using `*` for auto-incrementing build/revision numbers, this feature is currently disabled.
* **Missing Metadata:** The `AssemblyDescription`, `AssemblyConfiguration`, `AssemblyCompany`, and `AssemblyTrademark` fields are initialized as empty strings. This may complicate automated documentation generation or assembly property inspection in production environments.
* **Legacy Timestamp:** The `AssemblyCopyright` attribute lists 2008, indicating this is a mature or legacy codebase.

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:19.908878+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "344d5d1b6c8a507c"
---
# Documentation: DTS.Common.IConnection
## 1. Purpose
This file serves as the assembly manifest configuration for the `DTS.Common.IConnection` library. It provides versioning, metadata, and COM visibility settings for the compiled assembly. Based on the assembly name `IConnection`, this module is intended to define the contract or interface for connection-related logic within the larger DTS system, though the specific interface definitions are not contained within this configuration file.
## 2. Public Interface
This source file does not contain any public classes, methods, or interfaces. It strictly defines assembly-level attributes.
**Defined Attributes:**
* `AssemblyTitle`: Set to `"IConnection"`.
* `AssemblyDescription`: Empty string.
* `AssemblyConfiguration`: Empty string.
* `AssemblyCompany`: Empty string.
* `AssemblyProduct`: Set to `"IConnection"`.
* `AssemblyCopyright`: Set to `"Copyright © 2008"`.
* `AssemblyTrademark`: Empty string.
* `AssemblyCulture`: Empty string.
* `ComVisible`: Set to `false`.
* `Guid`: Set to `"c8394d57-92d3-4ee1-b2f3-f8fabce0d487"`.
* `AssemblyVersion`: Set to `"1.06.0081"`.
* `AssemblyFileVersion`: Set to `"1.06.0081"`.
## 3. Invariants
* **COM Visibility:** The assembly is explicitly configured with `ComVisible(false)`, ensuring types within this assembly are not exposed to COM components by default.
* **Versioning:** The assembly version (`1.06.0081`) is strictly defined and matches the file version.
## 4. Dependencies
**Internal Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
**External Dependencies:**
* None identified from this source file alone.
## 5. Gotchas
* **Missing Description:** The `AssemblyDescription` attribute is an empty string, which may hinder automatic documentation generation or assembly browsing tools.
* **Legacy Date:** The copyright string indicates a base year of 2008. Developers should verify if this metadata has been maintained or if it reflects the original creation date without updates.
* **Missing Logic:** This file contains only metadata; the actual `IConnection` interface and its members are defined in other files within this project not included in the provided source.

View File

@@ -0,0 +1,84 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/SerialConnection.cs
generated_at: "2026-04-16T11:48:46.182914+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "4992256eaf51da73"
---
# Documentation: DTS.Common.SerialConnection.SerialConnection
## 1. Purpose
The `SerialConnection` class provides a wrapper around `System.IO.Ports.SerialPort` to implement the `IConnection` interface. Its primary role is to abstract serial port communication behind an asynchronous, socket-like API (APM pattern). This allows serial devices to be handled uniformly within a system designed around generic connection interfaces, mimicking the behavior of network sockets for operations like connecting, sending, and receiving data.
## 2. Public Interface
**Class:** `SerialConnection` (implements `IConnection`)
**Properties:**
* `bool Connected { get; }`: Returns the connection state. **Note:** Currently hardcoded to return `false`.
* `bool IsSoftDisconnected { get; }`: Returns `true` if the unit is soft disconnected.
* `string ConnectString { get; }`: Returns the stored port name (`_PortName`).
* `System.Net.Sockets.SocketFlags Flags { get; set; }`: Gets or sets socket flags.
**Events:**
* `EventHandler OnDisconnected`: Event raised upon disconnection.
**Methods:**
* `void Create(string PortName)`: Instantiates the internal `SerialPort` object.
* `void Create(string connectString, string hostIPAddress)`: Overload that currently performs no operation.
* `void SoftConnect()`: Intended to connect the unit; currently empty.
* `void SoftDisconnect()`: Intended to disconnect the unit; currently empty.
* `string GetConnectionData()`: Returns an empty string.
* `double GetCurrentDownloadRate()`: Returns `0.0`.
* `double GetCurrentUploadRate()`: Returns `0.0`.
**Connection Lifecycle (APM Pattern):**
* `IAsyncResult BeginConnect(AsyncCallback cb, object state)`: Opens the serial port. Throws `Exception` if `Port` is null or `_PortName` is empty. Returns `null`.
* `void EndConnect(IAsyncResult ar)`: Validates `Port` exists. Throws `Exception` if null.
**Data Transfer (APM Pattern):**
* `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`: Begins an asynchronous write to the serial port. Throws `Exception` if `Port` or `cb` is null.
* `int EndSend(IAsyncResult ar)`: Completes the asynchronous write. Returns `Port.BytesToWrite`.
* `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`: Task-based async wrapper for `BeginSend`/`EndSend`.
* `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`: Begins an asynchronous read from the serial port. Throws `Exception` if `Port` or `cb` is null.
* `int EndReceive(IAsyncResult ar)`: Completes the asynchronous read. Returns the number of bytes read.
**Server/Socket Mimicry Methods:**
* `IAsyncResult BeginAccept(AsyncCallback callback, Object state)`: Returns `null`. Throws if `Port` is null.
* `IConnection EndAccept(IAsyncResult asyncResult)`: Returns a new instance of `SerialConnection`. Throws if `Port` is null.
* `void Bind(int port)`: No-op. Throws if `Port` is null.
* `void Listen(int backlog)`: No-op. Throws if `Port` is null.
* `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`: Returns `null`. Throws if `Port` is null.
* `void EndDisconnect(IAsyncResult asyncResult)`: No-op. Throws if `Port` is null.
**IDisposable:**
* `void Dispose()`: Disposes the `SerialPort` and suppresses finalization.
## 3. Invariants
* **Null Checks:** Nearly all public methods (except `Create` overloads and disposal methods) throw a `System.Exception` if the protected `Port` field is null.
* **Callback Validation:** `BeginSend` and `BeginReceive` throw a `System.Exception` if the provided `AsyncCallback` is null.
* **Connection String:** `BeginConnect` throws a `System.Exception` if `_PortName` is null or empty.
* **Disposal:** Once `Dispose(bool disposing)` runs, the `Port` is closed and set to null; subsequent calls return immediately.
## 4. Dependencies
* **Dependencies (Imports):**
* `DTS.Common.Interface.Connection`: Defines the `IConnection` interface this class implements.
* `System.IO.Ports`: Provides the underlying `SerialPort` functionality.
* `System`: Basic system types, exceptions, and async patterns.
* `System.Threading.Tasks`: Used for `Task`-based async operations (`SendAsync`).
* **Dependents:** Unknown from source alone (consumers of `IConnection`).
## 5. Gotchas
* **Critical Bug in `Create(string PortName)`:** The method assigns `_PortName` *after* attempting to initialize `Port`.
```csharp
Port = new SerialPort(_PortName); // _PortName is likely null or stale here
_PortName = PortName; // Assigned too late
```
This results in the `SerialPort` being instantiated with an incorrect or empty port name, likely causing connection failures.
* **Hardcoded `Connected` Property:** The `Connected` property is hardcoded to return `false` and is never updated by `BeginConnect` or `EndConnect`. Code relying on this property to verify connectivity will fail.
* **APM Return Values:** `BeginConnect`, `BeginDisconnect`, and `BeginAccept` return `null` instead of a valid `IAsyncResult`. This may break callers expecting a valid state object from standard APM implementations.
* **`EndSend` Return Value:** `EndSend` returns `Port.BytesToWrite` (the number of bytes waiting in the send buffer), not the number of bytes successfully written (which is the standard behavior for socket `EndSend`).
* **Soft Disconnect Implementation:** `SoftConnect` and `SoftDisconnect` are empty methods. The `IsSoftDisconnected` property is initialized to `false` but is never set by any method in the class.
* **No-op Methods:** `Bind`, `Listen`, and `KeepAliveErrorReceived` perform no actions but throw exceptions if `Port` is null, making them effectively validation checks with no side effects.

View File

@@ -0,0 +1,46 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:55.465329+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "387f9fdb03f26ec5"
---
# Documentation: AssemblyInfo.cs (SerialConnection)
## 1. Purpose
This file provides assembly-level metadata and configuration attributes for the `DTS.Common.IConnection.SerialConnection` assembly. It defines the assembly's identity, version information, and COM visibility settings. As a standard `AssemblyInfo.cs` file, it does not contain executable logic but serves as a manifest for the compiled library, presumably handling serial port communication based on the naming conventions.
## 2. Public Interface
This file does not expose any public classes, methods, or functions. It strictly contains assembly-level attributes.
**Attributes Defined:**
* **`AssemblyTitle`**: Set to `"SerialConnection.cs"`.
* **`AssemblyDescription`**: Empty.
* **`AssemblyConfiguration`**: Empty.
* **`AssemblyCompany`**: Empty.
* **`AssemblyProduct`**: Set to `"SerialConnection.cs"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2009"`.
* **`AssemblyCulture`**: Empty (neutral culture).
* **`ComVisible`**: Set to `false`. Types in this assembly are not visible to COM components.
* **`Guid`**: Set to `"8d3a85de-321a-48fb-8f9e-f1d9594ee423"`.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
## 3. Invariants
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are synchronized at `"1.06.0081"`.
* **COM Visibility:** The assembly is explicitly marked as not visible to COM (`ComVisible(false)`); this behavior is constant unless overridden by specific types.
* **Identity:** The assembly is uniquely identified by the GUID `8d3a85de-321a-48fb-8f9e-f1d9594ee423` if exposed to COM in the future.
## 4. Dependencies
* **Internal Imports:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **System Context:** This file is a component of the `DTS.Common.IConnection.SerialConnection` project. The specific runtime dependencies of the assembly logic are not visible in this file.
## 5. Gotchas
* **Misnamed Title/Product:** The `AssemblyTitle` and `AssemblyProduct` attributes are set to `"SerialConnection.cs"`. This appears to be a configuration error where a source filename was entered instead of a human-readable product name (e.g., `"SerialConnection"`).
* **Legacy Date:** The copyright string suggests the code originates from 2009. Developers should verify compatibility with modern .NET runtimes or operating systems, as serial communication APIs can change between framework versions.
* **Empty Description:** The `AssemblyDescription` attribute is empty, providing no inline documentation regarding the specific responsibilities of this assembly.

View File

@@ -0,0 +1,123 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/HIDUSBConnection.cs
generated_at: "2026-04-16T11:51:28.238124+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "4a9eeb7b8043999a"
---
# Documentation: HIDUSBConnection
## 1. Purpose
`HIDUSBConnection` implements the `IConnection` interface to provide asynchronous communication with USB Human Interface Device (HID) hardware. It serves as a bridge between the application layer and USB HID devices manufactured by DTS (Vendor ID `0x1CB9`, Product ID `0x0003`), encapsulating low-level Windows API calls for device discovery, connection management, and data transfer via input/output reports.
---
## 2. Public Interface
### Constants
| Name | Value | Description |
|------|-------|-------------|
| `HIDSLICE_PID` | `0x0003` | Product ID for the target HID device |
| `DTS_VID` | `0x1CB9` | Vendor ID for DTS devices |
### Properties
| Signature | Description |
|-----------|-------------|
| `bool Connected { get; }` | Returns the current connection state (`_Connected`) |
| `string ConnectString { get; }` | Returns the device name (`Device_Name`) |
| `System.Net.Sockets.SocketFlags Flags { get; set; }` | Socket flags property (usage unclear from source) |
| `double GetCurrentDownloadRate()` | Always returns `0D` |
| `double GetCurrentUploadRate()` | Always returns `0D` |
### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Event declared but **never raised** in the source |
### Methods
| Signature | Description |
|-----------|-------------|
| `void Create(string ConnectString)` | Stores the device path in `Device_Name` |
| `void Dispose()` | Public disposal method implementing IDisposable pattern |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Initiates an asynchronous connection attempt |
| `void EndConnect(IAsyncResult ar)` | Completes the connection: opens handles, retrieves device capabilities, configures buffers |
| `static string GetFirstConnectString()` | Scans for the first matching HID device (VID: `DTS_VID`, PID: `HIDSLICE_PID`) and returns its device path |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` | Initiates an asynchronous disconnect |
| `void EndDisconnect(IAsyncResult asyncResult)` | Closes all handles (`_HIDHandle`, `_ReadHandle`, `_WriteHandle`) and sets `_Connected = false` |
| `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Initiates an asynchronous send operation |
| `int EndSend(IAsyncResult ar)` | Writes data to the device in chunks based on `OutputReportByteLength`; returns total bytes sent |
| `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Initiates an asynchronous receive operation |
| `int EndReceive(IAsyncResult ar)` | Reads an input report and copies payload to the buffer; returns `size` on success, `0` on failure |
| `string GetConnectionData()` | Returns an empty string |
| `IAsyncResult BeginAccept(AsyncCallback callback, Object state)` | **Throws `NotSupportedException`** |
| `IConnection EndAccept(IAsyncResult asyncResult)` | **Throws `NotSupportedException`** |
| `void Bind(int port)` | **Throws `NotSupportedException`** |
| `void Listen(int backlog)` | **Throws `NotSupportedException`** |
### Nested Classes
| Name | Description |
|------|-------------|
| `HIDUSBRecAsyncResult` | Implements `IAsyncResult`; contains `buffer`, `offset`, `size` properties for async operations |
| `AUSBRecFix` (private) | Helper class bundling `AsyncCallback` and `HIDUSBRecAsyncResult` for thread pool dispatch |
---
## 3. Invariants
1. **Device Identification**: `GetFirstConnectString()` only recognizes devices with Vendor ID `0x1CB9` and Product ID `0x0003`.
2. **Handle Validity**: `BeginSend` and `BeginReceive` throw if `_ReadHandle` or `_WriteHandle` equals `INVALID_HANDLE_VALUE`.
3. **Report Buffer Structure**: Output reports reserve byte 0 for the report ID (always set to `0`); actual data starts at byte 1.
4. **Input Report Buffer Size**: `InputReportBuffer` is sized to `_MyHID.Capabilities.InputReportByteLength`.
5. **Async Pattern**: All `Begin*` methods queue work via `ThreadPool.QueueUserWorkItem` and require corresponding `End*` calls.
6. **Dispose Guard**: The `disposed` flag prevents double-disposal.
---
## 4. Dependencies
### This Module Depends On
| Namespace/Class | Usage |
|-----------------|-------|
| `DTS.DASLib.Connection.USBFramework.HIDevice` | HID device abstraction, capabilities, input/output reports |
| `DTS.DASLib.Connection.USBFramework.DeviceManagement` | Device enumeration via GUID |
| `DTS.DASLib.Connection.USBFramework.HIDDeclarations` | P/Invoke declarations for `HidD_GetHidGuid`, `HidD_GetAttributes` |
| `DTS.DASLib.Connection.USBFramework.FileIODeclarations` | P/Invoke declarations for `CreateFile`, `CloseHandle`, `SECURITY_ATTRIBUTES` |
| `DTS.DASLib.DASResource.Strings` | Localized error message strings |
| `System.Runtime.InteropServices` | `Marshal.SizeOf` for structure sizing |
### What Depends On This Module
**Unclear from source alone** — the `IConnection` interface suggests this is consumed by a connection abstraction layer, but callers are not visible in this file.
---
## 5. Gotchas
1. **`OnDisconnected` Event Never Raised**: The event is declared but no code path in this file invokes it. Callers should not rely on it for disconnection notification.
2. **`InputReportBuffer` is a Class-Level Field**: This buffer is shared across all receive operations. If multiple `BeginReceive`/`EndReceive` calls overlap, data corruption is possible. Thread safety is unclear.
3. **`EndReceive` Returns `size` on Success, Not Bytes Read**: The method returns `rar.size` (the requested size) rather than the actual number of bytes copied (`InputReportBuffer.Length - 1`). Callers may receive fewer bytes than indicated.
4. **`EndDisconnect` Ignores `CloseHandle` Results**: The `Result` variable from `CloseHandle` calls is captured but never checked. Failures are silently ignored.
5. **`GetCurrentDownloadRate`/`GetCurrentUploadRate` Are Stubbed**: Both always return `0D`. If rate monitoring is required, it is not implemented here.
6. **`GetFirstConnectString` Hardcodes Array Size**: The `DevicePathName` array is fixed at 128 elements. Systems with more than 128 HID devices could fail to find the target.
7. **`EndSend` Chunking Logic**: Data is chunked into `OutputReportByteLength - 1` sized pieces. Each chunk requires a separate write operation; there is no batching optimization.
8. **Exception Handling in `NetCallbackFix`**: Exceptions are shown via `MessageBox.Show`, which blocks the UI thread and is inappropriate for library code.
9. **`Flags` Property is Unused**: The `SocketFlags` property has no apparent purpose in this HID implementation.
10. **`BeginConnect` Does Not Perform Actual Connection**: The connection logic is in `EndConnect`. `BeginConnect` merely queues a callback that immediately invokes the user's `AsyncCallback`.

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:52:31.104928+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "1fcf58774b015c19"
---
# Documentation: HIDUSBConnection Assembly Configuration
## 1. Purpose
This source file defines the assembly metadata for the `USBConnection` component, specifically within the `DTS.Common.IConnection` namespace structure. It exists to configure the manifest of the compiled .NET assembly, setting the version information, title, and COM visibility settings. Its role is strictly limited to build-time configuration; it contains no executable logic.
## 2. Public Interface
This file does not contain any public classes, methods, or functions. It consists entirely of assembly-level attributes used by the compiler.
**Attributes Defined:**
* `AssemblyTitle`: Set to `"USBConnection"`.
* `AssemblyProduct`: Set to `"USBConnection"`.
* `AssemblyCopyright`: Set to `"Copyright © 2008"`.
* `ComVisible`: Set to `false`.
* `Guid`: Set to `"9127ae79-928b-4187-a425-97f49034c5ad"`.
* `AssemblyVersion`: Set to `"1.06.0081"`.
* `AssemblyFileVersion`: Set to `"1.06.0081"`.
## 3. Invariants
* **COM Visibility:** The attribute `[assembly: ComVisible(false)]` dictates that no types within this assembly are visible to COM components by default. This must be explicitly overridden on specific types if COM interop is required.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `"1.06.0081"`.
* **Identity:** The assembly is identified by the GUID `9127ae79-928b-4187-a425-97f49034c5ad` if exposed to COM.
## 4. Dependencies
* **Internal Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **External Dependencies:** None identified from this file alone. The file is a properties file for the `HIDUSBConnection` project.
## 5. Gotchas
* **Legacy Project Format:** This file uses the explicit `AssemblyInfo` style typical of older .NET Framework projects (pre-SDK style). If this project is migrated to a modern SDK-style `.csproj` format, these attributes may conflict with auto-generated values unless `<GenerateAssemblyInfo>false</GenerateAssemblyInfo>` is set in the project file.
* **Hardcoded Versions:** The version string `"1.06.0081"` is hardcoded. Continuous Integration (CI) pipelines looking to inject version numbers dynamically would need to modify this file pre-build or use a different versioning strategy.
* **Empty Metadata:** `AssemblyDescription`, `AssemblyConfiguration`, `AssemblyCompany`, and `AssemblyTrademark` are initialized as empty strings, which may result in missing metadata in the compiled DLL properties.

View File

@@ -0,0 +1,217 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/USBFramework/FileIODeclarations.cs
- Common/DTS.Common.IConnection/USBConnection/USBFramework/HIDDeclarations.cs
- Common/DTS.Common.IConnection/USBConnection/USBFramework/DeviceManagementDeclarations.cs
- Common/DTS.Common.IConnection/USBConnection/USBFramework/DeviceManagement.cs
generated_at: "2026-04-16T11:51:16.904126+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8939bee008e13a9a"
---
# USB Framework Module Documentation
## 1. Purpose
This module provides a .NET wrapper around Windows Win32 APIs for USB device communication and management. It enables applications to discover, monitor, and interact with HID-class USB devices through P/Invoke declarations for `kernel32.dll`, `hid.dll`, `setupapi.dll`, `user32.dll`, and `advapi32.dll`. The module handles device enumeration by GUID, device arrival/removal notifications, and low-level file I/O operations required for USB device communication.
---
## 2. Public Interface
### FileIODeclarations Class
**Namespace:** `DTS.Common.USBFramework`
A container for Win32 file I/O P/Invoke declarations.
**Constants:**
- `GENERIC_READ` (uint): `0x80000000`
- `GENERIC_WRITE` (uint): `0x40000000`
- `FILE_SHARE_READ` (uint): `0x00000001`
- `FILE_SHARE_WRITE` (uint): `0x00000002`
- `FILE_FLAG_OVERLAPPED` (uint): `0x40000000`
- `INVALID_HANDLE_VALUE` (int): `-1`
- `OPEN_EXISTING` (short): `3`
- `WAIT_TIMEOUT` (int): `0x102`
- `WAIT_OBJECT_0` (uint): `0`
- `WAIT_FAILED` (uint): `0xFFFFFFFF`
- `WAIT_ABANDONED` (uint): `0x00000080`
- `FSCTL_SET_COMPRESSION` (int): `0x9C040`
**Structures:**
- `OVERLAPPED` - Sequential layout structure with fields: `Internal`, `InternalHigh`, `Offset`, `OffsetHigh`, `hEvent` (all int)
- `SECURITY_ATTRIBUTES` - Sequential layout structure with fields: `nLength`, `lpSecurityDescriptor`, `bInheritHandle` (all int)
**Static Methods (DllImport kernel32.dll):**
- `int CancelIo(int hFile)`
- `int CloseHandle(int hObject)`
- `int CreateEvent(ref SECURITY_ATTRIBUTES SecurityAttributes, int bManualReset, int bInitialState, string lpName)`
- `int CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, uint dwFlagsAndAttributes, int hTemplateFile)`
- `int GetLastError()`
- `int ReadFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, int lpOverlapped)`
- `uint WaitForSingleObject(int hHandle, int dwMilliseconds)`
- `int WriteFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, int lpOverlapped)`
- `int DeviceIoControl(IntPtr hDevice, int dwIoControlCode, ref short lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped)`
---
### FileIO Class
**Namespace:** `DTS.Common.USBFramework`
Alternative file I/O declarations using `SafeFileHandle`.
**Constants:**
- `FILE_ATTRIBUTE_NORMAL` (short): `0x80`
- `FILE_FLAG_OVERLAPPED` (int): `0x40000000`
- `FILE_SHARE_READ` (short): `0x1`
- `FILE_SHARE_WRITE` (short): `0x2`
- `GENERIC_READ` (uint): `0x80000000`
- `GENERIC_WRITE` (uint): `0x40000000`
- `INVALID_HANDLE_VALUE` (int): `-1`
- `OPEN_EXISTING` (short): `3`
**Structure:**
- `SECURITY_ATTRIBUTES` - Sequential layout with `nLength` (int), `lpSecurityDescriptor` (IntPtr), `bInheritHandle` (int)
**Static Methods (DllImport kernel32.dll):**
- `bool CloseHandle(SafeFileHandle hObject)`
- `SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile)`
---
### HIDDeclarations Class
**Namespace:** `DTS.DASLib.Connection.USBFramework` (Note: different namespace)
A container for HID device P/Invoke declarations.
**Constants:**
- `HidP_Input` (short): `0`
- `HidP_Output` (short): `1`
- `HidP_Feature` (short): `2`
**Structures:**
- `HIDD_ATTRIBUTES` - Fields: `Size` (int), `VendorID` (short), `ProductID` (short), `VersionNumber` (short)
- `HIDP_CAPS` - Fields: `Usage`, `UsagePage`, `InputReportByteLength`, `OutputReportByteLength`, `FeatureReportByteLength`, `Reserved[17]`, `NumberLinkCollectionNodes`, `NumberInputButtonCaps`, `NumberInputValueCaps`, `NumberInputDataIndices`, `NumberOutputButtonCaps`, `NumberOutputValueCaps`, `NumberOutputDataIndices`, `NumberFeatureButtonCaps`, `NumberFeatureValueCaps`, `NumberFeatureDataIndices`
- `HidP_Value_Caps` - Extensive structure with fields for usage page, report ID, bit field, link collection, logical/physical min/max, usage min/max, string min/max, designator min/max, data index min/max, and multiple reserved fields
**Static Methods (DllImport hid.dll):**
- `bool HidD_FlushQueue(int HidDeviceObject)`
- `bool HidD_FreePreparsedData(ref IntPtr PreparsedData)`
- `int HidD_GetAttributes(int HidDeviceObject, ref HIDD_ATTRIBUTES Attributes)`
- `bool HidD_GetFeature(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)`
- `bool HidD_GetInputReport(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)`
- `void HidD_GetHidGuid(ref System.Guid HidGuid)`
- `bool HidD_GetNumInputBuffers(int HidDeviceObject, ref int NumberBuffers)`
- `bool HidD_GetPreparsedData(int HidDeviceObject, ref IntPtr PreparsedData)`
- `bool HidD_SetFeature(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)`
- `bool HidD_SetNumInputBuffers(int HidDeviceObject, int NumberBuffers)`
- `bool HidD_SetOutputReport(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)`
- `int HidP_GetCaps(IntPtr PreparsedData, ref HIDP_CAPS Capabilities)`
- `int HidP_GetValueCaps(short ReportType, ref byte ValueCaps, ref short ValueCapsLength, IntPtr PreparsedData)`
---
### DeviceManagementDeclarations Class
**Namespace:** `DTS.Common.USBFramework`
A container for device management P/Invoke declarations.
**Constants:**
- Device event constants: `DBT_DEVICEARRIVAL` (`0x8000`), `DBT_DEVICEREMOVECOMPLETE` (`0x8004`), `DBT_DEVTYP_DEVICEINTERFACE` (`5`), `DBT_DEVTYP_HANDLE` (`6`)
- Notification constants: `DEVICE_NOTIFY_ALL_INTERFACE_CLASSES` (`4`), `DEVICE_NOTIFY_SERVICE_HANDLE` (`1`), `DEVICE_NOTIFY_WINDOW_HANDLE` (`0`), `WM_DEVICECHANGE` (`0x219`)
- Error constants: `ERROR_INSUFFICIENT_BUFFER` (`122`), `NO_ERROR` (`0`), `ERROR_NO_MORE_ITEMS` (`259`)
- SetupAPI flags: `DIGCF_PRESENT` (`0x00000002`), `DIGCF_DEVICEINTERFACE` (`0x00000010`), `DIGCF_ALLCLASSES` (`0x00000004`)
- Registry property constants: `SPDRP_FRIENDLYNAME`, `SPDRP_DEVICEDESC`, `SPDRP_DRIVER`
**Structures:**
- `DEV_BROADCAST_DEVICEINTERFACE` - Fields: `dbcc_size`, `dbcc_devicetype`, `dbcc_reserved`, `dbcc_classguid` (Guid), `dbcc_name` (string, SizeConst=400)
- `DEV_BROADCAST_DEVICEINTERFACE_1` - Class variant with `dbcc_classguid` as byte[16] and `dbcc_name` as char[255]
- `DEV_BROADCAST_HANDLE` - Fields: `dbch_size`, `dbch_devicetype`, `dbch_reserved`, `dbch_handle`, `dbch_hdevnotify`
- `DEV_BROADCAST_HDR` - Fields: `dbch_size`, `dbch_devicetype`, `dbch_reserved`
- `SP_DEVICE_INTERFACE_DATA` - Fields: `cbSize`, `InterfaceClassGuid` (Guid), `Flags`, `Reserved` (IntPtr)
- `SP_DEVICE_INTERFACE_DETAIL_DATA` - Fields: `cbSize`, `DevicePath` (string)
- `SP_DEVINFO_DATA` - Fields: `cbSize`, `ClassGuid` (Guid), `DevInst`, `Reserved`
**Enum:**
- `RegSAM` - Flags enum with values: `QueryValue`, `SetValue`, `CreateSubKey`, `EnumerateSubKeys`, `Notify`, `CreateLink`, `WOW64_32Key`, `WOW64_64Key`, `WOW64_Res`, `Read`, `Write`, `Execute`, `AllAccess`
**Static Methods:**
- `IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, int Flags)` - user32.dll
- `int SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, int hwndParent)` - setupapi.dll
- `int SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet)` - setupapi.dll
- `int SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, int MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData)` - setupapi.dll
- `IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, string Enumerator, int hwndParent, uint Flags)` - setupapi.dll
- `bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, ref int RequiredSize, IntPtr DeviceInfoData)` - setupapi.dll
- `bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, out SP_DEVINFO_DATA DeviceInfoData)` - setupapi.dll
- `IntPtr SetupDiGetClassDevsA(ref Guid ClassGuid, uint Enumerator, IntPtr hwndParent, uint Flags)` - setupapi.dll
- `bool SetupDiGetDeviceRegistryPropertyA(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, uint Property, uint PropertyRegDataType, StringBuilder PropertyBuffer, uint PropertyBufferSize, IntPtr RequiredSize)` - setupapi.dll
- `int SetupDiOpenDevRegKey(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, uint Scope, uint HwProfile, uint KeyType, RegSAM samDesired)` - setupapi.dll
- `uint RegQueryValueEx(int hKey, string lpValueName, uint lpReserved, out uint lpType, ref byte[] lpData, ref uint lpcbData)` - Advapi32.dll
- `bool UnregisterDeviceNotification(IntPtr Handle)` - user32.dll
- `int GetLastError()` - kernel32.dll
---
### DeviceManagement Class
**Namespace:** `DTS.Common.USBFramework`
Implements `IDisposable`. Provides high-level device management operations.
**Public Methods:**
- `void Dispose()` - Empty implementation; does not release resources.
- `bool DeviceNameMatch(Message m, string mydevicePathName)` - Compares the device path name from a `WM_DEVICECHANGE` message against a specified device path name. Returns `true` if names match (case-insensitive), `false` otherwise. Only processes messages where `dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE`.
- `bool FindDeviceFromGuid(System.Guid myGuid, ref string[] devicePathName)` - Enumerates all present devices matching the specified interface class GUID. Populates `devicePathName` array with device path names. Returns `true` if at least one device is found. Caller must pre-allocate the `devicePathName` array with sufficient size.
- `bool RegisterForDeviceNotifications(IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)` - Registers a window to receive device arrival/removal notifications for a specific device interface class. Returns `true` on success. The `deviceNotificationHandle` is set to the registration handle on success.
- `void StopReceivingDeviceNotifications(IntPtr deviceNotificationHandle)` - Unregisters device notifications. Failures are silently ignored.
- `bool GetDeviceRegistryProperty(Guid myGuid)` - Enumerates devices and logs driver names via `APILogger.Log()`. Returns `true` on success, `false` on error or if no matching device found.
**Static Fields:**
- `IS64_BIT_PROCESS` (bool, readonly) - Computed as `(IntPtr.Size == 8)`
---
## 3. Invariants
- **Handle Validity:** All Win32 handles (`int` or `IntPtr` types) must be valid when passed to API functions. `INVALID_HANDLE_VALUE` (-1) indicates failure from `CreateFile` operations.
- **Structure Size Initialization:** Structures with `cbSize` fields (`SP_DEVICE_INTERFACE_DATA`, `SP_DEVICE_INTERFACE_DETAIL_DATA`, `SP_DEVINFO_DATA`) must have `cbSize` set to `Marshal.SizeOf()` before passing to API functions.
- **Memory Management:** Memory allocated via `Marshal.AllocHGlobal()` must be freed via `Marshal.FreeHGlobal()`. The `FindDeviceFromGuid` method allocates and frees `detailDataBuffer` within its scope.
- **Device Path Array Pre-allocation:** `FindDeviceFromGuid` requires the caller to pre-allocate the `devicePathName` string array; the method does not resize it.
- **32/64-bit Compatibility:** The code conditionally handles pointer arithmetic based on `IS64_BIT_PROCESS` for correct memory offset calculations.
- **Namespace Inconsistency:** `HIDDeclarations` resides in `DTS.DASLib.Connection.USBFramework` while all other classes are in `DTS.Common.USBFramework`.
---
## 4. Dependencies
**External Dependencies (DLL Imports):**
- `kernel32.dll` - File I/O, handles, synchronization
- `hid.dll` - HID device communication
- `setupapi.dll` - Device enumeration and management
- `user32.dll` - Device notification registration
- `Advapi32.dll` - Registry operations
**Internal Dependencies:**
- `Microsoft.Win32.SafeHandles` - Used by `FileIO` class for `SafeFileHandle`
- `System.Runtime.InteropServices` - P/Invoke and marshaling
- `System.Windows.Forms` - `Message` struct used in `DeviceNameMatch`
- `DTS.Common.Utilities.Logging` - `APILogger` used in `DeviceManagement.GetDeviceRegistryProperty`
**Consumers:**
- Not determinable from source alone; this module appears to be a low-level infrastructure layer for USB communication.
---
## 5. Gotchas
1. **Empty Dispose Implementation:** `DeviceManagement.Dispose()` is empty and does not release the `deviceNotificationHandle` or clean up any resources. Callers must explicitly call `StopReceivingDeviceNotifications()` before disposal.
2. **Namespace Mismatch:** `HIDDeclarations` is in `DTS.DASLib.Connection.USBFramework` namespace, while all other classes are in `DTS.Common.USBFramework`. This may cause compilation issues or require multiple using directives.
3. **Duplicate Constants:** `FileIODeclarations` and `FileIO` both define identical constants (`GENERIC_READ`, `GENERIC_WRITE`, `FILE_SHARE_READ`, `FILE_SHARE_WRITE`, `FILE_FLAG_OVERLAPPED`, `INVALID_HANDLE_VALUE`, `OPEN_EXISTING`) with slightly different

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/USBFramework/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:52:05.531680+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f8e1fde835545ec4"
---
# Documentation: USBFramework Assembly Configuration
## 1. Purpose
This source file (`AssemblyInfo.cs`) provides standard .NET assembly metadata for the `HIDFramework` component, which appears to be part of the larger `DTS.Common.IConnection` USB connectivity subsystem. Its primary role is to define the assembly's identity, version, and COM visibility settings during the build process. It serves as the manifest root for this specific library.
## 2. Public Interface
As an assembly information file, this module does not expose traditional methods or classes. Instead, it defines the following assembly-level attributes:
* **`AssemblyTitle`**: Set to `"HIDFramework"`. Defines the friendly name for the assembly.
* **`AssemblyProduct`**: Set to `"HIDFramework"`. Specifies product information for the assembly output.
* **`AssemblyVersion`**: Set to `"1.06.0081"`. Specifies the version number used by the common language runtime.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`. Specifies the file version number displayed on the file properties dialog.
* **`ComVisible`**: Set to `false`. Ensures types within this assembly are not visible to COM components by default.
* **`Guid`**: Set to `"c655f31f-ca6c-4e9b-9480-934762d20a8c"`. Provides a unique identifier for the assembly if exposed to COM.
* **`AssemblyCopyright`**: Set to `"Copyright © 2008"`.
* **`AssemblyDescription`**, **`AssemblyConfiguration`**, **`AssemblyCompany`**, **`AssemblyTrademark`**, **`AssemblyCulture`**: Defined but set to empty strings.
## 3. Invariants
* **COM Visibility:** The attribute `[assembly: ComVisible(false)]` guarantees that no types within this assembly are exposed to COM unless a specific type overrides this with `[ComVisible(true)]`.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are explicitly synchronized to the string `"1.06.0081"`. They do not use auto-increment wildcards.
* **Identity:** The internal identity of the assembly is strictly defined as `HIDFramework` via both `AssemblyTitle` and `AssemblyProduct`.
## 4. Dependencies
* **Internal Dependencies:**
* `System.Reflection`: Required for the assembly attributes.
* `System.Runtime.CompilerServices`: Required for compiler interaction.
* `System.Runtime.InteropServices`: Required for the `ComVisible` and `Guid` attributes.
* **External Dependencies:** None inferred from this file alone. As an AssemblyInfo file, it is a leaf node in the dependency graph, consumed by the compiler during the build of the `HIDFramework` DLL.
## 5. Gotchas
* **Naming Discrepancy:** The file path indicates this project resides in a directory named `USBFramework` (`.../USBConnection/USBFramework/...`), but the `AssemblyTitle` and `AssemblyProduct` attributes explicitly name the output `"HIDFramework"`. This inconsistency between the folder structure and the binary name could cause confusion when referencing the DLL.
* **Empty Metadata:** Several standard metadata fields (`AssemblyDescription`, `AssemblyCompany`) are empty. This may result in missing metadata in the compiled DLL properties, which can be problematic for automated tooling or license management.
* **Legacy Date:** The copyright year is 2008, suggesting this is a legacy codebase. Modern .NET projects often embed this information in the `.csproj` file rather than a separate `AssemblyInfo.cs`.

View File

@@ -0,0 +1,111 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/WINUSBDeviceApi.cs
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/CDCUSBConnection.cs
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/WINUSBConnection.cs
generated_at: "2026-04-16T11:50:38.580755+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2043cd8e3c0f04ef"
---
# Documentation: DTS.Common.WINUSBConnection
## 1. Purpose
This module provides USB connectivity abstractions within the `DTS.Common.WINUSBConnection` namespace. It contains two concrete implementations of the `IConnection` interface: `CDCUSBConnection`, which wraps a standard `System.IO.Ports.SerialPort` for CDC (Communications Device Class) USB devices, and `WINUSBConnection`, which provides low-level communication via the native `winusb.dll` API for custom WinUSB devices. Additionally, it defines the internal P/Invoke signatures and data structures required to interact with the Windows WinUSB driver stack.
## 2. Public Interface
### Class: `CDCUSBConnection`
Implements `IConnection`. Represents a USB device connection via a virtual COM port (CDC).
* **`void Create(string connectString, string hostIPAddress)`**
* Parses the `connectString` to match against registry keys in `RegKeys`. If a match is found, it retrieves the `PortName` from the registry (`Device Parameters` subkey) and configures the internal `SerialPort` instance.
* **`IAsyncResult BeginConnect(AsyncCallback cb, object state)`**
* Initiates an asynchronous connection. Queues the connection logic to the thread pool.
* **`void EndConnect(IAsyncResult ar)`**
* Completes the asynchronous connection. Configures the serial port (BaudRate, DataBits, etc.) and calls `_comPort.Open()`. Sets `Connected` to `true`.
* **`IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous send operation.
* **`int EndSend(IAsyncResult ar)`**
* Completes the send operation. Writes data to the internal `_comPort` using `_comPort.Write`.
* **`Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`**
* Task-based asynchronous wrapper for `BeginSend`/`EndSend`.
* **`IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous receive operation.
* **`int EndReceive(IAsyncResult ar)`**
* Completes the receive operation. Reads data from `_comPort`. **Note:** This method blocks in a loop (`Thread.Sleep(1)`) until at least one byte is read.
* **`IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`**
* Initiates an asynchronous disconnect.
* **`void EndDisconnect(IAsyncResult ar)`**
* Completes the disconnect. Closes and disposes the internal `_comPort`.
* **Properties**
* `bool Connected`: Gets the current connection state.
* `string ConnectString`: Returns the device pathname.
* `IList<string> RegKeys`: Static property that lazily loads registry keys for the device from `SYSTEM\CurrentControlSet\Enum\USB\`.
### Class: `WINUSBConnection`
Implements `IConnection`. Represents a USB device connection using the native WinUSB driver.
* **`void Create(string connectString, string hostIPAddress)`**
* Stores the `connectString` in the `ConnectString` property.
* **`IAsyncResult BeginConnect(AsyncCallback cb, object state)`**
* Initiates an asynchronous connection. Throws `NotConnectedException` if already connected.
* **`void EndConnect(IAsyncResult ar)`**
* Completes the connection. Instantiates a new `WinUsbDevice`, retrieves a device handle via `GetDeviceHandle`, and initializes the device via `InitializeDevice`. Uses a mutex (`_usbConnectionMutex`) to synchronize access.
* **`IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous send. Validates buffer parameters.
* **`int EndSend(IAsyncResult ar)`**
* Completes the send. Checks `MyDevInfo.UseHybridBulkIntMode`. If true, calls `SendViaInterruptTransfer`; otherwise, calls `SendViaBulkTransfer`.
* **`Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`**
* Task-based asynchronous wrapper for `BeginSend`/`EndSend`.
* **`IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous receive.
* **`int EndReceive(IAsyncResult ar)`**
* Completes the receive. Reads data via `ReadViaBulkTransfer`. Blocks in a loop (`Thread.Sleep(1)`) until bytes are read. Returns 0 if the connection fails or closes.
* **`IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`**
* Initiates an asynchronous disconnect.
* **`void EndDisconnect(IAsyncResult ar)`**
* Completes the disconnect. Calls `DisposeSliceDev` to release the WinUSB handle.
* **Properties**
* `bool Connected`: Gets the current connection state.
* `string ConnectString`: Gets the device pathname.
### Internal Class: `WinUsbDevice` (Partial)
Defines P/Invoke signatures and structures for `winusb.dll`.
* **Structs**: `USBConfigurationDescriptor`, `USBInterfaceDescriptor`, `WinUSBPipeInformation`, `WinUSBSetupPacket`.
* **Enums**: `PolicyType`, `USBDPipeTypes`, `USBDeviceSpeeds`.
* **Methods**: `WinUsb_Initialize`, `WinUsb_Free`, `WinUsb_ControlTransfer`, `WinUsb_ReadPipe`, `WinUsb_WritePipe`, `WinUsb_QueryPipe`, `WinUsb_SetPipePolicy`, etc.
## 3. Invariants
* **Registry Dependency (CDCUSBConnection)**: The `CDCUSBConnection` requires the device to be registered under `SYSTEM\CurrentControlSet\Enum\USB\` with a Vendor ID of `VID_1CB9` and Product ID of `PID_001A`. The `Create` method cannot resolve the port name if these registry keys are missing.
* **Thread Safety (WINUSBConnection)**: The `WINUSBConnection.EndConnect` and `DisposeSliceDev` methods rely on a named Mutex (`"USBConnection"`) to prevent race conditions during device initialization and disposal.
* **Disposal State**: Both connection classes track `Disposed` and `Disposing` flags. Methods generally do not proceed if `Disposed` is true.
* **APM Pattern**: Both classes implement the Asynchronous Programming Model (APM) using internal `IAsyncResult` implementations (`UsbRecAsyncResult` and `WinUSBRecAsyncResult`). Callbacks are invoked via `ThreadPool.QueueUserWorkItem`.
## 4. Dependencies
### Internal Dependencies
* `DTS.Common.Interface.Connection`: Implements `IConnection`.
* `DTS.Common.DASResource`: Uses localized strings for exception messages (e.g., `Strings.CDCUSBConnection_BeginConnect_Err1`).
* `DTS.Common.Utilities.Logging`: Uses `APILogger` for logging exceptions and status messages.
* `DTS.Common.USBFramework`: Uses `DeviceManagement` class (in `WINUSBConnection`).
* `DTS.Common.Classes.Connection`: Uses `NotConnectedException`.
### External Dependencies
* `System.IO.Ports`: Used by `CDCUSBConnection` for `SerialPort`.
* `System.Runtime.InteropServices`: Used for P/Invoke attributes.
* `Microsoft.Win32`: Used for registry access (`RegistryKey`, `SafeFileHandle`).
* `winusb.dll`: Native Windows DLL imported by `WinUsbDevice`.
## 5. Gotchas
* **Blocking Async Reads**: The `EndReceive` methods in both `CDCUSBConnection` and `WINUSBConnection` contain `while` loops that sleep (`Thread.Sleep(1)`) if zero bytes are read. This effectively makes the "asynchronous" operation blocking and consumes a thread pool thread while waiting for data.
* **Recursive Comment**: The `Create(string connectString)` method in both connection classes contains a commented-out line `//Create(connectString);` with a note "this is recursive!". This suggests a historical bug or confusion regarding method overloads.
* **Empty Soft Disconnect**: `SoftConnect` and `SoftDisconnect` methods are implemented but empty. The comments explicitly state they do nothing because there is no soft disconnect option implemented.
* **Hardcoded Device IDs**: `CDCUSBConnection` hardcodes `DTS_VENDOR_ID` (0x1CB9) and `DTS_TSR2_CDCUSB_PRODUCT_ID_STR` ("PID_001A"). It will not work with other USB devices.
* **Partial Class Source**: `WinUsbDevice` is defined as `internal sealed partial class`. The logic for `GetDeviceHandle`, `InitializeDevice`, `SendViaBulkTransfer`, etc., is referenced in `WINUSBConnection` but is **not present in the provided source files** (likely in another file part of the partial class definition).
* **Hybrid Mode Logic**: `WINUSBConnection.EndSend` switches between interrupt and bulk transfers based on a boolean `UseHybridBulkIntMode` located on a `MyDevInfo` object. The definition of `MyDevInfo` is not visible in the provided source.

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:51:53.479173+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8875c5ea92f3aea7"
---
# Documentation: WINUSBConnection Assembly Info
## 1. Purpose
This file configures assembly-level metadata for the `WINUSBConnection` component within the `DTS.Common.IConnection` namespace. It establishes the assembly's identity, version, and COM visibility settings, serving as the manifest definition for the compiled output. This module exists to provide versioning and attribution information for the WinUSB connection library.
## 2. Public Interface
This file contains no executable public classes, methods, or functions. It strictly defines assembly-level attributes using C# attribute syntax.
**Defined Attributes:**
* **`AssemblyTitle`**: Set to `"WINUSBConnection"`.
* **`AssemblyDescription`**: Set to an empty string.
* **`AssemblyConfiguration`**: Set to an empty string.
* **`AssemblyCompany`**: Set to an empty string.
* **`AssemblyProduct`**: Set to `"WINUSBConnection"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2008"`.
* **`AssemblyTrademark`**: Set to an empty string.
* **`AssemblyCulture`**: Set to an empty string.
* **`ComVisible`**: Set to `false`. Prevents types in this assembly from being visible to COM components.
* **`Guid`**: Set to `"F3C369E6-BFFB-41bc-B8E8-A31094CED447"`. Identifies the Type Library ID if the project is exposed to COM.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
## 3. Invariants
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are explicitly synchronized at `"1.06.0081"`.
* **COM Visibility:** The assembly is explicitly marked as not visible to COM (`ComVisible(false)`). This must be overridden at the type level if specific types need COM exposure.
* **Identity:** The `Guid` attribute provides a unique identifier for this specific assembly's type library.
## 4. Dependencies
* **Imports:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **Consumers:** Any project or reference that depends on the `WINUSBConnection` assembly relies on this file for correct versioning and assembly identity resolution.
## 5. Gotchas
* **Missing Metadata:** The `AssemblyDescription`, `AssemblyCompany`, and `AssemblyConfiguration` attributes are empty. This may result in missing information in assembly property dialogs or automated documentation generation.
* **Legacy Date:** The `AssemblyCopyright` attribute lists the year 2008. It is unclear if this is historical or if the metadata has not been updated to reflect current ownership/year.
* **Hardcoded Version:** The version `1.06.0081` is hardcoded. Unlike the commented-out suggestion in the source (`"*"` for auto-generation), the build and revision numbers are fixed, requiring manual updates for new releases.

View File

@@ -0,0 +1,96 @@
---
source_files:
- Common/DTS.Common.ISO/IsoMDBFile.cs
- Common/DTS.Common.ISO/ISerializableFile.cs
- Common/DTS.Common.ISO/AbstractOLEDbWrapper.cs
- Common/DTS.Common.ISO/HardwareChannel.cs
- Common/DTS.Common.ISO/IsoCode.cs
- Common/DTS.Common.ISO/TestObjectChannel.cs
- Common/DTS.Common.ISO/CalculatedValueClass.cs
- Common/DTS.Common.ISO/LevelTriggerChannel.cs
- Common/DTS.Common.ISO/TestSetting.cs
- Common/DTS.Common.ISO/TestObjectTemplate.cs
- Common/DTS.Common.ISO/MMEFilterClasses.cs
- Common/DTS.Common.ISO/MMEPositions.cs
- Common/DTS.Common.ISO/MMEFineLocations2.cs
generated_at: "2026-04-16T11:35:02.794204+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8371f072462a5521"
---
# Documentation: DTS.Common.ISO
## 1. Purpose
The `DTS.Common.ISO` namespace provides data structures and utilities for managing test configuration entities, specifically adhering to ISO 13499 (MME - Measurement of Mechanical Effects) standards. It serves as a bridge between raw database records (accessed via OLE DB/SQL) and domain objects used in the application's test setup and execution logic. The module handles the serialization of test settings, definition of hardware and calculated channels, and parsing of ISO metadata such as filter classes, positions, and fine locations.
## 2. Public Interface
### **AbstractOLEDbWrapper**
An abstract base class providing helper methods for safe database value retrieval.
* `protected static long GetLong(IDataReader reader, string field)`: Returns `long.MinValue` if the database field is `DBNull`, otherwise converts the value to `long`.
* `protected static DateTime GetDate(IDataReader reader, string field)`: Returns `DateTime.MinValue` if the database field is `DBNull`, otherwise casts to `DateTime`.
### **HardwareChannel**
Represents a physical hardware channel, inheriting from `DASChannelDBRecord`.
* `public Hardware ParentDAS`: Gets or sets the parent hardware device.
* `public static int PhysicalCompare(HardwareChannel left, HardwareChannel right)`: Comparison function based on `ChannelIdx`. Handles nulls.
* `public void Insert()`: Inserts the record into the database via `DbOperations.DASChannelsInsert`.
* `public bool IsSupported(SensorConstants.BridgeType bridge)`: Checks if a specific bridge type is supported using bitwise comparison against `SupportedBridges`.
### **IsoCodeStatics**
Static helper class for generating ISO code strings.
* `public static string GetString(MMEPossibleChannels channel, MMETestObjects container, MMEPositions position, MMEFilterClasses fc)`: Constructs an ISO code string from various metadata objects.
* `public static string GetString(MMEPossibleChannels channel, bool careAboutTestTimeFields)`: Constructs an ISO code string, optionally masking "test time" fields (TestObject, FilterClass) with placeholder characters.
* `public static string GetString(string testObject, string position, string main, string floc1, string floc2, string floc3, string physdim, string dir, string fc)`: Constructs an ISO code string from raw string components.
### **TestObjectChannel**
Represents a channel within a test object, implementing `IComparable<TestObjectChannel>` and `IGroupChannel`.
* `public bool Disabled`: Determines if the channel is used in data collection.
* `public int ChannelIdx`: Index of the channel, defaults to `CHANNEL_IDX_UNKNOWN` (-1).
* `public string SensorSerialNumber`: Serial number of the associated sensor.
* `public string HardwareId`: Physical hardware channel ID. The setter parses and reformats strings containing underscores.
* `public string GetGraphId()`: Returns the ID, appending `Constants.CURRENT_SUFFIX` if `SquibChannelType` is `Current`.
* `public string GetId()`: Returns a composite ID string (`SerialNumber_ChannelType_Id`).
* `public string GetDASId()`: Extracts the DAS ID portion from `HardwareId`.
* `public int CompareTo(TestObjectChannel right)`: Sorts by `DisplayOrder`, then `Name`, then `TestObject` serial number.
### **CalculatedValueClass**
Represents a calculated/derived channel (e.g., HIC, IRTRACC), inheriting from `CalculatedChannelRecord`.
* `public bool SupportsRealtime`: Returns true if `ViewInRealtime` is true.
* `public bool IsValid(Dictionary<string, bool> channelIdLookup)`: Validates that the channel has a name and all `InputChannelIds` exist in the provided lookup.
* `public bool ViewInRealtime`: Getter returns `false` for specific operations (`IRTRACC3D`, `HIC`), regardless of the backing field value.
* `public bool CanChangeViewInRealtime`: Returns `false` for operations that force `ViewInRealtime` to false.
* `public void ReplaceInputChannelIdAtIndex(int index, string newId)`: Modifies the input channel ID array at a specific index.
### **LevelTriggerChannel**
Defines trigger conditions based on signal levels.
* `public LevelTriggerChannel(System.Data.DataRow dr)`: Constructs the object by parsing fields from a database row using `DbOperations.LevelTriggers.Fields`.
* `public string LevelTriggerText`: Getter that generates a human-readable description of the trigger logic (e.g., "Less than X", "Trigger Inside [X, Y]").
### **TestSetting & TestSettingDictionary**
Manages test configuration settings.
* `TestSetting`
* `public string ToSerializeString()`: Serializes the setting to "Id=Value" format, escaping equals signs.
* `public static bool TryParse(string s, out TestSetting ts)`: Parses a serialized string back into a `TestSetting`.
* `TestSettingDictionary`
* `public string GetValue(int id, string defaultValue)`: Retrieves a value or returns the default.
* `public void SetValue(TestSetting setting)`: Initializes a setting in the dictionary.
* `public void SetValue(int id, string value)`: Sets a value, creating a new `TestSetting` if the ID doesn't exist.
* `public void LoadSettings(string s)`: Deserializes a string of settings into the dictionary.
### **MMEFilterClasses, MMEPositions, MMEFineLocations2**
Classes mapping to ISO 13499 metadata database tables.
* `public static [Type][] Get[Types]()`: Static method (e.g., `GetFilterClasses`, `GetPositions`) that queries the database using `DbOperations.GetISOCommand()` and returns an array of objects.
* `public static [Type] ReadXML(XmlElement node)`: Static method to instantiate the object from an XML node attribute mapping.
### **TestObjectTemplate**
Wrapper for group templates.
* `public bool IsISOMode()`: Returns `true` if `TestObjectType` does not contain specific non-ISO constants.
* `public static TestObjectTemplate GetTemplate(ref ISO13499FileDb db, string name)`: **Currently returns null.**
## 3. Invariants
* **Database Null Handling**: `AbstractOLEDbWrapper` derivatives guarantee that `DBNull` values are converted to `long.MinValue` or `DateTime.MinValue`, never throwing conversion exceptions for null fields.
* **Realtime Calculation Constraints**: For `CalculatedValueClass`, if the `Operation` is `IRTRACC3D`, `IRTRACC3D_ABDOMEN`, `IRTRACC3D_LOWERTHORAX`, or `HIC`, `ViewInRealtime` will always return `false` and `CanChangeViewInRealtime` will always return `false`.
* **HardwareChannel Comparison**: `HardwareChannel.Physical

View File

@@ -0,0 +1,66 @@
---
source_files:
- Common/DTS.Common.Import/ImportError.cs
- Common/DTS.Common.Import/ParseProcessor.cs
- Common/DTS.Common.Import/TsetSetupImportSensorInfo.cs
- Common/DTS.Common.Import/CsvUtil.cs
- Common/DTS.Common.Import/ImportNotification.cs
- Common/DTS.Common.Import/XMLParseProcessor.cs
- Common/DTS.Common.Import/CalibrationImport.cs
- Common/DTS.Common.Import/GroupHelper.cs
- Common/DTS.Common.Import/ImportObject.cs
generated_at: "2026-04-16T11:29:51.864320+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "e94d77a26e8f0798"
---
# Documentation: DTS.Common.Import
## 1. Purpose
The `DTS.Common.Import` namespace provides the infrastructure for parsing and importing test configuration data (sensors, calibrations, groups, test setups) into the system. It defines `ImportObject` as the central data transfer object that accumulates state during the import process. The module includes orchestration processors for handling files (CSV and XML), utility classes for data normalization and calibration logic, and notification mechanisms to report progress and errors to the UI or calling application.
## 2. Public Interface
### Classes
#### `ImportObject`
The primary state container for an import operation. It holds collections of sensors, calibrations, hardware, groups, and lookup dictionaries.
* **Properties**:
* `SourceFormat`: Gets or sets the `ImportFormats` enum value.
* `TestSetupImportFileFormat`: Gets or sets the `ImportFileFormat` (Single, Multiple, No TestSetup).
* **Methods**:
* `AddSensor(SensorData sensorData)` / `AddSensors(IEnumerable<SensorData> sensorsData)`: Adds sensors to the import list.
* `AddCalibration(SensorCalibration sensorCalibration)` / `AddCalibrations(...)`: Adds calibration records.
* `AddTestSetup(TestTemplate testTemplate)` / `AddTestSetups(...)`: Adds test setups.
* `AddError(ImportError d)` / `AddErrors(IEnumerable<ImportError> d)`: Registers import errors.
* `AssignParseParameters(ParseParameters parseParameters)`: Assigns parameters used during parsing.
* `GetSensorLookup()`: Returns a `IReadOnlyDictionary<int, ISensorData>` mapped by `DatabaseId`. Logs duplicates to `System.Diagnostics.Trace`.
* `GetImportFileFormat()`: Returns `ImportFileFormat` based on the count of test setups.
#### `ParseProcessor`
Orchestrates the parsing of files using a list of `IParseVariant` implementations.
* **Constructor**: `ParseProcessor(ImportObject importObject, IEnumerable<string> fileNames, IEnumerable<IParseVariant> parseVariants)`
* **Methods**:
* `Process()`: Iterates through `fileNames` and `parseVariants`, executing `variant.Parse(ref _importObject)`. Returns the modified `ImportObject`.
#### `XMLParseProcessor`
Orchestrates XML file parsing with progress notification and cancellation support.
* **Constructor**: `XMLParseProcessor(ImportObject importObject, IImportNotification importNotification, IEnumerable<string> fileNames, Func<bool> isCancelled, bool skipNormalizing)`
* **Properties**:
* `UIItems`: List of `IUIItems` used by the parser factory.
* **Methods**:
* `Process()`: Invokes `XmlParserFactory.CreateXMLParsers`, executes parsing, and reports progress via `IImportNotification`. Progress is calculated based on the sum of counts of various imported entities (Calibrations, Sensors, Groups, etc.).
#### `CalibrationImport`
Implements `ICalibrationImport` to manipulate sensor calibration data.
* **Methods**:
* `CheckForExcitationCalibration(SensorCalibration sc, ...)`: Adds a new `CalibrationRecord` if the excitation type does not match the first record.
* `AddLinearCalRecordIfNeeded(SensorCalibration sc, ...)`: If only one record exists, adds a second linear record and adjusts `IsProportional`/`RemoveOffset` flags.
* `AddLinearZeroMethodIfNeeded(SensorCalibration sc, ...)`: Adds a second `ZeroMethod` if only one exists.
#### `CsvUtil`
Static utility class for CSV file handling.
* **Methods**:
* `CreateCsvReader(string filename)`: Creates a `CsvReader` wrapping a `StreamReader` for the given file.

View File

@@ -0,0 +1,110 @@
---
source_files:
- Common/DTS.Common.Import/DatabaseLocks/LockImportGroups.cs
- Common/DTS.Common.Import/DatabaseLocks/LockImportTestSetups.cs
- Common/DTS.Common.Import/DatabaseLocks/LockImportSensors.cs
generated_at: "2026-04-16T11:44:27.973248+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "95ed39e21f5416a3"
---
# Documentation: DTS.Common.Import.DatabaseLocks
## 1. Purpose
This module provides a concurrency control mechanism for the import process, ensuring that database entities (Groups, TestSetups, and Sensors) are not modified by multiple users simultaneously. It implements the `ILockImport` interface to manage the lifecycle of database locks: acquiring them before an import operation, detecting contention (locks held by other users), handling "stranded" locks (expired locks), and releasing locks upon completion. It enforces permissions for lock stealing, restricting the ability to forcefully take locks to administrative users.
## 2. Public Interface
The module consists of three concrete classes, all implementing `ILockImport`.
### Class: `LockImportGroups`
Manages locking for static group entities.
* **Constructor**: `LockImportGroups(User currentUser, double strandedLockTimeoutMinutes)`
* Initializes the locker with the user context and the threshold for considering a lock "stranded" (expired).
* **Property**: `bool Contended`
* Returns `true` if any group attempted to be locked is currently held by another user; otherwise `false`.
* **Method**: `void FreeLock(ref ImportObject importObject)`
* Releases all groups currently stored in the internal `_lockedGroups` list by calling `LockManager.FreeLock`. Note that the `importObject` parameter is ignored in the implementation.
* **Method**: `void SetLock(ref ImportObject importObject, ref StringBuilder message)`
* Iterates over `importObject.StaticGroups()`. Attempts to lock each group.
* If a lock fails because the item is not found (`LockError.ITEM_NOT_FOUND`), it skips the item.
* If a lock is held by the current user (matching `UserName` and `MachineName`) or is expired (`LastUpdated` + `_strandedLockTimeoutMinutes` < `DateTime.Now`), it forcefully claims the lock.
* Populates `_contendedGroups` if locks are held by others. Appends contention details to the `message` StringBuilder.
* **Method**: `bool StealLock(bool proceed)`
* Attempts to forcefully take locks listed in `_contendedGroups`.
* Returns `false` if locks are contended and the user is not an Admin (`!_currentUser.IsAdmin`).
* Returns `false` if locks are contended and `proceed` is `false`.
* Returns `true` if no contention exists or if the steal operation proceeds successfully.
### Class: `LockImportTestSetups`
Manages locking for test setup entities.
* **Constructor**: `LockImportTestSetups(User currentUser, double strandedLockTimeoutMinutes)`
* **Property**: `bool Contended`
* Returns `true` if `_contendedTests` contains any items.
* **Method**: `void FreeLock(ref ImportObject importObject)`
* Releases locks for items in `_lockedTests`.
* **Method**: `void SetLock(ref ImportObject importObject, ref StringBuilder message)`
* Iterates over `importObject.TestSetups()`. Logic mirrors `LockImportGroups` regarding expiration, ownership checks, and contention handling.
* **Method**: `bool StealLock(bool proceed)`
* Logic mirrors `LockImportGroups` regarding Admin checks and the `proceed` flag.
### Class: `LockImportSensors`
Manages locking for sensor entities.
* **Constructor**: `LockImportSensors(User currentUser, double strandedLockTimeoutMinutes)`
* **Property**: `bool Contended`
* Returns `true` if `_contendedSensors` contains any items.
* **Method**: `void FreeLock(ref ImportObject importObject)`
* Releases locks for items in `_lockedSensors`.
* **Method**: `void SetLock(ref ImportObject importObject, ref StringBuilder message)`
* **Difference from other classes:** It first retrieves all sensors via `SensorsCollection.SensorsList.GetAllSensors(true)` and creates a dictionary lookup.
* Iterates `importObject.Sensors()`. Skips locking if the serial number is not found in the lookup.
* Logic mirrors other classes for handling existing/expired locks.
* **Method**: `bool StealLock(bool proceed)`
* Logic mirrors `LockImportGroups` regarding Admin checks and the `proceed` flag.
## 3. Invariants
1. **Admin Requirement for Stealing**: The `StealLock` method will always return `false` if `_contendedGroups` (or equivalent) is populated and `_currentUser.IsAdmin` is `false`.
2. **Lock Ownership Identity**: A lock is considered "owned" by the current user in `SetLock` only if both `existingLock.LockingUserName` matches `_currentUser.UserName` AND `existingLock.LockingMachineName` matches `Environment.MachineName`.
3. **State Reset**: Calling `SetLock` always clears the internal locked and contended lists (`_lockedGroups`, `_contendedGroups`, etc.) before processing new locks.
4. **Stranded Lock Calculation**: A lock is considered stranded/eligible for reclamation if `existingLock.LastUpdated.AddMinutes(_strandedLockTimeoutMinutes) < DateTime.Now`.
5. **Exception Handling**: In `SetLock` methods, if an exception occurs during the locking loop for a specific item, it is logged via `APILogger.Log(ex)` and the loop continues to the next item; the import process is not halted by a single locking failure.
## 4. Dependencies
### Internal Dependencies (Referenced in Source)
* `DTS.Common.Classes.Locking`: Provides `LockManager`, `LockRecord`, `LockError`.
* `DTS.Common.Import.Interfaces`: Defines `ILockImport`.
* `DTS.Common.SharedResource.Strings`: Provides `StringResources` for user messages.
* `DTS.Common.Storage`: Likely defines `ImportObject`.
* `DTS.Common.Utilities.Logging`: Provides `APILogger`.
* `DTS.Slice.Users`: Provides the `User` class.
* `DTS.SensorDB`: Provides `SensorsCollection` (used specifically in `LockImportSensors`).
### External Dependencies (Inferred)
* `System`, `System.Collections.Generic`, `System.Linq`, `System.Text`.
### Dependents
* Unknown from source alone. Presumably, an Import Manager or Controller class instantiates these lockers to orchestrate import operations.
## 5. Gotchas
1. **Incorrect Item Category in `StealLock` (Bug)**:
In both `LockImportGroups.StealLock` and `LockImportTestSetups.StealLock`, the code calls `LockManager.LockItem` with `LockManager.ItemCategories.Sensor`.
* *Source Evidence*: `LockImportGroups.cs` line 93 and `LockImportTestSetups.cs` line 90.
* *Impact*: When stealing a lock for a Group or TestSetup, the new lock is incorrectly recorded in the database with the "Sensor" category. `LockImportSensors` uses the correct category.
2. **Incorrect Error Message in `LockImportSensors`**:
In `LockImportSensors.SetLock`, when appending contention details to the message, the code uses `StringResources.ImportTestSetup_TestsLocked`.
* *Source Evidence*: `LockImportSensors.cs` line 76.
* *Impact*: Users importing sensors will receive an error message intended for Test Setups.
3. **Unused Parameter in `FreeLock`**:
The `FreeLock` method signature includes `ref ImportObject importObject`, but the implementation in all three classes ignores this parameter entirely. It relies strictly on the internal list (`_lockedGroups`, etc.) populated during `SetLock`. Passing a different `ImportObject` to `FreeLock` than was passed to `SetLock` will have no effect; the locks released are determined solely by the previous `SetLock` call.
4. **Silent Failures**:
The `SetLock` methods catch all exceptions, log them, and continue. If `LockManager` throws an unexpected exception (e.g., database connection failure), the import process will proceed for remaining items, potentially resulting in a partial lock state without a clear indication to the caller other than the log file.

View File

@@ -0,0 +1,105 @@
---
source_files:
- Common/DTS.Common.Import/Factories/CSVTestParserFactory.cs
- Common/DTS.Common.Import/Factories/DatabaseLocksFactory.cs
- Common/DTS.Common.Import/Factories/CSVSensorParserFactory.cs
- Common/DTS.Common.Import/Factories/SaveVariantFactory.cs
- Common/DTS.Common.Import/Factories/XmlParserFactory.cs
generated_at: "2026-04-16T11:45:43.783393+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "23d838f43f91b04f"
---
# Documentation: DTS.Common.Import.Factories
## 1. Purpose
This module provides factory classes for creating parsers, database locks, and persistence handlers for the DTS import system. It centralizes object creation logic for CSV parsing (tests and sensors), XML parsing across different schema versions, database locking mechanisms, and save operation variants. The factories enable version-specific parsing strategies and conditional object creation based on the presence of data in `ImportObject`.
---
## 2. Public Interface
### CSVTestParserFactory
| Method | Signature | Description |
|--------|-----------|-------------|
| `CreateCSVParsers` | `public static IParseCSVTest[] CreateCSVParsers()` | Creates an array of CSV test parsers for versions 0, 5, and 6. Returns parsers in order: Version0, Version5, Version6. |
### DatabaseLocksFactory
| Method | Signature | Description |
|--------|-----------|-------------|
| `Create` | `public static List<ILockImport> Create(ImportObject importObject, User user, double strandedLockTimeoutMinutes)` | Creates lock objects for import operations based on data present in `importObject`. Conditionally creates `LockImportTestSetups`, `LockImportSensors`, and `LockImportGroups` if corresponding data collections are non-empty. |
### CSVSensorParserFactory
| Method | Signature | Description |
|--------|-----------|-------------|
| `CreateCSVParsers` | `public static IReadOnlyDictionary<int, IParseCSVSensor> CreateCSVParsers(ICalibrationImport import, ZeroMethodOptions zmOptions, IImportNotification importNotification, bool importCreateDynamicGroups, bool useISOCodeFilterMapping, bool useZeroForUnfiltered)` | Creates a dictionary of CSV sensor parsers keyed by version number. Includes versions 0, 2, 3, and 4. Each parser is initialized with the provided parameters before being added to the dictionary. |
### SaveVariantFactory
| Method | Signature | Description |
|--------|-----------|-------------|
| `CreateVariants` | `public static List<IPersistImport> CreateVariants(ImportObject importObject, ImportNotification importNotification, User user, Func<bool> isCanceled, bool showCheckoutButton)` | Creates a list of persistence handlers based on data present in `importObject`. Handlers are created conditionally for: `CustomerDetails`, `TestEngineerDetails`, `LabDetails`, `SensorModels`, `Sensors` (with CSV vs non-CSV variants), `Users`, `GlobalSettings`, `Hardware`, `GroupTemplates`, `Groups`, and `TestSetups`. When `showCheckoutButton` is true, also creates a `SaveCheckoutTestSetup`. |
### XmlParserFactory
| Property/Method | Signature | Description |
|-----------------|-----------|-------------|
| `UIItems` | `public static List<IUIItems> UIItems { get; set; }` | Static property for UI items used during XML parsing. |
| `ImportNotification` | `public static IImportNotification ImportNotification { get; set; }` | Static property for import notifications. |
| `CreateXMLParsers` | `public static IEnumerable<IParseVariant> CreateXMLParsers(string fileName, IImportNotification importNotification, Func<bool> isCanceled, bool skipNormalizing)` | Creates XML parsers based on the file's import version. Routes to `LessThan20XMLVersion` for versions below `FileUtils.DataPRO20XmlVersion`, otherwise uses `GreaterOrEqual20XMLVersion`. |
---
## 3. Invariants
1. **Version-based dispatch**: `XmlParserFactory` uses `FileUtils.DataPRO20XmlVersion` as the threshold to select between pre-2.0 and 2.0+ parsing strategies.
2. **Conditional creation**: `DatabaseLocksFactory.Create` and `SaveVariantFactory.CreateVariants` only create handlers/locks when the corresponding data collections in `ImportObject` contain elements (checked via `.Any()`).
3. **Parser version keys**: `CSVSensorParserFactory.CreateCSVParsers` uses each parser's `Version` property as the dictionary key, guaranteeing unique keys per parser type.
4. **Shared progress calculation**: `SaveVariantFactory.CreateVariants` uses a single `PersistCalculator` instance across all save handlers, with counts accumulated via `AddToTotal()` before handlers are added to the list.
5. **Order-dependent processing**: Save handlers are added in a specific sequence (CustomerDetails → TestEngineerDetails → LabDetails → SensorModels → Sensors → Users → GlobalSettings → Hardware → GroupTemplates → Groups → TestSetups).
6. **Test setup naming convention**: When `showCheckoutButton` is true, test setup names are suffixed with `Serialization.RDF.File.SUFFIX_RUNTEST` and checkout setups with `Serialization.RDF.File.SUFFIX_CHECKOUT`.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Import.Interfaces``IParseCSVTest`, `IParseCSVSensor`, `ILockImport`, `IPersistImport`, `IParseVariant`, `ICalibrationImport`, `IImportNotification`, `IUIItems`
- `DTS.Common.Import.Parsers.CSV``Version0CSVTestParser`, `Version5CSVTestParser`, `Version6CSVTestParser`, `Version0CSVSensorParser`, `Version2CSVSensorParser`, `Version3CSVSensorParser`, `Version4CSVSensorParser`
- `DTS.Common.Import.DatabaseLocks``LockImportTestSetups`, `LockImportSensors`, `LockImportGroups`
- `DTS.Common.Import.Persist``PersistCalculator`, `SaveCustomerDetails`, `SaveTestEngineerDetails`, `SaveLabDetails`, `SaveSensorModels`, `SaveCsvSourceSensor`, `SaveNonCsvSourceSensor`, `SaveUsers`, `SaveGlobalSettings`, `SaveCustomChannels`, `SaveHardware`, `SaveGroupTemplates`, `SaveGroups`, `SaveTestSetup`, `SaveCheckoutTestSetup`
- `DTS.Common.Import.ImportOptions``ZeroMethodOptions`
- `DTS.Common.Import.XML``XMLParseMMECustomChannels`, `XMLParseMMECustomMainLocations`, `XMLParseDASList`, `XMLParseSensors`, `XMLParseCalibrations`, `XMLParseGroupTemplates`, `XMLParseGroups`, `XMLParseTestSetups`, `XMLParseLabDetails`, `XMLParseCustomerDetails`, `XMLParseTestEngineerDetails`, `XMLParseUsers`, `XMLPre20ParseDASList`, `XMLPre20ParseSensors`, `XMLPre20ParseCalibrations`, `XMLPre20ParseGroupTemplates`, `XMLPre20ParseGroups`, `XMLPre20ParseTestSetups`
- `DTS.Common.Enums.DBExport``TopLevelFields`
- `DTS.Common.Utils``FileUtils`
- `DTS.Slice.Users``User`
- `System.Xml``XmlElement`
### Consumers of this module:
- Cannot be determined from source alone; other modules in the codebase that require parser/lock/persistence handler creation would call these factories.
---
## 5. Gotchas
1. **Static mutable state in `XmlParserFactory`**: The properties `UIItems`, `ImportNotification`, and field `_isCancelled` are static and set during `CreateXMLParsers`. This could cause thread-safety issues or stale state if called concurrently.
2. **Non-sequential version numbers**: `CSVTestParserFactory` creates versions 0, 5, and 6 (skipping 1-4), while `CSVSensorParserFactory` creates versions 0, 2, 3, and 4 (skipping 1). The reason for these gaps is unclear from source alone.
3. **Misleading parameter name**: In `SaveVariantFactory.CreateVariants`, the `showCheckoutButton` parameter is used to determine "GM parse mode" and affects test setup naming, which is not obvious from the parameter name. (Comment references FB 38039.)
4. **Pre-2.0 XML wrapper pattern**: For XML versions below 2.0, parsers are wrapped in `XMLPre20Parse*` variants (e.g., `XMLPre20ParseSensors` wraps `XMLParseSensors`). This decorator-like pattern is specific to legacy format handling.
5. **Null-safe hardware channel counting**: In `SaveVariantFactory`, hardware channel counting uses `h?.Channels.Length ?? 0`, suggesting `Hardware` items or their `Channels` property may be null.
6. **Unused `saveCustomChannels` instance**: In `SaveVariantFactory`, `SaveCustomChannels` is instantiated unconditionally but only added to handlers if referenced by `SaveTestSetup`. Its standalone purpose is unclear from source alone.

View File

@@ -0,0 +1,98 @@
---
source_files:
- Common/DTS.Common.Import/ImportOptions/EqxImportOptions.cs
- Common/DTS.Common.Import/ImportOptions/CsvImportOptions.cs
generated_at: "2026-04-16T11:43:37.257209+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c231715b4e36a96d"
---
# Documentation: DTS.Common.Import.ImportOptions
## 1. Purpose
This module provides configuration option classes for data import operations within the DTS system. It defines three option classes—`EqxImportOptions`, `CsvImportOptions`, and `ZeroMethodOptions`—that encapsulate import behavior settings for EQX-format sensor imports, CSV file parsing, and zero method calibration configuration respectively. These classes serve as data transfer objects to parameterize import operations.
---
## 2. Public Interface
### Class: `EqxImportOptions`
**Namespace:** `DTS.Common.Import.ImportOptions`
Configuration options for EQX import operations.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `OverwriteExistingSensors` | `bool` | `true` | Controls whether existing sensors should be overwritten during import. |
| `ImportSensorModels` | `bool` | `true` | Controls whether sensor models should be imported. |
---
### Class: `CsvImportOptions`
**Namespace:** `DTS.Common.Import.ImportOptions`
Configuration options for CSV file parsing and import.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `Encoding` | `string` | None (uninitialized) | Specifies the character encoding for the CSV file. |
| `FieldSeparator` | `string` | None (uninitialized) | Specifies the field delimiter character(s) used in the CSV. |
| `ImportCulture` | `CultureInfo` | None (uninitialized) | Specifies the culture settings for parsing culture-dependent data (e.g., number formats, dates). |
| `StripBackSlash` | `bool` | None (uninitialized) | Controls whether backslash characters should be removed during import. |
---
### Class: `ZeroMethodOptions`
**Namespace:** `DTS.Common.Import.ImportOptions`
Configuration options for zero method calibration settings.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `ZeroMethodType` | `ZeroMethodType` | None (uninitialized) | Specifies the type of zero method to apply. Type is defined in `DTS.Common.Enums.Sensors`. |
| `ZeroMethodStart` | `double` | None (uninitialized) | Specifies the start value for the zero method range. |
| `ZeroMethodEnd` | `double` | None (uninitialized) | Specifies the end value for the zero method range. |
---
## 3. Invariants
**Explicit invariants from source:** None. The classes contain only auto-implemented properties with no validation logic, constructors, or constraints visible in the source.
**Observations:**
- `EqxImportOptions` properties have explicit default values of `true`.
- `CsvImportOptions` and `ZeroMethodOptions` properties have no default values; consumers must initialize them.
- No nullability annotations are present; reference type properties (`Encoding`, `FieldSeparator`, `ImportCulture`) may be null at runtime if not explicitly set.
---
## 4. Dependencies
### This module depends on:
- `System` (core .NET types)
- `System.Collections.Generic` (generic collections)
- `System.Globalization` (`CultureInfo` type used in `CsvImportOptions`)
- `System.Linq` (LINQ support)
- `System.Text` (text encoding support)
- `System.Threading.Tasks` (async/task support)
- `DTS.Common.Enums.Sensors` (`ZeroMethodType` enum used in `ZeroMethodOptions`)
### Consumers:
Not determinable from the provided source files alone. These option classes are likely consumed by import service classes or handlers elsewhere in the `DTS.Common.Import` namespace or broader DTS system.
---
## 5. Gotchas
1. **`Encoding` is a `string`, not `System.Text.Encoding`:** The `CsvImportOptions.Encoding` property is declared as `string`, not the `System.Text.Encoding` type. Consumers must convert between string representations and actual encoding objects.
2. **Inconsistent default value patterns:** `EqxImportOptions` initializes both properties to `true`, while `CsvImportOptions` and `ZeroMethodOptions` leave all properties uninitialized. This inconsistency may lead to unexpected `null` or default value behavior if consumers assume all option classes follow the same initialization pattern.
3. **Unused imports:** Both files import `System.Collections.Generic`, `System.Linq`, `System.Text`, and `System.Threading.Tasks`, but none of these namespaces are referenced in the visible code. This may indicate legacy code or generated boilerplate.
4. **No validation or bounds checking:** `ZeroMethodOptions.ZeroMethodStart` and `ZeroMethodEnd` are raw `double` values with no validation. The relationship between start and end (e.g., whether start must be less than end) is not enforced at this level.

View File

@@ -0,0 +1,174 @@
---
source_files:
- Common/DTS.Common.Import/Interfaces/IPersistImport.cs
- Common/DTS.Common.Import/Interfaces/IParseImport.cs
- Common/DTS.Common.Import/Interfaces/IParseVariant.cs
- Common/DTS.Common.Import/Interfaces/IParseCSVTest.cs
- Common/DTS.Common.Import/Interfaces/IParseCSVSensor.cs
- Common/DTS.Common.Import/Interfaces/ICalibrationImport.cs
- Common/DTS.Common.Import/Interfaces/ILockImport.cs
- Common/DTS.Common.Import/Interfaces/IGroupImport.cs
generated_at: "2026-04-16T11:46:21.980624+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "4d7a3572ba82cd30"
---
# DTS.Common.Import Interfaces Documentation
## 1. Purpose
This module defines the core abstraction layer for the DTS import subsystem. It provides interfaces for parsing import files (CSV, variants), persisting imported data, managing database locks during concurrent imports, handling sensor calibration records, and organizing sensors into test groups. These interfaces establish the contract between import data sources and the domain model, enabling extensibility for different import formats and workflows.
---
## 2. Public Interface
### IPersistImport
**Signature:**
```csharp
public interface IPersistImport
{
void Save();
}
```
**Behavior:** Persists the imported data. Implementations are expected to commit the import state to a data store.
---
### IParseImport
**Signature:**
```csharp
public interface IParseImport
{
ImportObject Parse(IEnumerable<string> importFiles);
}
```
**Behavior:** Accepts a collection of file paths and returns a populated `ImportObject` representing the parsed import data.
---
### IParseVariant
**Signature:**
```csharp
public interface IParseVariant
{
string FileName { get; set; }
void Parse(ref ImportObject importObject);
}
```
**Behavior:** Parses variant-specific import data. The `FileName` property indicates the source file. The `Parse` method modifies the passed `ImportObject` by reference.
---
### IParseCSVTest
**Signature:**
```csharp
public interface IParseCSVTest
{
int Version { get; }
void ParseVersion(CsvReader csvReader, TestSetupImportData tsid);
}
```
**Behavior:** Handles versioned CSV test setup parsing. `Version` indicates the parser version supported. `ParseVersion` reads from a `CsvReader` and populates `TestSetupImportData`.
---
### IParseCSVSensor
**Signature:**
```csharp
public interface IParseCSVSensor
{
int Version { get; }
void Initialize(ICalibrationImport import, ZeroMethodOptions zmOptions,
IImportNotification importNotification, bool importCreateDynamicGroups,
bool useIsoCodeFilterMapping, bool useZeroForUnfiltered);
void ParseVersion(CSVImportTags.Tags field, string val, ParseParameters pp);
}
```
**Behavior:** Handles versioned CSV sensor parsing. `Initialize` must be called to configure calibration handling, zero method options, notification callbacks, and filtering options before parsing. `ParseVersion` processes individual field/value pairs using `ParseParameters`.
---
### ICalibrationImport
**Signature:**
```csharp
public interface ICalibrationImport
{
SensorCalibration AddLinearCalRecordIfNeeded(SensorCalibration sc, bool savedIsProportional, bool savedRemoveOffset);
SensorCalibration AddLinearZeroMethodIfNeeded(SensorCalibration sc, ZeroMethodType zeroMethodType, double zeroMethodStart, double zeroMethodEnd);
SensorCalibration CheckForExcitationCalibration(SensorCalibration sc, double sensitivity, ExcitationVoltageOptions.ExcitationVoltageOption excitation, string EU);
}
```
**Behavior:** Manages sensor calibration during import. Methods conditionally add calibration records (linear calibration, zero method, excitation calibration) to a `SensorCalibration` object and return the modified instance.
---
### ILockImport
**Signature:**
```csharp
public interface ILockImport
{
bool Contended { get; }
void SetLock(ref ImportObject importObject, ref StringBuilder message);
void FreeLock(ref ImportObject importObject);
bool StealLock(bool proceed);
}
```
**Behavior:** Manages database locks during import operations. `Contended` indicates whether lock contention exists. `SetLock` acquires a lock and populates the `message` StringBuilder with any errors. `FreeLock` releases the lock. `StealLock` forcibly takes a lock if `proceed` is true.
---
### IGroupImport
**Signature:**
```csharp
public interface IGroupImport
{
ParseParameters ParseParameters { get; set; }
Tuple<TestTemplate, List<IGroup>> CreateGroups(List<SensorData> sensors, Dictionary<string, List<TsetSetupImportSensorInfo>> groupSensorLookup, TestTemplate testTemplate, bool createDynamicGroups, List<IGroup> staticGroups, Action<double> setProgress);
Dictionary<string, List<TsetSetupImportSensorInfo>> GetGroupSensorLookup(List<SensorData> sensors, Dictionary<string, string> sensorGroupNameLookup, Dictionary<string, List<string>> groupNameSensorListLookup);
}
```
**Behavior:** Creates and manages sensor groupings during import. `GetGroupSensorLookup` builds a lookup dictionary mapping group names to sensor info. `CreateGroups` generates test groups (dynamic and/or static) and returns a tuple of the test template and group list. Progress reporting is supported via the `setProgress` callback.
---
## 3. Invariants
- **IParseCSVSensor initialization ordering:** The `Initialize` method must be called before `ParseVersion` can be meaningfully executed (inferred from parameter dependencies).
- **ILockImport message sharing:** The `StringBuilder message` parameter in `SetLock` is documented as shared between all types and accumulates all database lock errors.
- **IParseVariant ref semantics:** The `ImportObject` is passed by reference, implying the parser is expected to modify the existing object rather than replace it.
- **ILockImport.Contended:** Must return `true` if the internal collection of contended locks has any items (per source comment).
---
## 4. Dependencies
### This module depends on:
- `System.Collections.Generic` (IEnumerable, Dictionary, List)
- `System.Text` (StringBuilder)
- `System` (Tuple, Action)
- `CsvHelper` (CsvReader)
- `DTS.Common.Classes` (TestSetupImportData)
- `DTS.Common.Classes.Sensors` (SensorData)
- `DTS.Common.Enums` (ExcitationVoltageOptions)
- `DTS.Common.Enums.Sensors` (ZeroMethodType, ZeroMethodOptions)
- `DTS.Common.Import.ImportOptions` (CSVImportTags, ParseParameters)
- `DTS.Common.Interface.Groups.GroupList` (IGroup)
- `DTS.SensorDB` (SensorCalibration)
- `DataPROWin7.DataModel` (TestTemplate, TsetSetupImportSensorInfo)
### What depends on this module:
- Not determinable from the provided source files alone (these are interface definitions).
---
## 5. Gotchas
1. **ILockImport error message accumulation:** The `message` StringBuilder in `SetLock` is shared across all lock types. Errors accumulate, so callers should check the message contents after all lock operations complete rather than after each individual call.
2. **FB 36740 reference:** The `ILockImport` interface has a comment referencing "FB 36740" for database lock support. This appears to be a feature/bug tracking reference that may provide historical context for the locking implementation.
3. **IParseVariant ref parameter:** The use of `ref` for `ImportObject` in `Parse` is unusual for an interface pattern. Callers should be aware the object may be mutated in place.
4. **IParseCSVSensor.Initialize complexity:** The `Initialize` method accepts 6 parameters including flags for `importCreateDynamicGroups`, `useIsoCodeFilterMapping`, and `useZeroForUnfiltered`. The interaction between these flags and the parsing behavior is not documented in the interface.

View File

@@ -0,0 +1,114 @@
---
source_files:
- Common/DTS.Common.Import/Parsers/ParseVariantBase.cs
- Common/DTS.Common.Import/Parsers/DefaultParseImport.cs
- Common/DTS.Common.Import/Parsers/DTSXMLParseImport.cs
generated_at: "2026-04-16T11:43:16.787826+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "6317dc1ace913c30"
---
# Documentation: DTS.Common.Import.Parsers
## 1. Purpose
This module provides parsing infrastructure for importing data files into the system. It defines an abstract base class for parse variants (`ParseVariantBase`) and concrete implementations of the `IParseImport` interface (`DefaultParseImport` and `DTSXMLParseImport`) that orchestrate file parsing operations. The module acts as a bridge between raw import files and structured `ImportObject` instances, supporting both generic and XML-specific parsing workflows.
---
## 2. Public Interface
### ParseVariantBase (Abstract Class)
**Implements:** `IParseVariant`
| Member | Signature | Description |
|--------|-----------|-------------|
| `FileName` | `public string FileName { get; set; }` | Property to store the name of the file being parsed. |
| `Parse` | `public abstract void Parse(ref ImportObject importObject)` | Abstract method that derived classes must implement to perform parsing logic. Receives `ImportObject` by reference, allowing the object to be modified or replaced. |
---
### DefaultParseImport (Class)
**Implements:** `IParseImport`
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `public DefaultParseImport(ImportObject importObject, IEnumerable<IParseVariant> parseVariants)` | Initializes the parser with an `ImportObject` instance and a collection of `IParseVariant` implementations. |
| `Parse` | `public ImportObject Parse(IEnumerable<string> importFiles)` | Orchestrates parsing by creating an internal `ParseProcessor` with the configured variants and files. Returns the processed `ImportObject`. |
---
### DTSXMLParseImport (Class)
**Implements:** `IParseImport`
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `public DTSXMLParseImport(ImportObject importObject, IImportNotification importNotification, Func<bool> isCancelled = null, bool skipNormalizing = false)` | Initializes the XML parser with an `ImportObject`, notification interface, optional cancellation callback, and optional flag to skip normalization. |
| `UIItems` | `public List<IUIItems> UIItems { get; set; }` | Property for UI items configuration, passed to the internal `XMLParseProcessor`. |
| `Parse` | `public ImportObject Parse(IEnumerable<string> importFiles)` | Creates an `XMLParseProcessor`, processes files, then calls `AssignLinkedDASSerials` to link pseudo-rack hardware. Returns the processed `ImportObject`. |
**Private Methods:**
| Method | Description |
|--------|-------------|
| `AssignLinkedDASSerials(ref ImportObject importObject)` | Iterates over hardware objects, identifies pseudo-racks via `IsPseudoRack()`, and assigns `LinkedDASSerials` array to any pseudo-rack whose `SerialNumber` matches other hardware's `ParentDAS` value. |
---
## 3. Invariants
1. **ParseVariantBase.Parse**: The `ImportObject` parameter is passed by reference (`ref`), meaning implementations may modify or replace the object entirely.
2. **DefaultParseImport**: The `_importObject` field is reassigned after parsing via `parseProcesser.Process()`. The same `_parseVariants` collection provided at construction is used throughout the instance lifetime.
3. **DTSXMLParseImport**:
- `_importNotification` is required (no null check visible in source).
- `_isCancelled` and `_skipNormalizing` are optional parameters with default values (`null` and `false` respectively).
- `AssignLinkedDASSerials` only modifies hardware where `IsPseudoRack()` returns `true` and matching child hardware exists.
4. **Hardware Linking Logic**: In `AssignLinkedDASSerials`, linked serials are only assigned if `matches.Any()` returns true; otherwise, `LinkedDASSerials` is left unchanged (not explicitly cleared).
---
## 4. Dependencies
### This module depends on:
| Dependency | Used In |
|------------|---------|
| `DTS.Common.Import.Interfaces` | All three files (for `IParseVariant`, `IParseImport`, `ImportObject`, `IImportNotification`) |
| `DTS.Slice.Users` | `DTSXMLParseImport.cs` (for `IUIItems`) |
| `System.Collections.Generic` | `DefaultParseImport.cs`, `DTSXMLParseImport.cs` |
| `System.Linq` | `DefaultParseImport.cs`, `DTSXMLParseImport.cs` |
| `System.Threading.Tasks` | `DefaultParseImport.cs` |
| `System.Text` | `DefaultParseImport.cs` |
### External types referenced (not defined in source):
| Type | Source File | Notes |
|------|-------------|-------|
| `ImportObject` | All | Core data structure, defined elsewhere |
| `IParseVariant` | `ParseVariantBase.cs` | Interface definition not shown |
| `IParseImport` | `DefaultParseImport.cs`, `DTSXMLParseImport.cs` | Interface definition not shown |
| `ParseProcessor` | `DefaultParseImport.cs` | Concrete class, definition not shown |
| `XMLParseProcessor` | `DTSXMLParseImport.cs` | Concrete class, definition not shown |
| `IImportNotification` | `DTSXMLParseImport.cs` | Interface definition not shown |
| `IUIItems` | `DTSXMLParseImport.cs` | Interface definition not shown |
---
## 5. Gotchas
1. **Namespace Inconsistency**: `DTSXMLParseImport.cs` is in namespace `DTS.Common.Import` while the other two files are in `DTS.Common.Import.Parsers`. This may cause confusion when locating classes.
2. **Unused Imports**: `System.Threading.Tasks` and `System.Text` are imported in `DefaultParseImport.cs` but no async/await or text encoding operations are visible in the source.
3. **Field Reassignment**: Both `DefaultParseImport` and `DTSXMLParseImport` reassign their `_importObject` field during `Parse()`. If the same instance is used for multiple `Parse()` calls, the original `ImportObject` passed to the constructor will be overwritten.
4. **Null Handling Not Visible**: Neither class validates constructor parameters for null. Behavior with null `importObject`, `parseVariants`, or `importNotification` is undefined from source alone.
5. **UIItems Property Injection**: `DTSXMLParseImport.UIItems` must be set before calling `Parse()` if UI items are required by `XMLParseProcessor`. The property is not set in the constructor.

View File

@@ -0,0 +1,108 @@
---
source_files:
- Common/DTS.Common.Import/Parsers/CSV/AbstractCSVParser.cs
- Common/DTS.Common.Import/Parsers/CSV/Version0CSVTestParser.cs
- Common/DTS.Common.Import/Parsers/CSV/CSVFile.cs
- Common/DTS.Common.Import/Parsers/CSV/Version6CSVTestParser.cs
- Common/DTS.Common.Import/Parsers/CSV/Version3CSVSensorParser.cs
- Common/DTS.Common.Import/Parsers/CSV/Version5CSVTestParser.cs
- Common/DTS.Common.Import/Parsers/CSV/Version4CSVSensorParser.cs
- Common/DTS.Common.Import/Parsers/CSV/CSVGroupImport.cs
- Common/DTS.Common.Import/Parsers/CSV/DTSCSVTestSetupParser.cs
- Common/DTS.Common.Import/Parsers/CSV/DTSCSVSensorsParser.cs
generated_at: "2026-04-16T11:47:30.258239+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2bff5b23b8f73415"
---
# CSV Import Module Documentation
## 1. Purpose
This module provides a versioned parser architecture for importing DTS sensor configurations and test setups from CSV files. It transforms raw CSV data into domain objects (`SensorData`, `SensorCalibration`, `TestTemplate`) using a strategy pattern where specific parser versions (e.g., `Version0CSVTestParser`, `Version4CSVSensorParser`) handle different schema evolutions of the CSV format. It orchestrates the creation of groups, channel mappings, and hardware associations required for test setup imports.
## 2. Public Interface
### AbstractCSVParser
Base class for sensor parsers.
* `int Version { get; }` - Abstract property indicating the parser version.
* `void Initialize(ICalibrationImport import, ZeroMethodOptions zmOptions, IImportNotification importNotification, bool importCreateDynamicGroups, bool useISOCodeFilterMapping, bool useZeroForUnfiltered)` - Injects dependencies and configuration flags required for parsing.
* `void ParseVersion(CSVImportTags.Tags field, string val, ParseParameters pp)` - Abstract method to parse a specific field/value pair into the `ParseParameters` state object.
### CSVFile
Utility class for file inspection.
* `CSVFile(string filename)` - Constructor.
* `static bool IsInUse(string filename)` - Attempts to read the file to check for locks; returns `true` if `IOException` occurs.
* `static bool IsCSVFileForTestSetupImport(string filename, CsvImportOptions csvImportOptions)` - Validates if the file starts with the "Version" header.
* `static int GetCsvVersion(string filename)` - Extracts the integer version number from the second line of the CSV.
* `int LineCount { get; }` - Returns the total line count of the file.
### Versioned Test Parsers
Classes implementing `IParseCSVTest`:
* `Version0CSVTestParser`
* `Version5CSVTestParser`
* `Version6CSVTestParser`
**Common Members:**
* `int Version { get; }` - Returns the specific version number (0, 5, or 6).
* `void ParseVersion(CsvReader csvReader, TestSetupImportData tsid)` - Reads the CSV stream and populates `TestSetupImportData`.
### Versioned Sensor Parsers
Classes inheriting `AbstractCSVParser`:
* `Version3CSVSensorParser`: Handles `GroupName`, `GroupType`.
* `Version4CSVSensorParser`: Handles DAS mapping (`DASSerialNumber`, `DASChannelIndex`), UDP streaming (`UDPAddress`, `StreamProfile`), UART settings (`BaudRate`, `Parity`), and user codes.
### CSVGroupImport
Implements `IGroupImport`.
* `ParseParameters ParseParameters { get; set; }`
* `Tuple<TestTemplate, List<IGroup>> CreateGroups(List<SensorData> sensors, Dictionary<string, List<TsetSetupImportSensorInfo>> groupSensorLookup, TestTemplate testTemplate, bool createDynamicGroups, List<IGroup> staticGroups, Action<double> setProgress)` - Constructs group hierarchies and channels within a `TestTemplate`.
* `Dictionary<string, List<TsetSetupImportSensorInfo>> GetGroupSensorLookup(...)` - Builds a lookup dictionary mapping group names to sensor import info.
### DTSCSVTestSetupParser
Main orchestrator for test setup imports.
* `DTSCSVTestSetupParser(IImportNotification importNotification, CsvImportOptions csvImportOptions, TestSetupImportData testSetupImportData, IGroupImport groupImport, bool createDynamicGroups)`
* `void Parse(ref ImportObject importObject)` - Entry point. Validates file, parses test setup, creates groups, assigns calibrations.
* `static TestTemplate CreateTestSetup(TestSetupImportData tsid, DASHardware[] allDAS)` - Factory method to create a `TestTemplate` from parsed data.
* `static void UpdateDASSampleRate(TestTemplate t, TestSetupImportData tsid, DASHardware[] allDAS)` - Updates sample rates on the template.
### DTSCSVSensorsParser
Main orchestrator for sensor imports.
* `DTSCSVSensorsParser(IImportNotification importNotification, User user, CsvImportOptions csvImportOptions, ICalibrationImport calibrationImport, ZeroMethodOptions zeroMethodOptions)`
* `bool ImportCreateDynamicGroups { get; set; }`
* `bool UseISOCodeFilterMapping { get; set; }`
* `bool UseZeroForUnfiltered { get; set; }`
* `void Parse(ref ImportObject importObject)` - Entry point. Reads headers, iterates rows, populates `SensorData` and `SensorCalibration`.
## 3. Invariants
* **Version Header**: A valid CSV file for import must contain a "Version" header in the first row, with the version integer in the second row (enforced by `CSVFile.IsCSVFileForTestSetupImport` and `GetCsvVersion`).
* **Parser Selection**: `DTSCSVTestSetupParser` only invokes parsers for versions 1 through 5 if the file version is exactly 6. Otherwise, it defaults to running only the Version 0 parser.
* **Group Uniqueness**: In `Version3CSVSensorParser`, a sensor serial number cannot appear twice in the `SensorGroupNameLookup` or `SensorGroupTypeLookup`; duplicates trigger an error.
* **Version 6 Tag Filtering**: `Version6CSVTestParser` and `DTSCSVSensorsParser` explicitly check `CSVImportTags.GetVersionForTag` and skip tags that do not match their expected version (e.g., Version 6 parser skips Version 5 tags).
* **Hardware Association**: In `DTSCSVTestSetupParser`, hardware is only added to the `ImportObject` if the CSV version is 6 or greater.
## 4. Dependencies
**Internal Dependencies (Namespaces referenced):**
* `DTS.Common.Classes`, `DTS.Common.Classes.Sensors`: Core domain objects (`SensorData`, `SensorCalibration`).
* `DTS.Common.Enums`, `DTS.Common.Enums.Sensors`: Enumeration types (`RecordingModes`, `BridgeType`, `SensUnits`).
* `DTS.Common.Import.Interfaces`: Interfaces `IParseCSVSensor`, `IParseCSVTest`, `IGroupImport`.
* `DTS.Common.Import.ImportOptions`: `CsvImportOptions`, `ZeroMethodOptions`.
* `DTS.SensorDB`: Database operations and storage types.
* `DataPROWin7.DataModel`: Hardware data models (`DASHardware`).
* `DTS.Common.Storage`: `DbOperations`.
**External Libraries:**
* `CsvHelper`: Used via `CsvReader` for reading CSV records.
**Factory Dependencies (referenced but not defined in source):**
* `CSVTestParserFactory`: Creates the array of test parsers.
* `CSVSensorParserFactory`: Creates the dictionary of sensor parsers.
## 5. Gotchas
* **Silent Exception Swallowing**: `CSVFile.IsInUse` catches all non-IOExceptions and returns `true` (indicating the file is in use/unavailable), which may mask permission errors or corrupt file issues.
* **Hardcoded Version Logic**: `DTSCSVTestSetupParser.ParseTestSetup` contains logic that specifically checks `if (tsid.Version == 6)` to determine whether to iterate through higher-version parsers. Adding a Version 7 would require modifying this specific method.
* **Generic Exception Throwing**: `Version3CSVSensorParser` throws a generic `System.Exception("Parse error")` when a group maps to multiple test objects while dynamic groups are disabled. This is caught in `DTSCSVTestSetupParser.AssignGroupsToTestSetup` and reported generically.
* **Sensitivity Unit Mutation**: `DTSCSVSensorsParser` silently changes `SensitivityUnits` from `mVperVperEU` to `mVperEU` for non-proportional sensors, reporting it only as a non-blocking notification after processing.
* **ISO Channel Prefix**: Sensors with serial numbers starting with `Constants.ISO_CH_ONLY_PREFIX` are excluded from the standard sensor/calibration lookup dictionaries in `DTSCSVSensorsParser`,

View File

@@ -0,0 +1,182 @@
---
source_files:
- Common/DTS.Common.Import/Parsers/EQX/EQXTestSetupParser.cs
- Common/DTS.Common.Import/Parsers/EQX/EQXGroupImport.cs
- Common/DTS.Common.Import/Parsers/EQX/EQXSensorsParser.cs
generated_at: "2026-04-16T11:47:07.484549+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "ce57e1c33a0387ff"
---
# EQX Import Parsers Documentation
## 1. Purpose
This module provides parsing functionality for EQX (Equipment Exchange) format files, enabling import of sensor data and test setup configurations into the DTS system. It consists of three main components: `EQXSensorsParser` for parsing sensor definitions and calibrations, `EQXTestSetupParser` for constructing test setups with associated groups and channels, and `EQXGroupImport` for handling group creation and sensor-to-group mapping logic. The module bridges the proprietary EQX XML format with the internal `ImportObject` data model.
---
## 2. Public Interface
### EQXTestSetupParser
**Constructor:**
```csharp
public EQXTestSetupParser(
IImportNotification importNotification,
EqxImportOptions eqxImportOptions,
IGroupImport groupImport,
EquipmentExchange.EQXSensorDatabase eqxSensorDatabase,
bool createDynamicGroups)
```
**Public Methods:**
```csharp
public override void Parse(ref ImportObject importObject)
```
Parses the EQX file specified by `FileName` (inherited from `ParseVariantBase`) and populates the `importObject` with test setup data, groups, and sensors. Validates that the file contains test setup data (checks `GroupNameTestObjectLookup`). Aborts with a critical error if no test setup data is present.
---
### EQXGroupImport
**Implements:** `IGroupImport`
**Public Properties:**
```csharp
public ParseParameters ParseParameters { get; set; }
```
**Public Methods:**
```csharp
public Tuple<TestTemplate, List<IGroup>> CreateGroups(
List<SensorData> sensors,
Dictionary<string, List<TsetSetupImportSensorInfo>> groupSensorLookup,
TestTemplate testTemplate,
bool createDynamicGroups,
List<IGroup> staticGroups,
Action<double> setProgress)
```
Creates groups and populates a `TestTemplate` from sensor data. Returns a tuple containing the configured test template and list of static groups. Returns `null` if `groupSensorLookup` is null or empty. Groups are sorted by sensor count (descending), then by name (ascending) for tie-breaking.
```csharp
public Dictionary<string, List<TsetSetupImportSensorInfo>> GetGroupSensorLookup(
List<SensorData> sensors,
Dictionary<string, string> sensorGroupNameLookup,
Dictionary<string, List<string>> groupNameSensorListLookup)
```
Builds a lookup dictionary mapping group names to sensor information. Mutually exclusive: either `sensorGroupNameLookup` or `groupNameSensorListLookup` should be populated (per FB 30358).
---
### EQXSensorsParser
**Constructor:**
```csharp
public EQXSensorsParser(
IImportNotification importNotification,
User user,
EqxImportOptions eqxImportOptions,
EquipmentExchange.EQXSensorDatabase eqxSensorDatabase)
```
**Constants:**
```csharp
const float MAX_EQX_VERSION_SUPPORT = 1.5F;
```
**Public Properties:**
```csharp
public bool ImportCreateDynamicGroups { get; set; }
public bool EQXUseSerialNumberFieldForSN { get; set; }
public bool UseZeroForUnfiltered { get; set; }
```
**Public Methods:**
```csharp
public override void Parse(ref ImportObject importObject)
```
Parses the EQX file for sensor data. Validates XML structure and EQX format version (must be ≤ 1.5). Populates `importObject` with sensors, calibrations, and sensor model lookups.
---
## 3. Invariants
- **EQX Version Constraint:** `EQXSensorsParser` only supports EQX files with `DataFormatEdition``MAX_EQX_VERSION_SUPPORT` (1.5). Files with higher versions trigger an error and abort parsing.
- **Test Setup Presence:** `EQXTestSetupParser.Parse()` requires `GroupNameTestObjectLookup` to be non-null and non-empty. If empty, the import aborts with a critical error (`Import_EQXFileNotForTestSetup`).
- **Null Argument Handling:** Both `Parse()` methods throw `ArgumentNullException` if `importObject` is null. `EQXTestSetupParser.Parse()` returns early (no-op) if `FileName` is null or empty.
- **Calibration Sorting:** In `FixCalibrations()`, calibrations are sorted before the first one is assigned to a sensor. This implies calibrations have a defined sort order (likely by date or version).
- **Group Ordering:** In `EQXGroupImport.CreateGroups()`, groups are sorted by sensor count (descending), then alphabetically by name for equal counts.
- **Mutually Exclusive Lookups:** Per FB 30358, `GetGroupSensorLookup()` expects either `sensorGroupNameLookup` OR `groupNameSensorListLookup` to be populated, not both.
- **Sensor Uniqueness in Groups:** In `CreateGroups()`, a `HashSet<string>` (`sensorSerialHash`) ensures each sensor serial number is only counted once per group for `testGroupChannels`.
---
## 4. Dependencies
### Direct Dependencies (Imports):
**EQXTestSetupParser:**
- `DataPROWin7.DataModel` - `ImportObject`, `ImportError`, `ImportSeverityError`, `TestTemplate`, `SensorData`
- `DTS.Common.Import.ImportOptions` - `EqxImportOptions`
- `DTS.Common.Import.Parsers` - `ParseVariantBase`
- `DTS.Common.Interface.Groups.GroupList` - `IGroupImport`, `IGroup`
- `DTS.Common.SharedResource.Strings` - `StringResources`
- `DTS.Common.Utilities.Logging` - `APILogger`
- `DTS.Common.Utils` - `GroupHelper`
- `DTS.SensorDB` - `EquipmentExchange.EQXSensorDatabase`
- `System.Xml.Linq` - XML parsing
**EQXGroupImport:**
- `DataPROWin7.DataModel` - `TestTemplate`, `SensorData`, `TsetSetupImportSensorInfo`
- `DTS.Common.Classes.Groups` - Group-related classes
- `DTS.Common.Classes.Sensors` - `GroupChannel`
- `DTS.Common.Interface.Groups.GroupList` - `IGroupImport`, `IGroup`
- `DTS.Common.Interface.Channels` - `IGroupChannel`
- `DTS.Common.Storage` - `DbOperations`
- `DTS.SensorDB` - Sensor database types
**EQXSensorsParser:**
- `DTS.Common.Enums` - `BridgeType`, `SquibMeasurementType`, `ExcitationVoltageOptions`
- `DTS.Common.Import.ImportOptions` - `EqxImportOptions`
- `DTS.Common.Import.Parsers` - `ParseVariantBase`
- `DTS.Common.Storage` - `DbOperations`
- `DTS.Common.Classes.Sensors` - `FactorySensorModel`, `SensorsCollection`
- `DTS.Common.Interface.Sensors` - `ISensorData`
- `DTS.Common.SharedResource.Strings` - `StringResources`
- `DTS.Slice.Users` - `User`
- `DTS.SensorDB` - `EquipmentExchange.EQXSensorDatabase`
### Consumers:
- The module is designed to be consumed by the DTS import infrastructure via `ParseVariantBase` inheritance pattern.
- `EQXGroupImport` implements `IGroupImport`, suggesting it's injected into consumers that depend on that interface.
---
## 5. Gotchas
1. **Calibration Reset Bug (Case 44105):** `NormalizeSensorIds()` in `GroupHelper` can reset sensor calibrations. `EQXTestSetupParser.AssignGroupsToTestSetup()` calls `FixCalibrations()` after `NormalizeSensorIds()` to restore them. This is a known workaround documented in the source.
2. **Duplicate Sensor Addition:** In `EQXSensorsParser.ParseSensor()`, sensors are added to `importObject` via both `AddSensorLookup()` and `AddSensor()`. The comment "this is for compatability for import test setups" suggests legacy behavior being maintained.
3. **EID Preservation (Case 18467):** If an EQX file has a null `IDModuleString`, the parser attempts to preserve the existing EID from the sensor database to avoid wiping it out.
4. **Excitation Errors Not Reported:** `GetExcitationErrors()` collects excitation validation errors, but the method includes a `//TODO Report the errors` comment, indicating these errors may not be surfaced to users.
5. **Silent XML Parsing Failure:** `ParseSetupName()` catches all exceptions and returns `string.Empty` without logging, making setup name extraction failures invisible.
6. **Static Group Mutation:** `EQXGroupImport.CreateGroups()` modifies the `staticGroups` list parameter in-place (calls `staticGroups.Add(newGroup)`) rather than returning a new collection.
7. **Progress Callback Frequency:** In `EQXSensorsParser.ParseSensor()`, progress updates only occur every 10 iterations (`if (0 == currentDone % 10)`), which may cause UI staleness for small imports.
8. **Zero Method Hardcoded Index:** In `CreateGroups()`, zero method properties are accessed via `Methods[0]` without bounds checking, assuming at least one method exists in `ZeroMethods.Methods`.

View File

@@ -0,0 +1,315 @@
---
source_files:
- Common/DTS.Common.Import/Persist/SaveServer.cs
- Common/DTS.Common.Import/Persist/SaveGroupTemplates.cs
- Common/DTS.Common.Import/Persist/SaveVariantBase.cs
- Common/DTS.Common.Import/Persist/SaveGlobalSettings.cs
- Common/DTS.Common.Import/Persist/PersistCalculator.cs
- Common/DTS.Common.Import/Persist/SaveSensorModels.cs
- Common/DTS.Common.Import/Persist/SaveTestEngineerDetails.cs
- Common/DTS.Common.Import/Persist/SaveLabDetails.cs
- Common/DTS.Common.Import/Persist/SaveUsers.cs
- Common/DTS.Common.Import/Persist/SaveCustomerDetails.cs
- Common/DTS.Common.Import/Persist/SaveHardware.cs
- Common/DTS.Common.Import/Persist/SaveTestSetupHelper.cs
- Common/DTS.Common.Import/Persist/SaveGroups.cs
- Common/DTS.Common.Import/Persist/SaveCustomChannels.cs
- Common/DTS.Common.Import/Persist/SaveTestSetup.cs
- Common/DTS.Common.Import/Persist/SaveCheckoutTestSetup.cs
generated_at: "2026-04-16T11:46:11.806575+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "695fcda61b684601"
---
# DTS.Common.Import.Persist Module Documentation
## 1. Purpose
This module implements the persistence layer for an import system, responsible for saving various imported data entities (hardware, users, test setups, groups, sensors, etc.) to a database. It follows the Strategy pattern where each `SaveVariantBase` subclass handles a specific entity type, providing a unified interface (`IPersistImport`) for the import pipeline while supporting progress tracking, cancellation, and error reporting.
---
## 2. Public Interface
### SaveVariantBase (Abstract Base Class)
```csharp
public abstract class SaveVariantBase : IPersistImport
{
protected ImportObject _importObject;
protected readonly IPersistCalculator _persistCalculator;
protected readonly IImportNotification _importNotification;
protected readonly Func<bool> IsCancelled;
protected SaveVariantBase(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, Func<bool> isCancelled = null)
public abstract void Save();
}
```
Base class for all save variants. Provides shared infrastructure for progress reporting, cancellation checking, and access to the import data object.
### IPersistCalculator / PersistCalculator
```csharp
public interface IPersistCalculator
{
void AddDone();
void AddDone(double value);
double ProgressValue { get; }
void AddToTotal(double value);
}
public class PersistCalculator : IPersistCalculator
{
public double ProgressValue { get; } // Returns _done / _total
public void AddDone();
public void AddDone(double value);
public void AddToTotal(double value); // Throws ArgumentOutOfRangeException if value < 0
}
```
Tracks progress as a ratio of completed work (`_done`) to total work (`_total`).
### SaveServer
```csharp
public class SaveServer : SaveVariantBase
{
public SaveServer(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, Func<bool> isCancelled = null)
public override void Save(); // Throws NotImplementedException
}
```
Stub implementation — currently unimplemented.
### SaveGroupTemplates
```csharp
public class SaveGroupTemplates : SaveVariantBase
{
public SaveGroupTemplates(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, Func<bool> isCancelled = null)
public override void Save(); // Iterates _importObject.GroupTemplates(), updates progress
}
```
Iterates group templates without persisting them (appears to be a placeholder that only updates progress).
### SaveGlobalSettings
```csharp
public class SaveGlobalSettings : SaveVariantBase
{
public override void Save(); // Calls SettingsDB.SetGlobalValue(g.Key, g.Value) for each setting
}
```
Persists global settings via `SettingsDB.SetGlobalValue()`.
### SaveSensorModels
```csharp
public class SaveSensorModels : SaveVariantBase
{
public User CurrentUser { get; set; }
public override void Save(); // Commits sensor models via SensorModelCollection.SensorModelList.Commit()
}
```
Persists sensor models. Requires `CurrentUser` to be set for the commit operation.
### SaveTestEngineerDetails
```csharp
public class SaveTestEngineerDetails : SaveVariantBase
{
public override void Save(); // Adds test engineers via TestEngineerDetailsList.TestEngineerList.AddTestEngineer()
}
```
Persists test engineer details. Sets status to `ImportExtraStatus.ReadingEngineerDetails`.
### SaveLabDetails
```csharp
public class SaveLabDetails : SaveVariantBase
{
public override void Save(); // Adds labs via LabratoryDetailsList.AddLab()
}
```
Persists lab details. Skips invalid/blank entries (calls `l.IsInvalidBlank()`). Sets status to `ImportExtraStatus.ReadingLabDetails`.
### SaveUsers
```csharp
public class SaveUsers : SaveVariantBase
{
public IUIItems[] UIItems { get; set; }
public User CurrentUser { get; set; }
public override void Save(); // Commits users via UserCollection.UsersList.Commit()
}
```
Persists users. **Asserts** that `CurrentUser.IsAdmin` is true (will fail in debug builds if non-admin attempts import). Sets status to `ImportExtraStatus.ReadingUsers`.
### SaveCustomerDetails
```csharp
public class SaveCustomerDetails : SaveVariantBase
{
public override void Save(); // Adds customers via CustomerDetailsList.AddCustomer()
}
```
Persists customer details. Skips invalid/blank entries. Note: Sets status to `ImportExtraStatus.ReadingLabDetails` (appears to be a copy-paste error).
### SaveHardware
```csharp
public class SaveHardware : SaveVariantBase
{
public Dictionary<int, int> OldDASIdToNewDASId { get; set; } = new Dictionary<int, int>();
public Dictionary<int, List<IISOHardware>> TestIdToHardware { get; set; } = new Dictionary<int, List<IISOHardware>>();
public override void Save(); // Commits hardware via DASHardwareList.GetList().Commit()
}
```
Persists hardware configurations. Tracks DAS ID remapping (`OldDASIdToNewDASId`) and hardware-to-test relationships (`TestIdToHardware`). Sorts hardware before processing. Progress includes both hardware items and their channels.
### SaveGroups
```csharp
public class SaveGroups : SaveVariantBase
{
public bool CanCurrentUserCommitChannelCodes { get; set; } = true;
public IChannelSetting DefaultZeroMethod { get; set; }
public IChannelSetting DefaultZeroStart { get; set; }
public IChannelSetting DefaultZeroEnd { get; set; }
public IChannelSetting DefaultInitialOffset { get; set; }
public Dictionary<int?, int> OldGroupIdToNewGroupId { get; set; } = new Dictionary<int?, int>();
public SaveGroups(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, SaveHardware saveHardware, Func<bool> isCancelled = null)
public override void Save();
}
```
Persists static groups. Requires `SaveHardware` dependency for DAS ID remapping. Fixes missing zero method parameters and initial offsets. Maps old group IDs to new IDs. Reports warnings for groups with channels assigned to unknown DAS.
### SaveCustomChannels
```csharp
public class SaveCustomChannels : SaveVariantBase
{
public ISO13499FileDb IsoDb { get; set; }
public Dictionary<string, string> CustomChannelTextIdToOldChannelId { get; set; } = new Dictionary<string, string>();
public Dictionary<string, TestObjectChannel> CustomChannelOldChannelIdToChannel { get; set; } = new Dictionary<string, TestObjectChannel>();
public override void Save();
}
```
Persists custom channels via `CustomChannelList.List.Commit()`. Handles ID remapping for existing channels. Updates group templates and groups that reference custom channels. Calls `CustomChannelList.List.UpdateAll()` at the end.
### SaveTestSetup
```csharp
public class SaveTestSetup : SaveVariantBase
{
public User CurrentUser { get; set; }
public string TestSetupName { get; set; }
public SaveTestSetup(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, SaveCustomChannels saveCustomChannels,
SaveHardware saveHardware, SaveGroups saveGroups, Func<bool> isCancelled = null)
public override void Save();
}
```
Persists test setups via `TestTemplateList.TestTemplatesList.Commit()`. Requires dependencies on `SaveCustomChannels`, `SaveHardware`, and `SaveGroups`. Handles special case for `ImportFileFormat.SingleTestSetup` with custom naming. Deletes existing test setups before import. Updates hardware `TestId` references after commit.
### SaveCheckoutTestSetup
```csharp
public class SaveCheckoutTestSetup : SaveVariantBase
{
public User CurrentUser { get; set; }
public SaveCheckoutTestSetup(ImportObject importObject, IPersistCalculator persistCalculator,
IImportNotification importNotification, SaveCustomChannels saveCustomChannels,
SaveHardware saveHardware, SaveGroups saveGroups,
Func<bool> isCancelled = null, string setupName = null)
public override void Save();
}
```
Persists checkout test setups with specific configuration (checkout mode enabled, missing sensors allowed, etc.). Creates new groups from `ChannelsForGroup` configuration.
### SaveTestSetupHelper (Static Class)
```csharp
public static class SaveTestSetupHelper
{
public static void AddHardwareFromEmbeddedGroups(TestTemplate t, SaveGroups saveGroups,
List<int> hardwareRemoved, List<int> hardwareIncluded);
public static void FixDasAff(Dictionary<string, DASHardware> hardwareLookup, TestTemplate t);
public static Dictionary<string, DASHardware> PopulateHarwareLookup();
public static void DeleteExistingTestSetups(IEnumerable<TestTemplate> testSetups, string userName);
public static void UpdateLevelTriggers(ref Dictionary<string, string> oldIdToNewIdLookup,
SaveCustomChannels saveCustomChannels, IEnumerable<TestTemplate> testSetups);
}
```
Helper methods extracted for reuse between `SaveTestSetup` and `SaveCheckoutTestSetup`.
---
## 3. Invariants
1. **Cancellation Check Pattern**: All `Save()` implementations check `IsCancelled()` at the start of each iteration loop and return immediately if true.
2. **Progress Reporting Pattern**: After each item is processed, implementations call `_persistCalculator.AddDone()` followed by `_importNotification.SetProgress(_persistCalculator.ProgressValue)`.
3. **Constructor Signature**: All `SaveVariantBase` subclasses accept the same base parameters: `ImportObject`, `IPersistCalculator`, `IImportNotification`, and optional `Func<bool> isCancelled`.
4. **Null Cancellation Handler**: If `isCancelled` is null, `SaveVariantBase` assigns a lambda returning `false`.
5. **ProgressValue Calculation**: `ProgressValue` is calculated as `_done / _total`. Division by zero is possible if `AddToTotal()` is never called (undefined behavior in source).
6. **AddToTotal Validation**: `PersistCalculator.AddToTotal()` throws `ArgumentOutOfRangeException` if `value < 0`.
7. **Hardware ID Mapping**: `SaveHardware` always populates `OldDASIdToNewDASId` when DAS IDs change during commit.
8. **Group ID Mapping**: `SaveGroups` always populates `OldGroupIdToNewGroupId` for non-embedded static groups.
---
## 4. Dependencies
### This module depends on:
- **DTS.Common.Import.Interfaces** - `IPersistImport` interface (inferred)
- **DTS.Common.Settings** - `SettingsDB` for global settings persistence
- **DTS.SensorDB** - `SensorModelCollection`, `SensorsCollection` for sensor data
- **DTS.Slice.Users** - `User`, `UserCollection`, `IUIItems` for user management
- **DataPROWin7.DataModel** - Core data models (`TestTemplate`, `DASHardware`, `CustomerDetails`, `LabratoryDetails`, `TestEngineerDetails`, `CustomChannel`, etc.)
- **DTS.Common.Import.Enums** - `ImportStatus`, `ImportExtraStatus`, `PossibleStatus`, `ImportFileFormat`, `ImportSeverityError`
- **DTS.Common.Interface.Channels** - Channel interfaces
- **DTS.Common.Interface.Groups.GroupList** - `IGroup`, `IGroupChannel`, `GroupHelper`
- **DTS.Common.SharedResource.Strings** - `StringResources` for localized error messages
- **DTS.Common.Storage** - `DbOperations` for database queries
- **DTS.Common.ISO** - `ISO13499FileDb`, `IsoCodeStatics`, `MMEPossibleChannels`
- **DTS.Common.Classes.Groups.ChannelSettings** - `ChannelSettingBase`, `IChannelSetting`
- **DTS.Common.Interface.DASFactory.Diagnostics** - Diagnostics interfaces
- **DTS.Common.Enums** - `SupportedExportFormatBitFlags`
### What depends on this module:
- Cannot be determined from source alone (no consumers shown).
---
## 5. Gotchas
1. **SaveServer is unimplemented**: Calling `Save()` on `SaveServer` throws `NotImplementedException`.
2. **SaveCustomerDetails status typo**: Sets `ImportExtraStatus.ReadingLabDetails` instead of a customer-specific status (likely copy-paste error from `SaveLabDetails`).
3. **SaveUsers admin assertion**: Uses `Trace.Assert` to verify admin status — this only triggers in debug builds; production builds will silently proceed with potentially unauthorized operations.
4. **SaveGroupTemplates does nothing**: Iterates group templates but performs no persistence — only updates progress.
5. **Division by zero risk**: `PersistCalculator.ProgressValue` returns `_done / _total` without checking if `_total` is zero.
6. **SaveHardware sorts in-place**: Calls `_importObject.Hardware().ToList().Sort()` but then iterates the original `_importObject.Hardware()` — unclear if this has any effect since `ToList()` creates a copy.
7. **SaveCustomChannels memory concern**: Contains commented-out `GC.Collect()` with a code smell note referencing issue #11287 (out of memory exceptions on large CSV imports).
8. **Interdependent save order**: `SaveGroups` requires `SaveHardware` to be executed first (needs `OldDASIdToNewDASId`). `SaveTestSetup` requires `SaveCustomChannels`, `SaveHardware`, and `SaveGroups`. Order of execution matters.
9. **SaveCheckoutTestSetup clears groups**: Explicitly clears `t.Groups` and `t.ChannelsForGroup` before repopulating — this modifies the import object state.
10. **SaveTestSetup and SaveCheckoutTestSetup delete existing setups**: Both call `DeleteExistingTestSetups()` which removes existing test setups by name before importing.

View File

@@ -0,0 +1,50 @@
---
source_files:
- Common/DTS.Common.Import/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:45:05.560734+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "528b9a9492c4b445"
---
# Documentation: DTS.Common.Import (Assembly Metadata)
## 1. Purpose
This file provides assembly-level metadata and configuration for the `DTS.Common.Import` library. It exists to define the assembly's identity, versioning scheme, visibility settings for COM interop, and legal information (copyright/trademark) within the .NET build ecosystem. It contains no executable business logic.
## 2. Public Interface
This source file contains no public classes, methods, or functions. It exclusively defines assembly-level attributes that apply to the compiled output `DTS.Common.Import.dll`.
**Defined Attributes:**
* **`AssemblyTitle`**: Set to `"DTS.Common.Import"`.
* **`AssemblyDescription`**: Set to an empty string.
* **`AssemblyConfiguration`**: Set to an empty string.
* **`AssemblyCompany`**: Set to an empty string.
* **`AssemblyProduct`**: Set to `"DTS.Common.Import"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2023"`.
* **`AssemblyTrademark`**: Set to an empty string.
* **`AssemblyCulture`**: Set to an empty string (indicating the assembly is culture-neutral).
* **`ComVisible`**: Set to `false`. Types in this assembly are not visible to COM components.
* **`Guid`**: Set to `"c1bc06f4-8657-4892-bc4d-1064da01c4c7"`. This is the unique identifier for the type library if exposed to COM.
* **`AssemblyVersion`**: Set to `"1.0.0.0"`.
* **`AssemblyFileVersion`**: Set to `"1.0.0.0"`.
## 3. Invariants
* **COM Visibility:** The attribute `ComVisible(false)` ensures that all types within this assembly are not exposed to COM by default. To expose a specific type, it must be explicitly decorated with `[ComVisible(true)]`.
* **Culture Neutrality:** The `AssemblyCulture` attribute is empty, enforcing that this is a code assembly rather than a satellite resource assembly (which would require a culture string).
* **Versioning:** Both the assembly version and file version are currently locked to `1.0.0.0`.
## 4. Dependencies
**Internal Dependencies (Imports):**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
**External Dependencies:**
* Consumers of this assembly depend on the `DTS.Common.Import` binary. The specific consumers cannot be determined from this file alone.
## 5. Gotchas
* **Hardcoded Versions:** The `AssemblyVersion` and `AssemblyFileVersion` are hardcoded as string literals (`"1.0.0.0"`). They are not configured to auto-increment (the commented-out wildcard syntax `1.0.*` is not active).
* **SDK Style Projects:** If this project is migrated to the newer SDK-style `.csproj` format, these attributes may conflict with auto-generated assembly info unless `<GenerateAssemblyInfo>false</GenerateAssemblyInfo>` is set in the project file.
* **Missing Metadata:** Several informational attributes (`Description`, `Configuration`, `Company`) are explicitly set to empty strings, which may result in sparse metadata in the compiled DLL properties.

View File

@@ -0,0 +1,360 @@
---
source_files:
- Common/DTS.Common.Import/XML/XMLPre20ParseGroupTemplates.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomDirections.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomTestObjects.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomPositions.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomFineLoc3s.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomFineLoc2s.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomFineLoc1s.cs
- Common/DTS.Common.Import/XML/XMLParseSensorModels.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomFilterClasses.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomChannels.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomMainLocations.cs
- Common/DTS.Common.Import/XML/XMLParseMMECustomPhysicalDimensions.cs
- Common/DTS.Common.Import/XML/XMLPre20ParseSensors.cs
- Common/DTS.Common.Import/XML/XMLParseUsers.cs
- Common/DTS.Common.Import/XML/XMLParseBase.cs
- Common/DTS.Common.Import/XML/XMLParseTestEngineerDetails.cs
- Common/DTS.Common.Import/XML/XMLParseLabDetails.cs
- Common/DTS.Common.Import/XML/XMLParseGlobalSettings.cs
- Common/DTS.Common.Import/XML/XMLPre20ParseDASList.cs
- Common/DTS.Common.Import/XML/XMLParseCustomerDetails.cs
- Common/DTS.Common.Import/XML/XMLParseSensors.cs
- Common/DTS.Common.Import/XML/XMLParseDASList.cs
- Common/DTS.Common.Import/XML/XMLParseGroupTemplates.cs
- Common/DTS.Common.Import/XML/XMLParseCalibrations.cs
- Common/DTS.Common.Import/XML/XMLPre20ParseCalibrations.cs
- Common/DTS.Common.Import/XML/XMLParseGroups.cs
- Common/DTS.Common.Import/XML/XMLParseTestSetups.cs
generated_at: "2026-04-16T11:44:54.944851+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "87dec39982bd8179"
---
# Documentation: DTS.Common.Import.XML Parsers
## 1. Purpose
This module provides a family of XML parsing classes for importing configuration and data entities into the DTS system. Each parser handles a specific domain entity (sensors, hardware, groups, test setups, calibrations, MME custom definitions, etc.) by reading XML elements and populating an `ImportObject`. The module supports versioned imports (handling pre-2.0, 1.0, and 2.1+ formats) with ID normalization to avoid collisions with existing database records. All parsers inherit from `XMLParseBase` and implement `IParseVariant`, enabling a strategy pattern for import operations.
---
## 2. Public Interface
### XMLParseBase (Abstract Base Class)
```csharp
public abstract class XMLParseBase : IParseVariant
{
// Properties
public string FileName { get; set; }
// Abstract method
public abstract void Parse(ref ImportObject importObject);
// Constructor
protected XMLParseBase(XmlElement root, double importedVersion, Func<bool> isCancelled = null, bool skipNormalizing = false)
// Protected methods
protected XmlElement GetXmlElement()
protected bool IsCancelled() // via delegate
}
```
**Behavior**: Base class providing shared infrastructure for all XML parsers. Maintains static ID mapping dictionaries for DAS, group, sensor, and channel IDs. Provides cancellation support via delegate and XML document building utilities via `XmlWriter`.
---
### XMLParseDASList
```csharp
public XMLParseDASList(XmlElement root, double importedVersion, Func<bool> isCancelled = null, bool skipNormalizing = false)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public List<DASHardware> ParseDASList(XmlElement root)
private XmlElement ConvertDASList(List<DASHardware> dasList)
```
**Behavior**: Parses DAS (Data Acquisition System) hardware entries. Normalizes DAS IDs starting at -2 (preserving -1 for unassigned channels). Validates hardware types against `DTS.Common.Enums.Hardware.HardwareTypes`. Clears `_dasIdMapping` on construction.
---
### XMLParseSensors
```csharp
public XMLParseSensors(XmlElement root, double importedVersion, Func<bool> isCancelled = null, bool skipNormalizing = false)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public XmlElement ConvertSensors(IEnumerable<SensorData> sensors)
public IEnumerable<SensorData> ParseSensors(XmlElement root)
```
**Behavior**: Parses sensor data entries. Normalizes sensor `DatabaseId` starting at -2 (preserving -1 for invalid). Populates `_sensorIdMapping` during conversion. Optionally skips normalization via `_skipNormalizing`.
---
### XMLParseGroups
```csharp
public XMLParseGroups(XmlElement root, double importedVersion, Func<bool> isCancelled = null)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public List<IGroup> ParseGroups(XmlElement root, ref ImportObject importObject)
private XmlElement ConvertGroups(List<IGroup> staticGroups)
```
**Behavior**: Parses static group definitions. Normalizes group IDs starting at -2. Maps group IDs by string (name) for pre-2.1 exports, by integer ID for 2.1+. Remaps DAS and sensor IDs in group channels using `_dasIdMapping` and `_sensorIdMapping`. Clears `_groupIdMapping` on construction.
---
### XMLParseTestSetups
```csharp
public XMLParseTestSetups(XmlElement root, double importedVersion, Func<bool> isCancelled = null, bool skipNormalizing = false)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public IEnumerable<TestTemplate> ParseTestTemplate(ImportObject importObject, XmlElement root)
private XmlElement ConvertTestTemplates(IEnumerable<TestTemplate> testTemplates, ImportObject importObject)
```
**Behavior**: Parses test setup templates. Normalizes channel IDs starting at -1. Remaps DAS, sensor, and group IDs using the static mapping dictionaries. Handles embedded groups and deleted sensor references gracefully. Clears `_channelIdMapping` on construction. Sets `importObject.TestSetupImportFileFormat` based on template count.
---
### XMLParseCalibrations
```csharp
public XMLParseCalibrations(XmlElement root, double importedVersion, Func<bool> isCancelled = null)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public XmlElement ConvertCalibrations(IEnumerable<SensorCalibration> calibrations)
public IEnumerable<SensorCalibration> ParseCalibrations(XmlElement root)
```
**Behavior**: Parses sensor calibration data. Handles version-specific logic: for version 1.0, sets `AtCapacity = false` and derives `SensitivityUnits` based on `NonLinear` and `IsProportional` flags. Uses `FileUtils.DataPROPre20XmlVersion` threshold.
---
### XMLParseGroupTemplates
```csharp
public XMLParseGroupTemplates(XmlElement root, double importedVersion, ISO.ISO13499FileDb iSO13499FileDb, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
public IEnumerable<DataPROWin7.DataModel.TestObjectTemplate> ParseGroupTemplates(ref ImportObject importObject, XmlElement root)
```
**Behavior**: Parses group templates (test object templates). Requires `ISO13499FileDb` reference. Sets `Embedded = true` for system-built or embedded templates. Throws `NotSupportedException` if referenced ISO test object is not found in import file.
---
### XMLParseUsers
```csharp
public XMLParseUsers(XmlElement root, double importedVersion, IEnumerable<IUIItems> uiItems, Func<bool> isCancelled = null)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
private IEnumerable<User> ParseUsers(XmlElement root, IEnumerable<IUIItems> iUItems)
```
**Behavior**: Parses user records. Requires `IEnumerable<IUIItems>` for user construction. Sets import status to `ReadingUsers`.
---
### XMLParseGlobalSettings
```csharp
public XMLParseGlobalSettings(XmlElement root, double importedVersion, Func<bool> isCancelled = null)
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
private Dictionary<string, string> ParseGlobalSettings(XmlElement root)
private void GetGlobalSetting(XmlElement node, ref Dictionary<string, string> settings)
```
**Behavior**: Parses global settings into a `Dictionary<string, string>`. Reads `SettingName` and `SettingValue` child elements.
---
### XMLParseSensorModels
```csharp
public XMLParseSensorModels(XmlElement root, double importedVersion, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
private List<SensorModel> ParseSensorModels(XmlElement root)
```
**Behavior**: Parses sensor model definitions. Creates new `SensorModel` instances and calls `ReadXML` on each.
---
### MME Custom Parsers (8 classes)
All follow the same pattern:
```csharp
// XMLParseMMECustomDirections
public override void Parse(ref ImportObject importObject)
private IEnumerable<ISO.MMEDirections> ParseCustomDirections(XmlElement root)
// XMLParseMMECustomTestObjects
public override void Parse(ref ImportObject importObject)
public IEnumerable<ISO.MMETestObjects> ParseCustomTestObjects(XmlElement root)
// XMLParseMMECustomPositions
public override void Parse(ref ImportObject importObject)
private IEnumerable<ISO.MMEPositions> ParsePhysicalDimensions(XmlElement root)
// XMLParseMMECustomFineLoc1s/2s/3s
public override void Parse(ref ImportObject importObject)
private IEnumerable<ISO.MMEFineLocations1/2/3> ParseCustomFineLoc1s/2s/3s(XmlElement root)
// XMLParseMMECustomFilterClasses
public override void Parse(ref ImportObject importObject)
private IEnumerable<ISO.MMEFilterClasses> ParseMMECustomFilterClasses(XmlElement root)
// XMLParseMMECustomChannels
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
public IEnumerable<ISO.MMEPossibleChannels> ParseCustomChannels(XmlElement root)
// XMLParseMMECustomMainLocations
public override void Parse(ref ImportObject importObject)
public IEnumerable<ISO.MMETransducerMainLocation> ParseCustomMainLocations(XmlElement root)
// XMLParseMMECustomPhysicalDimensions
public override void Parse(ref ImportObject importObject)
private IEnumerable<ISO.MMEPhysicalDimensions> ParsePhysicalDimensions(XmlElement root)
```
**Behavior**: Each parses ISO MME (Measurement Module Equipment) custom definitions by iterating child nodes and calling `ReadXML` on the appropriate ISO type.
---
### Detail Parsers (3 classes)
```csharp
// XMLParseCustomerDetails
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
private XmlElement ConvertCustomerDetails(IEnumerable<ISO.CustomerDetails> customerDetails)
private List<ISO.CustomerDetails> ParseCustomerDetails(XmlElement root)
// XMLParseTestEngineerDetails
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
private XmlElement ConvertTestEngineerDetails(IEnumerable<ISO.TestEngineerDetails> details)
private List<ISO.TestEngineerDetails> ParseTestEngineerDetails(XmlElement root)
// XMLParseLabDetails
public IImportNotification ImportNotification { get; set; }
public override void Parse(ref ImportObject importObject)
private XmlElement ConvertLabDetails(IEnumerable<ISO.LabratoryDetails> details)
private List<ISO.LabratoryDetails> ParseLabDetails(XmlElement root)
```
**Behavior**: Parse and re-serialize detail records. Set import status notifications.
---
### Pre-20 Version Parsers (4 classes)
```csharp
// XMLPre20ParseDASList
public XMLPre20ParseDASList(XmlElement root, double importedVersion, XMLParseDASList xmlParseDASList, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
public List<DASHardware> ParsePre20DASList(XmlElement root)
private XmlElement MigratePre20DASList(List<DASHardware> dasList)
// XMLPre20ParseSensors
public XMLPre20ParseSensors(XmlElement root, double importedVersion, XMLParseSensors xmlParseSensors, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
public XmlElement MigrateSensors(IEnumerable<SensorData> sensors)
// XMLPre20ParseCalibrations
public XMLPre20ParseCalibrations(XmlElement root, double importedVersion, XMLParseCalibrations xmlParseCalibrations, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
private IEnumerable<SensorCalibration> ParsePre20Calibrations(ref ImportObject importObject)
// XMLPre20ParseGroupTemplates
public XMLPre20ParseGroupTemplates(XmlElement root, double importedVersion, XMLParseGroupTemplates xmlParseGroupTemplates, Func<bool> isCancelled = null)
public override void Parse(ref ImportObject importObject)
```
**Behavior**: Handle migration from pre-2.0 XML formats. Delegate to corresponding non-Pre20 parser after initial parsing. Use negative ID assignment starting at -1 for sensors/DAS.
---
## 3. Invariants
1. **ID Normalization**: All normalized IDs are negative integers. DAS and sensor normalization starts at -2 (preserving -1 for "unassigned/invalid"). Group normalization starts at -2. Channel normalization starts at -1.
2. **Mapping Dictionary Lifecycle**:
- `_dasIdMapping` is cleared in `XMLParseDASList` constructor
- `_groupIdMapping` is cleared in `XMLParseGroups` constructor
- `_channelIdMapping` is cleared in `XMLParseTestSetups` constructor
- `_sensorIdMapping` is NOT explicitly cleared (relies on static initialization)
3. **Import Order Dependency**: Parsers must be invoked in dependency order (DAS → Sensors → Groups → TestSetups) because later parsers use mapping dictionaries populated by earlier parsers.
4. **Cancellation Contract**: When `IsCancelled()` returns true, parsers return their partially-filled collection immediately.
5. **Version Thresholds**:
- `1.0D`: Legacy format requiring calibration unit inference
- `FileUtils.DataPROPre20XmlVersion`: Pre-2.0 format threshold
- `FileUtils.DataPRO21XmlVersion`: 2.1+ format (uses integer group IDs instead of names)
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Import.Interfaces` - `IParseVariant`, `ImportObject`, `IImportNotification`, `ImportStatus`, `ImportError`, `ImportSeverityError`
- `DTS.Common.Enums.DBExport` - `TopLevelFields` enum
- `DTS.Common.Enums` - Various enums
- `DTS.Common.Interface` - `IUIItems`, sensor interfaces
- `DTS.Common.Interface.Groups.GroupList` - `IGroup`, group interfaces
- `DTS.Common.Interface.GroupTemplate` - Group template interfaces
- `DTS.Common.SharedResource.Strings` - `StringResources` for error messages
- `DTS.Common.Utils` - `FileUtils` with version constants
- `DTS.SensorDB` - `SensorData`, `SensorModel`, `SensorCalibration`, `SensorConstants`
- `DTS.Slice.Users` - `User` class
- `DataPROWin7.DataModel` - `DASHardware`, `TestObjectTemplate`, `TestObject`
- `DTS.Common.Classes.TestSetups` - `TestTemplate`
- `DTS.Common.ISO` / `ISO` namespace - MME types (`MMEDirections`, `MMETestObjects`, `MMEPositions`, `MMEFineLocations1/2/3`, `MMEFilterClasses`, `MMEPossibleChannels`, `MMETransducerMainLocation`, `MMEPhysicalDimensions`, `CustomerDetails`, `TestEngineerDetails`, `LabratoryDetails`)
- `System.Xml` - `XmlElement`, `XmlDocument`, `XmlWriter`
### What depends on this module:
- Unknown from source alone (no consumers shown in imports)
---
## 5. Gotchas
1. **Static Mapping Dictionaries**: The ID mapping dictionaries (`_dasIdMapping`, `_groupIdMapping`, `_sensorIdMapping`, `_channelIdMapping`) are `static`, meaning they persist across parser instances. If parsers are instantiated out of order or reused, stale mappings could cause incorrect ID translations.
2. **Inconsistent Cancellation Checks**: `XMLParseMMECustomChannels.ParseCustomChannels` does NOT check `IsCancelled()` during iteration, unlike all other MME parsers. This could lead to non-responsive cancellation for large channel imports.
3. **Pre-20 vs Standard ID Normalization Difference**:
- `XMLPre20ParseSensors` and `XMLPre20ParseDASList` start normalization at -1
- `XMLParseSensors` and `XMLParseDASList` start at -2
This inconsistency may be intentional (different handling for pre-2.0 imports) but could cause confusion.
4. **Unused Invalid DAS Collection**: In `XMLParseDASList.ParseDASList`, invalid DAS serial numbers are collected into `invalidDAS` list but the subsequent `if (invalidDAS.Any()) { //??? }` block is empty, suggesting incomplete error handling.
5. **Group ID Mapping Key Type**: `_groupIdMapping` uses `string` keys to handle both old exports (group name) and new exports (integer ID as string). This dual-mode requires careful version checking via `_importedVersion >= FileUtils.DataPRO21XmlVersion`.
6. **Missing Sensor Handling**: In `XMLParseGroups` and `XMLParseTestSetups`, if a sensor ID is not found in `_sensorIdMapping`, it's silently set to 0 rather than failing (per FB 14308). This handles deleted sensors gracefully but may mask data integrity issues.
7. **XMLParseMMECustomChannels Public ImportNotification**: The `ImportNotification` property on `XMLParseMMECustomChannels` is never used within the class, unlike other parsers that call `SetStatus`.
8. **Ref Parameter Patterns**: Several methods pass `ImportObject` by `ref` even when not reassigning the variable, which is unnecessary but harmless.

View File

@@ -0,0 +1,154 @@
---
source_files:
- Common/DTS.Common.Property/PropertyModule.cs
generated_at: "2026-04-16T11:33:44.285966+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5ade2343bf1c7a50"
---
# Documentation: DTS.Common.Property Module
## 1. Purpose
This module serves as a Prism-based plugin module for a modular WPF application. It registers property-related UI components (a view and view-model) with the Unity dependency injection container and provides assembly-level metadata (name, image, region, and group) that the main application uses to display and categorize this component. It is part of a larger plugin architecture where modules self-register at startup.
---
## 2. Public Interface
### `PropertyModule` Class
**Signature:**
```csharp
[Export(typeof(IModule))]
[Module(ModuleName = "Property")]
public class PropertyModule : IModule
```
**Constructor:**
```csharp
public PropertyModule(IUnityContainer unityContainer)
```
Accepts an injected `IUnityContainer` instance and stores it in a readonly field.
**Methods:**
```csharp
public void Initialize()
```
Registers the following type mappings with Unity (transient lifetime, not singleton despite the comment):
- `IPropertyView``PropertyView`
- `IPropertyViewModel``PropertyViewModel`
---
### `PropertiesNameAttribute` Class
**Signature:**
```csharp
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public class PropertiesNameAttribute : TextAttribute
```
**Constructors:**
```csharp
public PropertiesNameAttribute()
public PropertiesNameAttribute(string s)
```
Both constructors initialize `_assemblyName` to the hardcoded string `"PropertiesAsssembly"`.
**Properties:**
```csharp
public override string AssemblyName { get; }
```
Returns the hardcoded assembly name.
**Methods:**
```csharp
public override Type GetAttributeType() // Returns typeof(TextAttribute)
public override string GetAssemblyName() // Returns AssemblyName property
```
---
### `PropertiesImageAttribute` Class
**Signature:**
```csharp
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public class PropertiesImageAttribute : ImageAttribute
```
**Constructors:**
```csharp
public PropertiesImageAttribute()
public PropertiesImageAttribute(string s)
```
Both constructors initialize `_img` via `AssemblyInfo.GetImage(AssemblyNames.Property.ToString())`.
**Properties:**
| Property | Return Type | Value |
|----------|-------------|-------|
| `AssemblyImage` | `BitmapImage` | Loaded via `AssemblyInfo.GetImage(AssemblyNames.Property.ToString())` |
| `AssemblyName` | `string` | `AssemblyNames.Property.ToString()` |
| `AssemblyGroup` | `string` | `eAssemblyGroups.Viewer.ToString()` |
| `AssemblyRegion` | `eAssemblyRegion` | `eAssemblyRegion.PropertyRegion` |
**Methods:**
```csharp
public override Type GetAttributeType() // Returns typeof(ImageAttribute)
public override BitmapImage GetAssemblyImage() // Returns AssemblyImage property
public override string GetAssemblyName() // Returns AssemblyName property
public override eAssemblyRegion GetAssemblyRegion() // Returns AssemblyRegion property
public override string GetAssemblyGroup() // Returns AssemblyGroup property
```
---
## 3. Invariants
1. **Single Instance per Assembly**: Both `PropertiesNameAttribute` and `PropertiesImageAttribute` are applied at assembly level with `AllowMultiple = false`, ensuring exactly one instance of each per assembly.
2. **Module Registration Order**: The `Initialize()` method must be called after the Unity container is fully constructed but before any code attempts to resolve `IPropertyView` or `IPropertyViewModel`.
3. **Attribute Base Class Requirements**: Both attribute classes inherit from abstract base classes (`TextAttribute` and `ImageAttribute` respectively) that are not defined in this file but must exist in `DTS.Common.Interface` or another referenced assembly.
4. **Image Resource Availability**: `AssemblyInfo.GetImage()` must be able to locate an image resource keyed by `AssemblyNames.Property.ToString()` at the time the attribute is queried.
---
## 4. Dependencies
### This Module Depends On:
| Dependency | Purpose |
|------------|---------|
| `Microsoft.Practices.Prism.Modularity` | Provides `IModule` interface and `ModuleAttribute` for plugin architecture |
| `Microsoft.Practices.Unity` | Provides `IUnityContainer` for dependency injection |
| `System.ComponentModel.Composition` | Provides MEF `ExportAttribute` |
| `System.Windows.Media.Imaging` | Provides `BitmapImage` for assembly icon |
| `DTS.Common.Interface` | Defines `TextAttribute`, `ImageAttribute`, `IPropertyView`, `IPropertyViewModel` |
| `AssemblyInfo` (location unclear) | Static utility class with `GetImage()` method |
| `AssemblyNames` (enum, location unclear) | Enum containing `Property` value |
| `eAssemblyGroups` (enum, location unclear) | Enum containing `Viewer` value |
| `eAssemblyRegion` (enum, location unclear) | Enum containing `PropertyRegion` value |
| `PropertyView` (location unclear) | Concrete type implementing `IPropertyView` |
| `PropertyViewModel` (location unclear) | Concrete type implementing `IPropertyViewModel` |
### What Depends On This Module:
- The main application shell, which discovers and loads Prism modules via MEF exports and reads assembly-level attributes for UI display.
---
## 5. Gotchas
1. **Typo in Assembly Name**: `PropertiesNameAttribute` hardcodes `_assemblyName = "PropertiesAsssembly"` with three consecutive 's' characters. This may cause lookup failures if other code expects correct spelling.
2. **Misleading XML Comment**: The constructor XML doc references `<see cref="PropertiesModule"/>` but the actual class name is `PropertyModule` (no 's').
3. **Comment Inaccuracy**: The comment in `Initialize()` states "Register View & View-Model... as a singleton" but `RegisterType` registers types with transient lifetime by default. To register as singleton, `ContainerControlledLifetimeManager` would be required.
4. **Unused Constructor Parameters**: Both attribute classes accept a `string s` parameter in their constructors but completely ignore it, always using hardcoded values instead.
5. **Side Effects in Property Getters**: The `AssemblyImage` property getter has a side effect (assigning to `_img` field), which violates typical property getter conventions and could cause unexpected behavior if the property is accessed multiple times.
6. **Lazy Initialization Pattern Inconsistency**: The `AssemblyName`, `AssemblyGroup`, and `AssemblyRegion` properties in `PropertiesImageAttribute` assign to their backing fields on every get, making them behave more like methods than properties.

View File

@@ -0,0 +1,53 @@
---
source_files:
- Common/DTS.Common.Security/Encryption.cs
generated_at: "2026-04-16T11:36:14.772984+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2d41661347ec3dbc"
---
# Documentation: DTS.Common.Security.Encryption
## 1. Purpose
The `Encryption` static class provides symmetric encryption and decryption utilities for the DTS system. It serves as a wrapper around the `AesCryptoServiceProvider` to securely convert plaintext strings into byte arrays and vice versa. This module centralizes AES encryption logic to ensure consistent cryptographic handling across the application.
## 2. Public Interface
### `public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)`
Encrypts a specified plaintext string into an array of bytes using the AES algorithm.
* **Parameters:**
* `plainText` (string): The text to encrypt.
* `key` (byte[]): The secret key for the symmetric algorithm.
* `iv` (byte[]): The initialization vector (IV) for the symmetric algorithm.
* **Returns:** A byte array containing the encrypted data.
* **Exceptions:** Throws `ArgumentNullException` if `plainText`, `key`, or `iv` are null or empty.
### `public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)`
Decrypts a specified byte array back into a plaintext string using the AES algorithm.
* **Parameters:**
* `cipherText` (byte[]): The byte array containing encrypted data.
* `key` (byte[]): The secret key used for encryption.
* `iv` (byte[]): The initialization vector used for encryption.
* **Returns:** The decrypted plaintext string.
* **Exceptions:** Throws `ArgumentNullException` if `cipherText`, `key`, or `iv` are null or empty.
## 3. Invariants
* **Null Checks:** All input parameters (`plainText`, `cipherText`, `key`, `iv`) must be non-null and have a length greater than zero. Failure to meet this condition results in an `ArgumentNullException`.
* **Algorithm Consistency:** Both methods utilize `AesCryptoServiceProvider` (AES). The key and IV provided to `DecryptStringFromBytes` must match those used in `EncryptStringToBytes` for decryption to succeed.
* **Stream Encoding:** The implementation uses `StreamWriter` and `StreamReader` for stream transformations. The specific character encoding is not explicitly defined in the method signatures, relying on the default encoding of the underlying stream writer/reader (typically UTF-8).
## 4. Dependencies
* **Internal Dependencies:** None identified within the provided source.
* **External Dependencies:**
* `System`: For basic types and exceptions.
* `System.IO`: Used for `MemoryStream`, `StreamWriter`, and `StreamReader` to handle data flow during encryption/decryption.
* `System.Security.Cryptography`: Used for `AesCryptoServiceProvider` and `CryptoStream` to perform the cryptographic operations.
* **Unused Dependencies:** The file imports `System.Collections.Generic`, `System.Linq`, `System.Text`, and `System.Threading.Tasks`, but none of these namespaces appear to be utilized in the current implementation.
## 5. Gotchas
* **Copy-Paste Error in Validation:** In both `EncryptStringToBytes` and `DecryptStringFromBytes`, the validation check for the `iv` parameter throws an exception naming the `key` parameter instead.
* *Source Reference:* `if (iv == null || iv.Length <= 0) throw new ArgumentNullException(nameof(key));`
* This will report "key" as the null argument in the exception message when the `iv` is actually the invalid parameter, complicating debugging.
* **Variable Naming Mismatch:** The `AesCryptoServiceProvider` instance is named `rijAlg` in both methods. This is likely a legacy artifact from a previous implementation using `RijndaelManaged`, which may cause confusion as the code now explicitly uses AES.
* **Key/IV Management:** The class provides no mechanism for key or IV generation. Callers are responsible for generating and managing valid AES keys and IVs. Passing invalid key/IV lengths will cause the underlying `AesCryptoServiceProvider` to throw a `CryptographicException`, which is not caught by this wrapper.

View File

@@ -0,0 +1,227 @@
---
source_files:
- Common/DTS.Common.Serialization/StringWriterWithEncoding.cs
- Common/DTS.Common.Serialization/TickEventHandler.cs
- Common/DTS.Common.Serialization/InvariantStreamWriter.cs
- Common/DTS.Common.Serialization/BadCRCBypass.cs
- Common/DTS.Common.Serialization/IProgressAware.cs
- Common/DTS.Common.Serialization/ToyotaCsv.File.cs
- Common/DTS.Common.Serialization/EventHandlers.cs
- Common/DTS.Common.Serialization/Test.IConvertable.cs
- Common/DTS.Common.Serialization/TestSetup.TestObject.Channel.cs
- Common/DTS.Common.Serialization/Test.Module.IConvertable.cs
- Common/DTS.Common.Serialization/Test.Module.Channel.IConvertable.cs
- Common/DTS.Common.Serialization/TestSetup.TestObject.DASHardware.cs
- Common/DTS.Common.Serialization/TestSetup.Sensor.cs
- Common/DTS.Common.Serialization/File.Writer.cs
- Common/DTS.Common.Serialization/IReadable.cs
- Common/DTS.Common.Serialization/TestSetup.Graph.cs
- Common/DTS.Common.Serialization/FilteredData.cs
- Common/DTS.Common.Serialization/File.Writer.CharacterCountingStreamWriter.cs
- Common/DTS.Common.Serialization/Diadem.File.cs
- Common/DTS.Common.Serialization/TestSetup.TestObject.DASHardware.DASChannel.cs
- Common/DTS.Common.Serialization/File.cs
- Common/DTS.Common.Serialization/File.Reader.cs
- Common/DTS.Common.Serialization/TestSetup.Graph.Channel.cs
- Common/DTS.Common.Serialization/EventInfoAggregate.cs
- Common/DTS.Common.Serialization/IWriteable.cs
generated_at: "2026-04-16T11:37:25.731360+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2a2f1c17484ea7d0"
---
# DTS.Serialization Module Documentation
## 1. Purpose
The `DTS.Serialization` module provides a framework for serializing and deserializing test data to various file formats (Toyota CSV, Diadem, etc.). It defines abstract base classes (`File`, `File.Reader<T>`, `File.Writer<T>`) and interfaces (`IReadable<T>`, `IWritable<T>`, `IReader<T>`, `IWriter<T>`) that establish a consistent pattern for file import/export operations. The module also contains domain models for test setups (`TestSetup`, `Test`, `FilteredData`) and supports progress reporting during long-running serialization operations via event handlers.
---
## 2. Public Interface
### Core File Abstractions
#### `File` (abstract partial class)
- **Signature:** `public abstract partial class File : Exceptional`
- **Constructor:** `File(string formatName)` - Initializes with a format name.
- **Properties:**
- `string FormatName` (get, private set) - The format name of this file.
- `int DefaultEncoding` (get, set) - Defaults to `Encoding.UTF8.CodePage`.
- `static string BaseExportDirectory` (get, set) - Static base path for exports.
- `static bool UseLegacyTDCSoftwareFiltering` (get, set) - Controls filtered data sample adjustment.
- `Common.Enums.IsoViewMode ISOViewMode` (get, set)
- **Methods:**
- `virtual void SetEUData(string channelID, FilteredData fd)` - Stores EU data for linearized channels.
- `virtual FilteredData GetEUData(string channelID)` - Retrieves EU data.
- `virtual int GetChannelNumberFromChannelFileName(string channelFileName)` - Returns -1 by default; overridden in subclasses.
- `protected string EnsureTrailingBackslashOnPathString(string path)` - Normalizes path strings.
#### `File.Reader<T>` (abstract class)
- **Signature:** `public abstract class Reader<T> : Exceptional, IReader where T : File`
- **Constructor:** `protected Reader(T fileType)` - Protected; readers created via File-level factory.
- **Properties:**
- `protected T FileType` - The associated file type.
- `protected ChannelFilenameComparer ChFileCompare` - Comparer for channel filenames.
- **Nested Class:** `ChannelFilenameComparer : IComparer<string>` - Compares channel filenames using `GetChannelNumberFromChannelFileName`.
#### `File.Writer<T>` (abstract partial class)
- **Signature:** `public abstract partial class Writer<T> : Exceptional, IWriter where T : File`
- **Constructor:** `public Writer(T fileType, int encoding)`
- **Properties:**
- `protected T FileType` - The associated file type.
- `virtual int DefaultEncoding` (get, set)
- **Nested Class:** `CharacterCountingStreamWriter : StreamWriter` - Counts characters written via `WriteLine(string)`. Property: `uint CharactersCounted`.
### Interfaces
#### `IReadable` / `IReadable<T>`
- Marker interfaces for readable file types.
- `IReadable<T>.Importer` returns `IReader<T>`.
#### `IWritable` / `IWritable<T>`
- Marker interfaces for writable file types.
- `IWritable<T>.Exporter` returns `IWriter<T>`.
#### `IReader<T>`
- **Method:** `void Read(string pathname, out T target)` - Deserializes file into target object.
#### `IWriter<T>`
- **Methods:**
- `void Write(string pathname, string id, T target, bool bFiltering, bool includeGroupNameInISOExport, double minStartTime, int dataCollectionLength)`
- `void Write(string pathname, string id, string dataFolder, T target, bool bFiltering, bool includeGroupNameInISOExport, FilteredData fd, Test.Module.Channel tmChannel, int channelNumber, BeginEventHandler onBeginEvent, CancelEventHandler onCancelEvent, EndEventHandler onEndEvent, TickEventHandler onTickEvent, ErrorEventHandler onErrorEvent, CancelRequested cancelRequested, double minStartTime, int dataCollectionLength)`
- `void Initialize(...)` - Same parameters as Write minus minStartTime and dataCollectionLength.
#### `IProgressAware`
- **Events:** `OnBegin`, `OnEnd`, `OnTick`, `OnCancel`, `OnError`
### Event Delegates
- `delegate void TickEventHandler(object sender, double percentageComplete)`
- `delegate void BeginEventHandler(object sender, uint numberOfTicks)`
- `delegate void EndEventHandler(object sender)`
- `delegate void CancelEventHandler(object sender)`
- `delegate void ErrorEventHandler(object sender, Exception ex)`
- `delegate bool CancelRequested()`
### Utility Classes
#### `StringWriterWithEncoding`
- **Signature:** `public sealed class StringWriterWithEncoding : StringWriter`
- **Constructor:** `StringWriterWithEncoding(Encoding encoding)`
- **Property:** `override Encoding Encoding` - Returns the encoding passed to constructor.
#### `InvariantStreamWriter`
- **Signature:** `public class InvariantStreamWriter : System.IO.StreamWriter`
- **Constructors:** `InvariantStreamWriter(string path)`, `InvariantStreamWriter(string path, bool bAppend)`
- **Property:** `override IFormatProvider FormatProvider` - Always returns `CultureInfo.InvariantCulture`.
#### `FilteredData`
- **Signature:** `public class FilteredData : Exceptional, IComparable<FilteredData>`
- **Constructor:** `FilteredData(string filterDescription, double filterFrequencyHz, double[] data, int absoluteDisplayOrder)`
- **Properties:** `FilterDescription`, `FilterFrequencyHz`, `Data`, `AbsoluteDisplayOrder` (init-only)
- **Method:** `int CompareTo(FilteredData other)` - Compares by `AbsoluteDisplayOrder`.
### Domain Models
#### `TestSetup` (partial class hierarchy)
- `TestSetup : Exceptional`
- `TestSetup.Sensor : Exceptional` - Properties: `FilterClass`, `Name`, `Polarity`, `Position`, `Range`, `Version`
- `TestSetup.Graph : Exceptional` - Properties: `Channels`, `Name`, `HardwareChannelName`, `DisplayName`, `Version`, `Identifier` (Guid), `IsSingleChannelGraph`, `FirstChannel`, `FirstTestChannel`
- `TestSetup.Graph.Channel : Exceptional` - Properties: `ChannelId`, `ChannelGroupName`, `Name`, `SensorName`, `AxisUnit`, `SerialNumber`, `ParentTestModule`, `TestChannel`
- `TestSetup.TestObject : Exceptional`
- `TestSetup.TestObject.TOChannel : Exceptional` - Properties: `Name`, `SensorName`, `Version`
- `TestSetup.TestObject.DASHardware : Exceptional` - Properties: `DASChannels`, `SampleRate`, `SerialNumber`, `Version`
- `TestSetup.TestObject.DASHardware.DASChannel : Exceptional` - Properties: `Location`, `MeasurementUnits`, `Name`, `NumberOfSamples`, `SensorName`, `SerialNumber`, `Version`
#### `Test` (partial class with nested interfaces)
- `Test.IConvertable` - Interface for converting to/from `Test` objects.
- `Test ToDtsSerializationTest()`
- `void FromDtsSerializationTest(Test test, ReportErrors reportErrors)`
- `Test.Module.IConvertable` - Interface for converting to/from `Test.Module`.
- `Test.Module.Channel.IConvertable` - Interface for converting to/from `Test.Module.Channel`.
#### `EventInfoAggregate`
- Aggregates event info from multiple DAS units.
- **Properties:** `EventId`, `EventDescription`, `DurationSeconds`, `GUID`, `HasBeenDownloaded`, `WasTriggered`, `NumberOfChannels`, `NumberOfSamples`, `NumberOfBytes`, `Faulted`, `EventNumber`
- **Methods:** `GetEvent()`, `GetEvent(bool bClear)`, `GetEventIndex(IDASCommunication idas)`, `GetDasList()`, `Add(DownloadReport.EventInfo newEvent)`
### File Format Implementations
#### `ToyotaCsv.File`
- **Signature:** `public partial class File : Serialization.File, IWritable<Test>`
- **Constructor:** `File()` - Base format name "Toyota CSV".
- **Properties:** `static string Extension => ".csv"`, `IWriter<Test> Exporter`
#### `Diadem.File`
- **Signature:** `public partial class File : Serialization.File, IWritable<Test>`
- **Constructor:** `File(bool bUseEVG20, TestPlan plan)`
- **Properties:** `static string Extension => ".dat"`, `IWriter<Test> Exporter`, `UseIsoCodeForDiadem200`, `UseZeroForUnfiltered`, `ChannelName200Option`, `UserComment201Option`, `Reserved1_301Option`, `Reserved2_302Option`
- **Enums:** `DiademOptions`, `DiademOptionsReserved1`, `DiademOptionsReserved2`
### UI Components
#### `BadCRCBypass` (Windows Forms)
- **Signature:** `public partial class BadCRCBypass : Form`
- **Properties:** `string FileName`, `bool RememberChoice`
- **Events:** `btnOK_Click`, `btnCancel_Click` - Set `DialogResult` and close.
---
## 3. Invariants
1. **Reader/Writer Construction:** `File.Reader<T>` and `File.Writer<T>` are intended to be constructed only by their hosting `File` class via factory methods or properties (Writer constructor is public, Reader constructor is protected).
2. **Encoding Consistency:** `InvariantStreamWriter` always uses `CultureInfo.InvariantCulture` regardless of system locale—this ensures consistent numeric formatting across different regional settings.
3. **Property<T> Pattern:** Domain model classes use `Property<T>` wrappers with namespace-qualified names for property tracking. These are initialized with default values in constructors.
4. **Version Defaults:** All `Version` properties in `TestSetup` nested classes default to `"1.0.0.0"`.
5. **Channel Filename Ordering:** `ChannelFilenameComparer` relies on `GetChannelNumberFromChannelFileName` returning -1 for non-SLICE/TDAS file types, resulting in standard string comparison.
6. **CharacterCountingStreamWriter:** Only `WriteLine(string)` is overridden; other write methods do not update `CharactersCounted`.
---
## 4. Dependencies
### External Dependencies (inferred from imports)
- `System.Text` - Encoding support
- `System.IO` - Stream/StreamWriter base classes
- `System` - Exception handling, IFormatProvider
- `System.Windows.Forms` - BadCRCBypass dialog
- `System.Collections.Generic` - List, Dictionary, IComparer
- `System.Linq` - LINQ operations
- `System.Globalization` - CultureInfo.InvariantCulture
- `System.Xml.Serialization` - XmlIgnoreAttribute
### Internal Dependencies
- `DTS.Common.Utilities` / `DTS.Utilities` - `Exceptional` base class
- `DTS.Common.Utilities.DotNetProgrammingConstructs` / `DTS.Utilities.DotNetProgrammingConstructs` - `Property<T>` wrapper class
- `DTS.Common.ISO` - ISO-related types (used in Diadem)
- `DTS.Common.Utilities.Logging` - `APILogger` (used in EventInfoAggregate)
- `DTS.DASLib.Service` - `IDASCommunication`, `DownloadReport` (used in EventInfoAggregate)
- `Slice.Control.Event` - Event class (used in EventInfoAggregate)
### Dependents (not shown in source)
- Unknown from source alone; likely consumed by export/import modules and test data management components.
---
## 5. Gotchas
1. **CharacterCountingStreamWriter Partial Implementation:** Only `WriteLine(string)` updates the character count. Using `Write()`, `WriteLine(char[])`, or other overloads will not be counted.
2. **IProgressAware Interface Visibility:** The `IProgressAware` interface has no access modifier explicitly shown, making it `internal` by default. It also references `DTS.Serialization.EventHandler` in XML comments, but the actual type is `TickEventHandler` (likely a documentation typo).
3. **Documentation Typos:** In `IProgressAware`, the XML comment for `OnTick` references `DTS.Seralization.EventHandler` (missing 'i' in Serialization).
4. **EventInfoAggregate Mismatched Data Handling:** When `Add()` is called with mismatched event data (different TestIDs, durations, sample counts), the code logs warnings but continues processing, potentially using `Math.Min` for some values. This could lead to data truncation.
5. **TestSetup.Graph.Channel Private Constructor:** Has a private parameterless constructor that sets `ChannelId = "Not Set"`, but public constructors require either a `Test.Module.Channel` or `channelId` string.
6. **FilteredData AbsoluteDisplayOrder:** The property is init-only with a default of -1, but the constructor parameter is required. The `CompareTo` method will use -1 if not properly initialized.
7. **Diadem.File WriterParent Cast:** The `Exporter` property casts `_Exporter` to `Writer` to set `WriterParent`, suggesting tight coupling between the File and Writer classes not expressed in interfaces.

View File

@@ -0,0 +1,135 @@
---
source_files:
- Common/DTS.Common.Serialization/DDAS (Chrysler)/ChannelDefinition.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DDASTestDefinition.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DataFloat.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DDAS.File.cs
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DDASTest.cs
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DDAS.File.Writer.cs
- Common/DTS.Common.Serialization/DDAS (Chrysler)/TSVSettingsWindow.cs
- Common/DTS.Common.Serialization/DDAS (Chrysler)/TSVSettingsWindow.Designer.cs
- Common/DTS.Common.Serialization/DDAS (Chrysler)/DDASChannel.cs
generated_at: "2026-04-16T10:56:49.509276+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "3efc64a6d144d6f5"
---
# DDAS Serialization Module Documentation
## 1. Purpose
This module provides serialization support for the DDAS (DaimlerChrysler Data Acquisition System) file format, enabling reading and writing of test configuration and channel data. It bridges legacy C++ data structures (CHANNEL, FILEINFOBLOCK, TESTINFO, etc.) with a modern C# serialization framework, supporting export of test data including channel metadata, transducer information, and floating-point sample data to the proprietary DDAS ".ddas" and ".fpd" file formats.
---
## 2. Public Interface
### C++ Structures (ChannelDefinition.h)
**`CHANNEL` / `PCHANNEL` / `PCHAN`** - Channel definition structure:
| Field | Type | Description |
|-------|------|-------------|
| `Size` | `short` | Size of this object |
| `Flags` | `short` | Channel flags |
| `Name` | `char[64]` | Channel name |
| `Sign` | `char[8]` | Sign (+, -, or blank) |
| `Axis` | `char[8]` | Axis (X,Y,Z,FX,MX,AX,...) |
| `FilterFreq` | `float` | Channel filter class (Hz) |
| `SetGain` | `float` | Gain setting (1-n) |
| `ActGain` | `float` | Actual (measured) gain |
| `Rcal` | `float` | Shunt calibration resistance |
| `Excitation` | `float` | Excitation voltage (programmable) |
| `byteSpares` | `byte[4]` | Spare bytes (was CalDate) |
| `Transducer` | `TRANSDUCER` | Snapshot of transducer values |
**Channel Macros:**
- `ISCHANACTIVE(pChan)` - Returns 1 if channel active flag is set
- `SETCHANACTIVE(pChan)` - Sets channel active flag
- `CLRCHANACTIVE(pChan)` - Clears channel active flag
**Enumerations:**
- `ChannelFlags { CHANFLAG_ACTIVE }`
---
### C++ Structures (DDASTestDefinition.h)
**`FILEINFOBLOCK`** - File metadata:
| Field | Type | Description |
|-------|------|-------------|
| `Size` | `UINT` | Block size including Size |
| `FileTypeName` | `char[12]` | Software type name |
| `FileTypeVers` | `char[12]` | File version name |
| `FileTypeFlags` | `UINT` | Hardware type (upper 16 bits), File type (lower 16 bits) |
| `CreatedByName` | `char[16]` | Creator T-number |
| `UpdatedByName` | `char[16]` | Updater T-number |
**`DATASYSTEMBLOCK`** - Data system configuration:
| Field | Type | Description |
|-------|------|-------------|
| `Size` | `UINT` | Block size |
| `NumberOfSystems` | `UINT` | Number of systems |
| `ChannelsPerSystem` | `UINT` | Channels per system |
| `MaxSampleRate` | `UINT` | Max/default sample rate |
| `SizeOfConfig` | `UINT` | Size of DDASCONFIGBLOCK |
**`DDASCONFIGBLOCK`** - Per-system configuration:
| Field | Type | Description |
|-------|------|-------------|
| `Size` | `UINT` | Block size |
| `AnalogUnitNo` | `short` | DDAS analog unit number |
| `AnalogOptions` | `short` | Analog unit options |
| `MemoryUnitNo` | `short` | DDAS memory unit number |
| `MemoryOptions` | `short` | Memory unit options |
| `MemorySize` | `long` | Memory unit RAM (bytes) |
**`ACQUISITIONBLOCK`** - Acquisition parameters:
| Field | Type | Description |
|-------|------|-------------|
| `nSize` | `long` | Block size |
| `nRecordMode` | `long` | Record mode (RECORDMODE_EVENT or RECORDMODE_TAPE) |
| `SampleRate` | `long` | Samples per second |
| `TotalSamples` | `long` | Total samples in record |
| `PreEventSamples` | `long` | Pre-event samples (Event mode only) |
| `TapeModeChannels` | `long` | Number of channels (Tape mode only) |
| `nTrigBlock` | `long` | Number of trigger entries |
**`TRIGCHANDEF`** - Trigger channel definition:
| Field | Type | Description |
|-------|------|-------------|
| `ChanNo` | `BYTE` | Channel number for trigger |
| `LevelPct` | `BYTE` | Trigger level % full scale (0=off) |
**`TRIGCHANBLOCK`** - Trigger channel block:
| Field | Type | Description |
|-------|------|-------------|
| `SizeBlock` | `unsigned short` | Block size in bytes |
| `NumTrigs` | `unsigned short` | Number of trigger entries |
| `TrigChan` | `TRIGCHANDEF[MAXTRIGCHANS]` | Channel trigger array |
**Enumerations:**
- `FileTypeFlags { FILETYPE_IMPORTED4X }`
- `HardwareType { HWTYPE_UNKNOWN, HWTYPE_DDAS3, HWTYPE_KAYSERTHREDE, HWTYPE_COUNT }`
- `AnalogOptionFlags { ANAOPT_CHANTRIGGERS }`
- `MemoryOptionFlags { MEMOPT_TAPEMODE, MEMOPT_PREEVENT, MEMOPT_PREEVENTXXX }`
- `RecordModes { RECORDMODE_EVENT, RECORDMODE_TAPE }`
**Constants:**
- `MAXTRIGCHANS = 4`
- `TRIGCHANDSBL = 0x80`
- `TESTDEFEXT = ".tdf"`
- `DDASTYPENAME = "DDAS V5"`
- `DDASFILEVERS = "Ver 500"`
---
### C++ Structures (DataFloat.h)
**`TESTINFO`** - Test information:
| Field | Type | Description |
|-------|------|-------------|
| `Size` | `unsigned long` | Block size |
| `DeviceID` | `unsigned long` | DAQ device ID |
| `ChannelNo` | `long` | Channel number (1-32) |
| `SampleRate` | `long

View File

@@ -0,0 +1,250 @@
---
source_files:
- Common/DTS.Common.Serialization/DDAS (Chrysler)/FromChrysler/ChannelDefinition.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/FromChrysler/FilePath.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/FromChrysler/DDASTestDefinition.h
- Common/DTS.Common.Serialization/DDAS (Chrysler)/FromChrysler/DataFloat.h
generated_at: "2026-04-16T10:56:49.501225+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "289fd9f58c0583bc"
---
# DDAS (Chrysler) Serialization Module Documentation
## 1. Purpose
This module provides data structures and utility classes for serializing and deserializing DDAS (Dynamic Data Acquisition System) test configuration and floating-point data files used in Chrysler/DaimlerChrysler automotive testing. It defines the binary file formats for test definitions (`.tdf` files), floating-point data files (`.fpd` files), and supporting structures for channel configuration, transducer definitions, and file path manipulation. The module serves as the bridge between legacy DDAS hardware configurations and the software systems that process crash test and sensor data.
---
## 2. Public Interface
### ChannelDefinition.h
#### Enumerations
- **`ChannelFlags`** — Contains `CHANFLAG_ACTIVE` for channel active state flagging.
#### Macros
- **`ISCHANACTIVE(pChan)`** — Returns 1 if channel active flag is set, 0 otherwise.
- **`SETCHANACTIVE(pChan)`** — Sets the channel active flag.
- **`CLRCHANACTIVE(pChan)`** — Clears the channel active flag.
#### Structures
- **`CHANNEL`** (typedef `tagCHANNEL`) — 128+ byte structure containing:
- `short Size` — Size of this object
- `short Flags` — Channel flags
- `char Name[64]` — Channel name
- `char Sign[8]` — Sign (+, -, or blank)
- `char Axis[8]` — Axis identifier (X, Y, Z, FX, MX, AX, etc.)
- `float FilterFreq` — Filter frequency in Hz
- `float SetGain` — Gain setting (1 - n)
- `float ActGain` — Actual/measured gain setting
- `float Rcal` — Shunt calibration resistance
- `float Excitation` — Excitation voltage (when programmable)
- `byte byteSpares[4]` — Spare bytes (formerly `CalDate`)
- `TRANSDUCER Transducer` — Snapshot of transducer values
#### Type Aliases
- **`PCHANNEL`** — Pointer to `CHANNEL`
- **`PCHAN`** — Alias for `PCHANNEL`
---
### FilePath.h
#### Constants
- **`PATHLENMAX`** — Maximum path length allowed (300 characters)
#### Enumerations
- **`FileSpecOK`** — Bitmask flags for file specification validation:
- `FSPEC_EXTOK = 0x1` — File extension valid
- `FSPEC_NAMEOK = 0x2` — File name valid
- `FSPEC_PATHOK = 0x4` — File path valid
- `FSPEC_ROOTOK = 0x8` — Drive or computer valid
- `FSPEC_RELATIVEPATH = 0x10` — Path is relative
#### Class `CFilePath`
Public methods:
- **`CFilePath()`** — Default constructor
- **`virtual ~CFilePath()`** — Destructor
- **`void operator=(const CFilePath &src)`** — Assignment operator
- **`int SetFullFilePathAndName(char* szPathAndName)`** — Set complete file path
- **`int SetDriveOrResource(char *szNewDrive, int* nNext)`** — Set drive or network resource
- **`int SetDrive(int nDriveAis1)`** — Set drive number (A=1)
- **`int SetDir(char *szNewDir, int* nNext)`** — Set directory path
- **`int SetFile(char *szNewFile, int *nNext)`** — Set file name
- **`int SetExtension(char *szNewExt)`** — Set file extension
- **`int ParseFilePathAndName(char *szPathAndName)`** — Parse full path into components
- **`const char* GetFullFilePathAndName()`** — Retrieve complete path
- **`const char* GetFileName()`** — Retrieve file name
- **`const CString GetFileNameExt()`** — Retrieve file name with extension
- **`const char* GetFileExtension()`** — Retrieve extension
- **`BOOL FileExists()`** — Check if file exists
- **`bool IsPathComplete(int *pFlgValid)`** — Check if path is complete
- **`bool IsFileType(char *szFileTypeExt)`** — Check file type by extension
- **`bool IsFileValid(const char* szFileSpec, const char *szFileTypeExt, CString* pcsError)`** — Validate file specification
- **`bool IsAllValidChars(char* szInString, int* pnPosBad)`** — Validate characters in string
- **`void Clear()`** — Reset all path components
---
### DDASTestDefinition.h
#### Constants
- **`TESTDEFEXT`** — Test definition file extension (".tdf")
- **`DDASTYPENAME`** — "DDAS V5"
- **`DDASFILEVERS`** — "Ver 500"
- **`MAXTRIGCHANS`** — Maximum trigger channels (4)
- **`TRIGCHANDSBL`** — Trigger channel disable flag (0x80)
#### Enumerations
- **`FileTypeFlags`** — `FILETYPE_IMPORTED4X` for tests imported from 4.x format
- **`HardwareType`** — Hardware identifiers: `HWTYPE_UNKNOWN`, `HWTYPE_DDAS3`, `HWTYPE_KAYSERTHREDE`, `HWTYPE_COUNT`
- **`AnalogOptionFlags`** — `ANAOPT_CHANTRIGGERS` for analog unit channel triggers
- **`MemoryOptionFlags`** — `MEMOPT_TAPEMODE`, `MEMOPT_PREEVENT`, `MEMOPT_PREEVENTXXX`
- **`RecordModes`** — `RECORDMODE_EVENT`, `RECORDMODE_TAPE`
#### Structures
- **`FILEINFOBLOCK`** — File metadata (size, type name, version, flags, creator/updater names)
- **`DATASYSTEMBLOCK`** — System configuration (number of systems, channels per system, max sample rate, config block size)
- **`DDASCONFIGBLOCK`** — Per-system configuration (analog/memory unit numbers, options, memory size)
- **`ACQUISITIONBLOCK`** — Data acquisition parameters (record mode, sample rate, total samples, pre-event samples, tape mode channels, trigger block count)
- **`TRIGCHANDEF`** — Channel trigger definition (`ChanNo`, `LevelPct`)
- **`TRIGCHANBLOCK`** — Trigger channel block (size, count, array of `TRIGCHANDEF`)
---
### DataFloat.h
#### Constants
- **`TESTPATHSIZE`** — 128 (if not already defined)
- **`FILEERROR`** — -1
- **`FLOATDATANAME`** — "DDAS FlPt"
- **`FLOATDATARAW`** — "DDAS fpRAW"
- **`FLOATDATAVER`** — "Ver 500"
- **`RawExt`** — ".raw"
- **`FlPtExt`** — ".fpd"
#### Enumerations
- **`FileTypes`** — `UNKNOWN`, `FLOATPOINT`, `PROCESSED`
- **`PeakTypes`** — `PEAKS_MINMAX`, `PEAKS_3MSCONTIN`, `PEAKS_3MSCUMUL`
- **`FPDVerbosity`** — `FPD_SILENT`, `FPD_ERRORS`, `FPD_STATUS`, `FPD_RESULTS`, `FPD_VERBOSE`
#### Structures
- **`TESTINFO`** — Test metadata (device ID, channel number, sample rate, total samples, pre-event samples, channel number in system, calibration points, test creation path, time axis title, spare bytes)
- **`FILEHEADER`** — File header containing `FILEINFOBLOCK`, `TESTINFO`, `CHANNEL`, and 32 spare bytes
- **`DATAPEAK`** — Peak data (`Min`, `Xmin`, `Max`, `Xmax`)
- **`DATAHIST`** — Histogram data (`fVal`, `nOccurrences`)
#### Class `CDataFloat`
Public methods:
- **`CDataFloat()`** — Default constructor
- **`CDataFloat(unsigned int nSize)`** — Constructor with initial size
- **`virtual ~CDataFloat()`** — Destructor
- **`void operator=(const CDataFloat &src)`** — Assignment operator
- **`bool SetSize(long lNumberElements)`** — Resize data array
- **`long GetSize()`** — Get array size
- **`bool SetIndexToStart()`** — Reset buffer pointer to start
- **`bool StoreDataNext(float fData)`** — Store next data value
- **`bool GetDataNext(float* fData)`** — Retrieve next data value
- **`float* GetDataBuffer()`** — Get pointer to data buffer
- **`CArray<float, float&>* GetDataArray()`** — Get reference to data array
- **`int AppendArrayFloat(CArray<float, float&>* srcArray)`** — Append data from another array
- **`bool ReadFromFile(const char *lpFilename)`** — Read data from file
- **`bool WriteToFile(const char *lpFilename, bool bPrint)`** — Write data to file
- **`FILEHEADER* GetFileHeader()`** — Get file header structure
- **`FILEINFOBLOCK* GetFileInfo()`** — Get file info block
- **`TESTINFO* GetTestInfo()`** — Get test info structure
- **`CHANNEL* GetChannel()`** — Get channel definition
- **`int GetChannelNumber()`** — Get channel number
- **`int GetChannelNumberInBox()`** — Get channel number in box/system
- **`long GetSampleRate()`** — Get sample rate
- **`int GetEventOffset()`** — Get event offset
- **`float GetStartTime(bool bmSec)`** — Get start time (seconds or milliseconds)
- **`float GetStopTime(bool bmSec)`** — Get stop time
- **`float GetStartTimeData(bool bmSec)`** — Get data start time
- **`float GetStopTimeData(bool bmSec)`** — Get data stop time
- **`int ConvertTimeToIndex(float fTime)`** — Convert time to array index
- **`float ConvertIndexToTime(int nIndex)`** — Convert index to time
- **`int CalcSampIn3mSecInt()`** — Calculate samples in 3 milliseconds
- **`bool GetTimeAtValue(float fValue, float *pTvalue)`** — Find time at which a value occurs
- **`bool GetDataPeaks(...)`** — Multiple overloads for retrieving peak data
- **`void SetChannelName(char* szNewChannelName)`** — Set channel name
- **`void SetEngrgUnits(char *szNewEngrgUnits)`** — Set engineering units
- **`bool VerifyAndCoerceAxis(bool bNegativeSign, const char* szAxis, BOOL bVerbose)`** — Validate and correct axis designation
- **`int SetFilePathAndName(char* szNewFileSpec)`** — Set file path
- **`const char* GetFilePathAndName()`** — Get file path
- **`const char* GetFileTitle()`** — Get file title
- **`const char* GetFileExt()`** — Get file extension
- **`const CString GetFileName()`** — Get file name
- **`CString GetDataSetName(CString &csName)`** — Get data set name
- **`float GetFilterClass()`** — Get filter class
- **`int ClearAll(long NewNumberElements)`** — Clear and resize array
#### Inner Class `CDataFloat::CPeakList`
- **`void AddDataPoint(DATAHIST* pDHist)`** — Add data point to histogram
- **`void Get3msMin(int nPtPer3ms, DATAHIST* pDHist)`** — Get 3ms minimum
- **`void Get3msMax(int nPtPer3ms, DATAHIST* pDHist)`** — Get 3ms maximum
- **`void RemoveAll()`** — Clear all entries
---
## 3. Invariants
### Channel Definition
- `CHANNEL.Size` must reflect the actual size of the structure for versioning/serialization compatibility.
- `byteSpares[4]` in `CHANNEL` is fixed at 4 bytes; this was formerly `CalDate` (a `time_t`) and must not be repurposed without coordination with transducer date fields.
### File Path
- `PATHLENMAX` (300) is the maximum allowed path length.
- `CFilePath` maintains separate string pointers for root, directory, name, and extension components.
### Test Definition
- `FILEINFOBLOCK.FileTypeFlags` encodes hardware type in upper 16 bits and file type in lower 16 bits.
- `TRIGCHANDEF.ChanNo` and `LevelPct` must both be non-zero, and `TRIGCHANDSBL` must not be set in `LevelPct` for a trigger to be enabled.
- `TRIGCHANBLOCK.TrigChan` array is sized to `MAXTRIGCHANS` (4) but documented as variable-size in practice.
- `ACQUISITIONBLOCK.PreEventSamples` is only valid in `RECORDMODE_EVENT` mode.
- `ACQUISITIONBLOCK.TapeModeChannels` is only valid in `RECORDMODE_TAPE` mode.
### Data Float
- `FILEHEADER` has a fixed 32-byte spare section at the end.
- `TESTINFO` includes 2 spare bytes for 4-byte alignment.
- `FloatData` array and `pfBfr` pointer must remain synchronized; `SetIndexToStart()` resets `pfBfr` to the beginning of `FloatData`.
---
## 4. Dependencies
### This Module Depends On
- **`TransducerDefinition.h`** — Required by `ChannelDefinition.h` for `TRANSDUCER` type (not provided in source).
- **`<Afxtempl.h>`** — MFC template classes (`CArray`, `CList`) used in `DataFloat.h`.
- **MFC/ATL** — `CString` class used in `FilePath.h` and `DataFloat.h`.
### Consumers (Inferred)
- Any system reading or writing DDAS test definition files (`.tdf`).
- Any system reading or writing DDAS floating-point data files (`.fpd` or `.raw`).
- Crash test data analysis tools processing channel and transducer configurations.
---
## 5. Gotchas
### Historical Artifacts
1. **Removed `CalDate` field**: The `CHANNEL` structure formerly contained a `time_t CalDate` field. This was removed per revision on 11/08/04 and replaced with `byteSpares[4]`. The calibration date is now stored in the embedded `TRANSDUCER` structure. Code that assumes `CalDate` exists in `CHANNEL` will fail.
2. **Variable-size array pattern**: `TRIGCHANBLOCK.TrigChan` is declared with `MAXTRIGCHANS` elements but comments indicate it "will be a variable size array." This suggests the binary format may contain fewer than 4 entries in actual files, and `NumTrigs` should be used to determine actual count.
### Binary Format Considerations
3. **Alignment padding**: `TESTINFO` includes `SpareBytes[2]` explicitly for 4-byte alignment. Modifying this structure requires maintaining alignment for binary compatibility.
4. **File version strings**: Multiple version constants exist (`DDASFILEVERS`, `FLOATDATAVER` both equal "Ver 500"). These must match when reading/writing files.
5. **Hardware type encoding**: `FileTypeFlags` in `FILEINFOBLOCK` uses a split 16/16 bit encoding. Direct comparison of this field without masking will produce incorrect results.
### API Quirks
6. **Pointer-based buffer access**: `CDataFloat::GetDataBuffer()` returns a raw pointer to internal data. The state of this pointer after `SetSize()` or `ClearAll()` calls is unclear from the source—callers should re-fetch after modifications.
7. **Multiple channel number methods**: Both `GetChannelNumber()` and `GetChannelNumberInBox()` exist. The distinction between "channel number" and "channel number in system" is not fully explained in the source.
8. **Missing `TransducerDefinition.h`**: The `TRANSDUCER` type is used but not defined in the provided sources. The size

View File

@@ -0,0 +1,110 @@
---
source_files:
- Common/DTS.Common.SerializationPlus/EventInfoAggregate.cs
generated_at: "2026-04-16T11:34:44.427048+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "342395eec4a038a1"
---
# Documentation: EventInfoAggregate
## 1. Purpose
`EventInfoAggregate` is an aggregation class that consolidates event information from multiple Data Acquisition System (DAS) units into a single unified view. It implements `IEventInfoAggregate` and serves to merge data from distributed recording modules that participate in the same test event, tracking metadata such as duration, sample counts, channel counts, and fault status across all participating units.
---
## 2. Public Interface
### Properties
| Property | Type | Description |
|----------|------|-------------|
| `EventId` | `string` | Test/event identifier |
| `EventDescription` | `string` | Human-readable event description |
| `DurationSeconds` | `double` | Event duration in seconds |
| `GUID` | `string` | Unique test identifier (string representation of GUID) |
| `HasBeenDownloaded` | `bool` | Indicates whether event data has been downloaded |
| `WasTriggered` | `bool` | Indicates whether the event was triggered |
| `NumberOfChannels` | `int` | Cumulative channel count across all modules |
| `NumberOfSamples` | `ulong` | Sample count per channel |
| `NumberOfBytes` | `ulong` | Total data size in bytes |
| `Faulted` | `bool` | Indicates any fault condition across aggregated units |
| `EventNumber` | `int` | Sequential event number |
### Constructor
```csharp
public EventInfoAggregate(DownloadReport.EventInfo newEvent)
```
Initializes the aggregate with the first event. Handles empty `Modules` collections gracefully by setting `DurationSeconds` and `NumberOfSamples` to 0. Registers the owning DAS unit in the internal index map.
### Methods
```csharp
public Slice.Control.Event GetEvent(bool bClear)
```
Returns the cached `Slice.Control.Event` instance. If `bClear` is `true`, clears the cached instance before returning (forcing recreation on next call).
```csharp
public Slice.Control.Event GetEvent()
```
Returns the cached `Slice.Control.Event` instance, creating it lazily if null.
```csharp
public int GetEventIndex(IDASCommunication idas)
```
Returns the event index associated with the specified DAS unit. Returns `-1` and logs an error if the DAS unit is not found in the index map.
```csharp
public List<IDASCommunication> GetDasList()
```
Returns the list of DAS units associated with this event. Lazily populated from the internal index dictionary keys.
```csharp
public void Add(IEventInfo newEvent)
```
Merges another event into this aggregate. Accumulates channel counts, ORs fault status, and takes minimum values for mismatched durations and sample counts. Logs warnings for any data mismatches but does not throw exceptions.
---
## 3. Invariants
- **Byte Calculation**: `NumberOfBytes` is always calculated as `2 * NumberOfChannels * NumberOfSamples` (assumes 2 bytes per sample per channel).
- **Channel Accumulation**: `NumberOfChannels` is cumulative; each `Add()` call sums the new module's channel count.
- **Fault Aggregation**: `Faulted` is the logical OR of all aggregated events' fault status.
- **Mismatch Handling**: When durations or sample counts differ between aggregated events, the minimum value is retained.
- **Empty Modules Safety**: Constructor handles empty `Modules` collections without throwing (sets `DurationSeconds` and `NumberOfSamples` to 0).
- **Index Uniqueness**: `_eventIndices` uses indexer assignment to handle potential duplicate keys gracefully.
---
## 4. Dependencies
### This Module Depends On
- `DTS.Common.Interface.DASFactory``IDASCommunication` interface
- `DTS.Common.Interface.DASFactory.Download``IEventInfo`, `DownloadReport.EventInfo`, `DASModule`
- `DTS.Common.Utilities.Logging``APILogger` for diagnostic logging
- `DTS.DASLib.Service``Slice.Control.Event` class
### Implementations
- Implements `IEventInfoAggregate` (interface not shown in source)
---
## 5. Gotchas
1. **`Add()` lacks empty Modules guard**: Unlike the constructor, `Add()` accesses `newEvent.Modules[0]` without checking if `Modules` is empty, which will throw `ArgumentOutOfRangeException`.
2. **Mismatches are logged, not enforced**: The `Add()` method logs warnings for TestID, Description, GUID, EventNumber, and other mismatches but continues processing. Callers cannot detect mismatches programmatically.
3. **Silent data loss on mismatch**: When durations or sample counts don't match, the minimum is silently taken. The original values are lost and only a warning is logged.
4. **`GetEventIndex` returns -1 for missing keys**: Callers must check for -1 return value; no exception is thrown for unknown DAS units.
5. **Lazy initialization side effects**: `GetDasList()` and `GetEvent()` cache their results. The `GetEvent(bool bClear)` overload is the only way to reset the `Slice.Control.Event` cache.
6. **Historical bug fixes embedded**:
- Empty modules handling added for case 15575 (cable disconnect during download)
- Indexer assignment used instead of `.Add()` for case 44357 (duplicate key prevention)

View File

@@ -0,0 +1,90 @@
---
source_files:
- Common/DTS.Common.Service/ProjectInstaller.cs
- Common/DTS.Common.Service/Program.cs
- Common/DTS.Common.Service/DTSService.Designer.cs
- Common/DTS.Common.Service/DTSService.cs
- Common/DTS.Common.Service/ProjectInstaller.Designer.cs
generated_at: "2026-04-16T11:37:04.449162+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c2781b46f4b0859d"
---
# DTS.Common.Service Module Documentation
## 1. Purpose
This module provides a Windows Service infrastructure for DTS (Diversified Technical Systems) applications. It implements a standard Windows Service that can be installed, started, stopped, and controlled via the Windows Service Control Manager. The service includes built-in event logging capabilities and an optional monitoring feature that executes periodic tasks on a configurable timer interval. It serves as a base service framework that can be extended with custom monitoring activities and custom commands.
---
## 2. Public Interface
### `Program` (static class)
Entry point for the service application.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Main` | `static void Main()` | Creates a new `DTSService` instance and executes it via `ServiceBase.Run()`. This is the application entry point. |
### `DTSService` (class, inherits `ServiceBase`)
The primary Windows Service implementation.
| Member | Signature | Description |
|--------|-----------|-------------|
| `DTSService()` | `public DTSService()` | Constructor. Initializes the event log source (creating it if it doesn't exist), configures the event log from settings, and optionally starts a monitoring timer if `Settings.Default.Monitoring` is enabled. |
| `OnTimer` | `public void OnTimer(object sender, ElapsedEventArgs args)` | Timer callback that writes an informational entry "Monitoring the System" to the event log. Intended to be extended with monitoring activities. |
| `OnStart` | `protected override void OnStart(string[] args)` | Called when the service starts. Writes a start message to the event log using `Settings.Default.ServiceName`. |
| `OnStop` | `protected override void OnStop()` | Called when the service stops. Writes a stop message to the event log using `Settings.Default.ServiceName`. |
| `OnCustomCommand` | `protected override void OnCustomCommand(int command)` | Handles custom service commands. Dispatches to switch statement based on `CustomCommands` enum values. |
| `CustomCommands` | `public enum CustomCommands` | Defines custom command values: `Command1 = 128`, `Command2 = 129`, `Command3 = 130`. |
| `eventLog` | `public System.Diagnostics.EventLog eventLog` | Public field providing access to the event log component. Defined in `DTSService.Designer.cs`. |
### `ProjectInstaller` (class, inherits `System.Configuration.Install.Installer`)
Handles installation of the Windows Service via InstallUtil.exe.
| Member | Signature | Description |
|--------|-----------|-------------|
| `ProjectInstaller()` | `public ProjectInstaller()` | Constructor. Calls `InitializeComponent()` to configure service installers. |
---
## 3. Invariants
- **Event Source Existence**: The event source specified by `Settings.Default.ServiceName` must exist before logging; the constructor creates it if missing via `EventLog.CreateEventSource()`.
- **Event Log Configuration**: The event log name is determined by `Settings.Default.Service`, and the source by `Settings.Default.ServiceName`.
- **Timer Interval**: When monitoring is enabled, the timer interval is set from `Settings.Default.Interval` (comment indicates default is 60 seconds).
- **Service Account**: The service is configured to run under `ServiceAccount.LocalSystem` with no explicit username or password.
- **Service Start Type**: The service is configured for `ServiceStartMode.Automatic`.
- **Installation Identity**: The installer sets `ServiceName = "DTSService"`, `DisplayName = "DTS Common Service"`, and `Description = "Diversified Technical Systems Common Service"`.
---
## 4. Dependencies
### This module depends on:
- `System.ComponentModel` - For `IContainer` and component support
- `System.ServiceProcess` - For `ServiceBase`, `ServiceInstaller`, `ServiceProcessInstaller`
- `System.Diagnostics` - For `EventLog` and `EventLogEntryType`
- `System.Timers` - For `Timer` and `ElapsedEventArgs`
- `DTS.Common.Service.Properties` - For `Settings` class providing configuration values (`ServiceName`, `Service`, `Monitoring`, `Interval`)
### What depends on this module:
- Not determinable from the provided source files alone. This appears to be a foundational service module intended to be extended or referenced by other DTS components.
---
## 5. Gotchas
1. **Timer Started in Constructor**: The monitoring timer is started in the `DTSService` constructor, not in `OnStart()`. This means the timer begins before the service is officially in a "running" state.
2. **Timer Not Stored as Field**: The `Timer` instance in the constructor is a local variable, not a class field. This could potentially allow garbage collection of the timer, though the event subscription may keep it alive. This is a potential reliability issue.
3. **Designer ServiceName Mismatch**: In `DTSService.Designer.cs`, `InitializeComponent()` sets `this.ServiceName = "Service1"`, but the actual service name is configured via `Settings.Default.ServiceName`. The designer value appears to be a placeholder that gets overridden.
4. **Empty Custom Command Implementations**: The `OnCustomCommand` method defines three custom commands (`Command1`, `Command2`, `Command3`) but all switch cases are empty. This is placeholder functionality.
5. **TODO in Production Code**: The `OnTimer` method contains a `// TODO: Insert monitoring activities here.` comment, indicating incomplete implementation.
6. **Monitoring Conditional**: If `Settings.Default.Monitoring` is `false`, the timer is never created, and `OnTimer` will never be called. The service will only log start/stop events.

View File

@@ -0,0 +1,70 @@
---
source_files:
- Common/DTS.Common.ServiceLibrary/ServiceLibrary.cs
- Common/DTS.Common.ServiceLibrary/IServiceLibrary.cs
generated_at: "2026-04-16T11:33:15.064203+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "7c181fe270706bc1"
---
# Documentation: DTS.Common.ServiceLibrary
## 1. Purpose
This module implements a Windows Communication Foundation (WCF) service library defined within the `DTS.Common.ServiceLibrary` namespace. It provides a concrete implementation of the `IServiceLibrary` service contract, offering two basic operations: a simple data retrieval method and a data manipulation method using a data contract. Based on the inline comments (e.g., "Rename command," "TODO"), this module appears to be a boilerplate or template-generated code intended to serve as a starting point for service development.
## 2. Public Interface
### Class: `ServiceLibrary`
**Implements:** `IServiceLibrary`
**Location:** `ServiceLibrary.cs`
* **`string GetData(int value)`**
* Accepts an integer `value` and returns a formatted string: `"You entered: {value}"`.
* **`CompositeType GetDataUsingDataContract(CompositeType composite)`**
* Accepts an object of type `CompositeType`.
* **Behavior:**
* Throws `ArgumentNullException` if `composite` is `null`.
* If `composite.BoolValue` is `true`, appends the string `"Suffix"` to `composite.StringValue`.
* Returns the modified `composite` object.
### Interface: `IServiceLibrary`
**Attributes:** `[ServiceContract]`
**Location:** `IServiceLibrary.cs`
* **`[OperationContract] string GetData(int value)`**
* **`[OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite)`**
### Class: `CompositeType`
**Attributes:** `[DataContract]`
**Location:** `IServiceLibrary.cs`
* **`bool BoolValue`**
* Attribute: `[DataMember]`
* Default Value: `true`
* Auto-implemented property backing field initialized to `true`.
* **`string StringValue`**
* Attribute: `[DataMember]`
* Default Value: `"Hello "`
* Auto-implemented property backing field initialized to `"Hello "`.
## 3. Invariants
* **Null Checking:** The method `GetDataUsingDataContract` explicitly guarantees that it will throw an `ArgumentNullException` if the input `composite` parameter is `null`.
* **State Mutation:** `GetDataUsingDataContract` modifies the state of the passed `composite` object in-place (specifically `StringValue`) rather than returning a new instance, provided `BoolValue` is `true`.
* **Serialization:** `CompositeType` is marked with `[DataContract]` and its properties with `[DataMember]`, implying it must be serializable by the WCF runtime for transport.
## 4. Dependencies
**Internal Dependencies:**
* `ServiceLibrary` depends on `IServiceLibrary` for the service contract definition.
* `ServiceLibrary` depends on `CompositeType` for data transfer operations.
**External Dependencies (System Assemblies):**
* `System.Runtime.Serialization`: Required for `DataContract`, `DataMember` attributes.
* `System.ServiceModel`: Required for `ServiceContract`, `OperationContract` attributes.
* `System`: Required for basic types (`string`, `int`, `ArgumentNullException`).
## 5. Gotchas
* **Boilerplate Code:** The source code contains default Visual Studio template comments (e.g., `// NOTE: You can use the "Rename" command...`, `// TODO: Add your service operations here`). This indicates the code may not contain production-specific business logic and has not been refactored to remove template artifacts.
* **Side Effect in `GetDataUsingDataContract`:** This method mutates the `StringValue` property of the input object. Developers consuming this API might expect a pure function that returns a new object or leaves the input unchanged. This mutation occurs if `BoolValue` is `true`.
* **Naming Collision:** The class `ServiceLibrary` shares the same name as the namespace `DTS.Common.ServiceLibrary`. While valid in C#, this can lead to confusion in resolution or documentation generation.
* **Legacy Exception Construction:** The `ArgumentNullException` is thrown using the legacy constructor overload `new ArgumentNullException("composite")` rather than `nameof(composite)`, suggesting the code was written for an older version of C# or generated by an older template.

View File

@@ -0,0 +1,152 @@
---
source_files:
- Common/DTS.Common.SettingsDB/UserSetting.cs
- Common/DTS.Common.SettingsDB/Setting.cs
- Common/DTS.Common.SettingsDB/GlobalSetting.cs
- Common/DTS.Common.SettingsDB/SettingsDB.cs
generated_at: "2026-04-16T11:31:14.800080+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "0690ee9f2887691d"
---
# Documentation: DTS.Common.Settings
## 1. Purpose
This module provides a persistent settings management system that stores and retrieves application configuration values in a SQL database. It supports two categories of settings: **global settings** (application-wide, identified by the `"SYSTEM"` user) and **user-specific settings** (scoped to individual users). The `SettingsDB` class serves as the primary facade, implementing a thread-safe singleton pattern with in-memory caching to minimize database round-trips. Settings are serialized as strings in the database, with helper methods provided for type conversion to/from `int`, `double`, `bool`, and arrays.
---
## 2. Public Interface
### `Setting` (Abstract Base Class)
The abstract base class for all setting types.
**Properties:**
- `string PropertyId` — The string identifier for the setting.
- `PropertyTypes PropertyType` — Either `PropertyTypes.User` (1) or `PropertyTypes.Global` (2).
- `string PropertyValue` — The current value of the setting.
- `string UserId` — The user identifier; `"SYSTEM"` for global settings.
**Methods:**
- `void SetValue(string value)` — Updates the in-memory value and persists it to the database via `StoreInDB()`.
**Nested Types:**
- `enum PropertyTypes` — Values: `User = 1`, `Global = 2`.
---
### `GlobalSetting` (Class, inherits `Setting`)
Represents an application-wide setting.
**Constructors:**
- `GlobalSetting(string id, string defaultPropertyValue)` — Creates or retrieves a global setting with the given ID and default value.
**Static Methods:**
- `GlobalSetting ReadXML(System.Xml.XmlElement root)` — Parses an XML element to construct a `GlobalSetting`. Expects child elements matching `XMLFields.NAME` and `XMLFields.VALUE`.
- `GlobalSetting[] GetAllGlobalSettings()` — Retrieves all global settings from the database. Returns an empty array on failure.
**Nested Types:**
- `enum XMLFields` — Values: `NAME`, `VALUE`. Used for XML parsing.
- `class NullDefaultValueException : NullReferenceException` — Thrown when a setting doesn't exist and no default value is provided.
---
### `UserSetting` (Class, inherits `Setting`)
Represents a user-specific setting.
**Constructors:**
- `UserSetting(string id, string defaultValue, string user)` — Creates or retrieves a user-specific setting for the given user.
---
### `SettingsDB` (Static Facade Class)
The primary interface for interacting with settings. Implements a thread-safe singleton with caching.
**Static Methods:**
| Method | Description |
|--------|-------------|
| `void RefreshSettings()` | Clears the in-memory settings cache. |
| `string GetUserValue(string id, string defaultValue, string user)` | Retrieves a user-specific value; creates with default if not exists. |
| `string GetGlobalValue(string id, string defaultValue, bool useCache = true)` | Retrieves a global value; creates with default if not exists. Optionally bypasses cache. |
| `void GetAllGlobalValues()` | Loads all global settings into the cache. |
| `double GetGlobalValueDouble(string id, double defaultValue)` | Retrieves a global value parsed as `double`. |
| `int GetGlobalValueInt(string id, int defaultValue)` | Retrieves a global value parsed as `int`. |
| `bool GetGlobalValueBool(string id, bool defaultValue, bool useCache = true)` | Retrieves a global value parsed as `bool`. |
| `double[] GetGlobalValueDoubleArray(string id, double[] defaultValues)` | Retrieves an array of doubles stored as separate keys (`{id}_x_Count`, `{id}_x_0`, etc.). |
| `int[] GetGlobalValueIntArray(string id, int[] defaultValues)` | Retrieves an array of ints stored as separate keys. |
| `void SetUserValue(string id, string value, string user)` | Sets a user-specific value in the database. |
| `void SetGlobalValue(string id, string value)` | Sets a global string value. |
| `void SetGlobalValueDouble(string id, double value)` | Sets a global double value. |
| `void SetGlobalValueInt(string id, int value)` | Sets a global int value. |
| `void SetGlobalValueBoolean(string id, bool value)` | Sets a global bool value. |
| `void SetGlobalValueDoubleArray(string id, double[] values)` | Stores a double array as multiple keys. |
| `void SetGlobalValueIntArray(string id, int[] values)` | Stores an int array as multiple keys. |
---
## 3. Invariants
1. **Thread Safety**: All public methods in `SettingsDB` acquire a lock on `LOCK_OBJECT` before accessing `_settingsLookup`. The singleton instance is lazily initialized under lock.
2. **Key Uniqueness**: User-specific settings use a composite key format `{id}_{user}` in the cache; global settings use `{id}` directly.
3. **Global Settings Identity**: All `GlobalSetting` instances use `UserId = "SYSTEM"` (defined as a private constant).
4. **Database Synchronization**: Calling `SetValue()` on any `Setting` instance immediately persists the value to the database via `StoreInDB()`.
5. **Auto-Creation on Missing**: When a setting is retrieved but doesn't exist in the database, it is automatically created with the provided default value and persisted.
6. **Array Storage Convention**: Arrays are stored as multiple database records:
- `{id}_x_Count` — The number of elements.
- `{id}_x_{i}` — The value at index `i`.
7. **Culture Invariance**: All numeric-to-string conversions use `CultureInfo.InvariantCulture`.
---
## 4. Dependencies
### This Module Depends On:
- `System.Data` — For `CommandType`, `SqlParameter`, `SqlDbType`, `ParameterDirection`.
- `System.Data.SqlClient` — For `SqlConnection`/`SqlCommand` operations (implied via `SqlParameter`).
- `DTS.Common.Storage` — Provides:
- `DbOperations.GetSQLCommand(bool)`
- `DbOperations.Connection.QueryDataSet(SqlCommand)`
- `DbOperationsEnum.StoredProcedure` (enum with `sp_SettingsGet`, `sp_SettingsUpdateInsert`)
- `DbOperations.Settings.UserFields.PropertyValue` (enum)
- `DTS.Common.Utilities.Logging` — Provides `APILogger.LogException(Exception)` and `APILogger.Log(string, Exception)`.
### Database Dependencies:
- Stored Procedure: `sp_SettingsGet` — Retrieves settings by `@UserId` and `@PropertyId`.
- Stored Procedure: `sp_SettingsUpdateInsert` — Inserts or updates a setting. Parameters: `@PropertyId`, `@PropertyType`, `@PropertyValue`, `@UserId`, `@new_id` (output), `@errorNumber` (output), `@errorMessage` (output).
---
## 5. Gotchas
1. **Silent Exception Swallowing in `UserSetting.GetPropertyValue`**: All exceptions are caught and silently ignored; the method falls back to the default value without logging. This can mask database connectivity issues or data corruption.
2. **Unused Error Output Parameters**: In `Setting.StoreInDB()`, the stored procedure returns `@errorNumber` and `@errorMessage`, but the code checks if `errorNumber != 0` and then does nothing (empty block). Errors from the database are silently ignored.
3. **Max Length Constraint Not Enforced in Code**: The `PropertyValue` property documentation states "there is a max length" but no validation occurs before database insertion. The stored procedure parameters specify length 255 for string values.
4. **Redundant `cmd.Connection.Dispose()`**: All database methods call `cmd.Connection.Dispose()` inside a `finally` block, but the `cmd` is already inside a `using` statement. This is redundant and potentially confusing.
5. **Backward Compatibility Hack for `ImportCreateDynamicGroups`**: `SettingsDB` contains special-case logic for migrating from `CSV_IMPORT_CREATE_DYNAMIC_GROUPS` to `IMPORT_CREATE_DYNAMIC_GROUPS`. When setting the new key, it also sets the old key for pre-Version 93 client compatibility. This is documented in comments referencing issue 36831.
6. **`GetGlobalValueBool` Parsing Logic Error**: The method contains `return !bool.TryParse(sValue, out b) ? b : b;` — both branches return `b`, making the conditional meaningless. It should likely return `defaultValue` on parse failure.
7. **`NullDefaultValueException` Only Thrown by `GlobalSetting`**: `UserSetting.GetPropertyValue` does not throw this exception; it silently falls back to the default. Only `GlobalSetting.GetPropertyValue` throws `NullDefaultValueException` when the setting doesn't exist and `defaultValue` is null.
8. **TODO Comments Indicate Incomplete Work**:
- `UserSetting.GetPropertyValue` line 42: `//TODO: handle exception properly`
- `GlobalSetting.ProcessXMLElement` line 68: `// TODO: handle exception properly`
9. **Cache Bypass Only Affects Retrieval**: `GetGlobalValue(id, defaultValue, useCache: false)` bypasses the cache when reading, but `SetGlobalValue` always updates the cache. This can lead to stale cache entries if another process modifies the database directly.

View File

@@ -0,0 +1,41 @@
---
source_files:
- Common/DTS.Common.SettingsDB/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:55:21.671165+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "10c0db2038b748eb"
---
# Documentation for AssemblyInfo.cs
## 1. Purpose
This file serves as the assembly manifest for the `DTS.Common.SettingsDB` project. It defines metadata attributes—such as title, version, and culture—used by the .NET runtime and hosting applications to identify and interact with the compiled library (DLL). It exists to configure the assembly's identity and visibility settings during the build process.
## 2. Public Interface
This file contains no public classes, methods, or functions. It strictly applies assembly-level attributes. The significant configurations are:
* **`AssemblyTitle`**: Set to `"SettingsDB"`.
* **`AssemblyProduct`**: Set to `"SettingsDB"`.
* **`AssemblyVersion`**: Set to `"1.0.0.0"`.
* **`AssemblyFileVersion`**: Set to `"1.0.0.0"`.
* **`ComVisible`**: Set to `false`.
* **`Guid`**: Set to `"577ab42d-e5b3-4ba5-852d-ecadfbb81f9b"`.
## 3. Invariants
* **COM Visibility:** Types within this assembly are not visible to COM components by default (`ComVisible(false)`).
* **Versioning:** The assembly and file versions are fixed at `1.0.0.0`.
* **Identity:** The assembly is identified by the title "SettingsDB" and the specific GUID provided.
## 4. Dependencies
This file depends on standard .NET Framework namespaces:
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
No dependencies on other internal projects or custom libraries are visible in this file.
## 5. Gotchas
* **Missing Description:** The `AssemblyDescription` attribute is an empty string, offering no insight into the library's functionality via reflection tools.
* **Stale Copyright:** The `AssemblyCopyright` lists 2015, indicating the project may be legacy or that this metadata has not been maintained.
* **Manual Versioning:** The version numbers are hardcoded. Unlike SDK-style projects which may infer versions from the build system, this file relies on manual updates to `AssemblyVersion` and `AssemblyFileVersion`.

View File

@@ -0,0 +1,85 @@
---
source_files:
- Common/DTS.Common.SharedResource/EnumDescriptionTypeConverterShared.cs
generated_at: "2026-04-16T11:30:16.984345+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "accee265bcf5788d"
---
# Documentation: EnumDescriptionTypeConverterShared
## 1. Purpose
`EnumDescriptionTypeConverterShared` is a type converter that enables displaying human-readable descriptions for enumeration values instead of their raw string names. It extends `System.ComponentModel.EnumConverter` and is designed for UI data binding scenarios (particularly WPF). When an enum value has a `System.ComponentModel.DescriptionAttribute`, this converter extracts that description and optionally localizes it via the `StringResources` resource manager before returning it for display.
---
## 2. Public Interface
### `EnumDescriptionTypeConverterShared(Type type)`
**Signature:** Constructor
**Description:** Initializes a new instance of the converter for the specified enum type. Delegates to the base `EnumConverter` constructor.
---
### `public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)`
**Signature:** `object ConvertTo(ITypeDescriptorContext, CultureInfo, object, Type)`
**Description:** Converts an enum value to a display string. Behavior:
- If `destinationType` is not `string`, delegates to `base.ConvertTo()`
- If `value` is `null`, returns `string.Empty`
- If the enum field cannot be resolved via reflection, returns `string.Empty`
- If no `DescriptionAttribute` is present or the description is empty, returns `value.ToString()`
- If a `DescriptionAttribute` exists, attempts to look up the description text as a resource key via `StringResources.ResourceManager.GetString()`
- If the resource lookup returns null/whitespace, returns the raw description text; otherwise returns the localized string
---
### `public static string GetEnumDescription(Enum value)`
**Signature:** `static string GetEnumDescription(Enum)`
**Description:** A utility method that retrieves the description for an enum value. Behavior:
- Uses reflection to get the enum field's `DescriptionAttribute`
- If attributes exist, attempts localization via `StringResources.ResourceManager.GetString()`
- Returns the localized string if found; otherwise returns the raw description
- If no `DescriptionAttribute` is present, returns `value.ToString()`
---
## 3. Invariants
- The converter only modifies output when `destinationType == typeof(string)`; all other type conversions are passed through to the base class.
- The `DescriptionAttribute.Description` property is treated as a resource key first; if no matching resource is found, the raw description text is used as a fallback.
- `ConvertTo` always returns a non-null string (either the description, the enum name, or `string.Empty`).
- `GetEnumDescription` always returns a non-null string (either the description, the enum name, or the raw description text).
---
## 4. Dependencies
**This module depends on:**
- `System` - Core BCL types (`Type`, `string`, `object`)
- `System.ComponentModel` - `EnumConverter`, `DescriptionAttribute`, `ITypeDescriptorContext`
- `System.Globalization` - `CultureInfo`
- `System.Linq` - `Enumerable.Any()` extension method
- `DTS.Common.SharedResource.Strings.StringResources` - Resource manager for localization lookups
**Consumers:**
- Not determinable from source alone. Based on the class design and referenced article URL, it is intended for WPF data binding scenarios where enum values are displayed in UI controls.
---
## 5. Gotchas
1. **Null handling inconsistency:** `ConvertTo` has explicit null checks for `value` and returns `string.Empty`, but `GetEnumDescription` has no null check for its `value` parameter. Passing `null` to `GetEnumDescription` will throw a `NullReferenceException` when calling `value.GetType()`.
2. **Missing field info handling inconsistency:** `ConvertTo` checks if `fi` (field info) is null and returns `string.Empty`, but `GetEnumDescription` does not perform this check. If reflection fails to find the field, `GetEnumDescription` will throw a `NullReferenceException`.
3. **Resource key collision:** The `DescriptionAttribute.Description` value is used directly as a resource key. If the description text itself is not intended as a resource key but happens to match one, unintended localization may occur.
4. **Culture parameter ignored:** The `ConvertTo` method accepts a `culture` parameter but does not use it; the resource manager's default culture is used instead.

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.SharedResource/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:53:03.513910+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "d6fe7e91fd3430b0"
---
# Properties
## Documentation: DTS.Common.SharedResource (AssemblyInfo)
### 1. Purpose
This file provides assembly-level metadata and configuration for the `DTS.Common.SharedResource` library. It defines the assembly's identity, version, and visibility settings within the .NET runtime. As a standard `AssemblyInfo.cs` file, it does not contain executable business logic but serves as the manifest header for the compiled DLL, ensuring the component is correctly identified and versioned within the larger DTS system.
### 2. Public Interface
This file contains no public classes, methods, or functions. It defines the following assembly-level attributes:
* **`AssemblyTitle`**: Set to `"DTS.Common.SharedResource"`.
* **`AssemblyProduct`**: Set to `"DTS.Common.SharedResource"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2023"`.
* **`ComVisible`**: Set to `false`. This prevents types within this assembly from being visible to COM components by default.
* **`Guid`**: Set to `"c01e723f-86e2-403a-864c-9f56bdb60b8d"`. This serves as the unique identifier for the COM type library if COM interop is ever enabled.
* **`AssemblyVersion`**: Set to `"1.0.0.0"`.
* **`AssemblyFileVersion`**: Set to `"1.0.0.0"`.
### 3. Invariants
* **COM Visibility:** Types in this assembly are explicitly non-visible to COM components unless specifically overridden on individual types (enforced by `ComVisible(false)`).
* **Culture Neutrality:** The assembly is marked with an empty `AssemblyCulture`, indicating it is culture-neutral and not a satellite assembly.
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are synchronized at `1.0.0.0`.
### 4. Dependencies
* **Internal Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **External Consumers:** Any project or solution referencing the compiled `DTS.Common.SharedResource.dll` relies on the metadata defined here for version resolution and product identification.
### 5. Gotchas
* **Empty Metadata Fields:** Several informational attributes are initialized as empty strings (`AssemblyDescription`, `AssemblyConfiguration`, `AssemblyCompany`, `AssemblyTrademark`). This may result in missing details when viewing assembly properties via reflection or file explorer.
* **Static Versioning:** The version numbers are hardcoded to `1.0.0.0`. If the project uses modern SDK-style projects, these attributes may be overridden by the build system, or they may cause conflicts if the build system attempts to auto-generate version numbers.
* **Missing Implementation Context:** The source file provides no insight into what "SharedResource" entails (e.g., memory management, string resources, file handles). The actual functionality is defined in other files within this project not provided here.

View File

@@ -0,0 +1,79 @@
---
source_files:
- Common/DTS.Common.SharedResource/Strings/StringResources.es.Designer.cs
- Common/DTS.Common.SharedResource/Strings/StringResources.ja.Designer.cs
- Common/DTS.Common.SharedResource/Strings/StringResources.de.Designer.cs
- Common/DTS.Common.SharedResource/Strings/StringResources.fr.Designer.cs
generated_at: "2026-04-16T11:52:25.893174+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "df830ec32326c342"
---
# Documentation: StringResources Localization Designer Files
## 1. Purpose
This module appears to contain auto-generated designer classes for localized string resources supporting Spanish (`es`), Japanese (`ja`), German (`de`), and French (`fr`) cultures. These files are part of the `DTS.Common.SharedResource` assembly and likely provide strongly-typed access to localized strings for internationalization purposes. The `.Designer.cs` suffix indicates these are tool-generated resource accessor classes (typically produced by Visual Studio's resource designer).
**Important limitation:** All four source files provided are empty. The documentation below reflects what can be inferred from file paths and naming conventions alone.
---
## 2. Public Interface
**Cannot be documented.** The source files are empty. No function names, types, or constants are present to reference.
Based on standard .NET resource designer conventions, these files would typically contain:
- A `StringResources` class (culture-specific, e.g., `StringResources.es`, `StringResources.ja`, etc.)
- A `ResourceManager` property returning a cached `System.Resources.ResourceManager` instance
- Static string properties for each localized resource key
However, **none of this can be confirmed from the provided source**.
---
## 3. Invariants
**Cannot be determined from source alone.** The files are empty.
Standard .NET resource designer invariants would typically include:
- The `ResourceManager` property is lazily initialized and cached
- Resource keys are case-sensitive
- The culture-specific classes inherit from a base resource class
**These cannot be verified without actual source code.**
---
## 4. Dependencies
**Inferred from file paths and naming conventions (not confirmed by source):**
| Direction | Dependency |
|-----------|------------|
| **This module depends on** | `System.Resources` (for `ResourceManager`) |
| | `System.Globalization` (for `CultureInfo`) |
| | `System.Reflection` (for assembly loading) |
| **Depends on this module** | Unknown - cannot determine consumers from these files alone |
**Note:** These dependencies are inferred from standard .NET resource designer patterns and cannot be confirmed from the empty source files.
---
## 5. Gotchas
1. **Empty source files provided:** All four `.Designer.cs` files are empty. This is unusual—designer files should contain auto-generated code. This may indicate:
- A copy/export error when extracting the files
- The resources have not yet been generated
- The files are placeholders
2. **Auto-generated code warning:** Files named `.Designer.cs` are typically auto-generated by Visual Studio. Manual edits are usually overwritten by the designer tool and should be avoided.
3. **Culture-specific naming:** The file structure suggests satellite assembly localization, where each culture has its own resource file. Changes to the base resource file (likely `StringResources.resx`) would trigger regeneration of these designer files.
---
## Summary
**The provided source files contain no code.** Complete documentation requires the actual content of these designer files, or alternatively, the source `.resx` files from which they are generated.

View File

@@ -0,0 +1,97 @@
---
source_files:
- Common/DTS.Common.Storage/SensorDB.cs
- Common/DTS.Common.Storage/LocalOnlyOperations.cs
- Common/DTS.Common.Storage/TestHistory.cs
- Common/DTS.Common.Storage/TypeConverter.cs
- Common/DTS.Common.Storage/MMETables.cs
- Common/DTS.Common.Storage/DatabaseServices.cs
- Common/DTS.Common.Storage/TestSetups.cs
- Common/DTS.Common.Storage/UserMigrationHelper.cs
generated_at: "2026-04-16T11:31:09.102777+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5cf7683c6017efd4"
---
# Documentation: DTS.Common.Storage
## 1. Purpose
The `DTS.Common.Storage` namespace provides the data access layer, database schema definitions, and connection management utilities for the DTS DataPRO system. It bridges the application logic and the persistence layer (SQL Server and LocalDB). This module defines database schemas via constants and enums for Sensors, Test Setups, and MME (Measurement and Monitoring Equipment) tables, manages local/remote database connections, handles test history serialization, and provides utilities for type conversion and user data migration.
## 2. Public Interface
### `DTS.Common.Storage.DatabaseServices`
An abstract class providing static methods for database lifecycle management.
* `static void RestoreLocalDatabase(string defaultDbName)`: Restores the local database from `.BAK` files by stopping the LocalDB instance, copying files, and restarting the instance.
* `static void BackupLocalDatabase(string defaultDbName)`: Creates backups of the local database `.mdf` and `_log.ldf` files.
* `static int SetupLocal(string defaultDbName)`: Initializes the connection for a local database using `DbOperations`.
* `static int SetupLocal2(string defaultDbName)`: Initializes the connection for a local database using `LocalOnlyOperations`.
* `static int SetupForRemoteDb(string dbHost, bool userNTLMAuthentication, string user, string password, string defaultDbName)`: Configures the connection for a centralized remote SQL database.
* `static bool SimpleDbTest()`: Executes a simple query (`SELECT TOP 1 [DASId] FROM [DAS]`) to verify database connectivity.
### `DTS.Common.Storage.LocalOnlyOperations`
A singleton class used to access the local database independently of the remote database connection.
* `static LocalOnlyOperations Connection { get; }`: Singleton instance accessor.
* `static void CreateParam(IDbCommand icmd, string name, SqlDbType type, object value)`: Adds a parameter to a command. **Note:** Contains specific logic to convert `DateTime` values to strings or `SqlDateTime.MinValue`.
* `static SqlCommand GetSQLCommand(bool newCommand)`: Retrieves a `SqlCommand`. Reuses a static command object unless `newCommand` is true. Manages connection opening automatically.
* `int ExecuteCommand(IDbCommand icmd)`: Executes a non-query command against a newly opened connection.
* `string GetLocalConnectionString()`: Constructs and caches the connection string using `Server` and `DbName` properties.
### `DTS.Common.Storage.TestHistory`
A serializable entity class representing a record from the test history table.
* `TestHistory(IDataReader reader)`: Constructor that populates the object from a data reader.
* `static TestHistory[] GetTestHistory(string name)`: Retrieves all test histories matching a test setup name via the stored procedure `sp_TestHistoryGet`.
* `static string SerializeToString(TestHistory[] histories)`: Serializes an array of `TestHistory` objects to an XML string using the `TestHistoryCollection` helper class.
### `DTS.Common.Storage.TypeConvertor`
A sealed utility class for mapping between .NET types, `DbType`, and `SqlDbType`.
* `static Type ToNetType(DbType dbType)`
* `static Type ToNetType(SqlDbType sqlDbType)`
* `static DbType ToDbType(Type type)`
* `static DbType ToDbType(SqlDbType sqlDbType)`
* `static SqlDbType ToSqlDbType(Type type)`
* `static SqlDbType ToSqlDbType(DbType dbType)`
### `DTS.Common.Storage.UserMigrationHelper`
A helper class for migrating user data from database version 52 to 53.
* `UserMigrationHelper(DataRow row)`: Parses user data, permissions, and visibility from a `DataRow`.
* `void Commit(Dictionary<string, long> IUIItemNameToID)`: Inserts the user into `DataPROUsers` and related tables (`UserUIItemSettings`, `TagAssignments`). Supports both MSSQL and SQLite execution paths.
### `DTS.Common.Storage.DbOperations` (Partial Classes)
Contains nested abstract classes defining database schemas via constants and enums.
* **`DbOperations.SensorDB`**:
* Constants: `SensorCalibrationTable`, `SensorDataTable`, `SensorModelsTable`.
* Enums: `SensorDataFields`, `SensorModelFields`, `SensorCalibrationFields`, `SensorCalibrationRecordFields`.
* **`DbOperations.MMETables`**:
* Constants: `MMEPossibleChannelsTable`, `MMEDirectionsTable`, `MMEFilterClassesTable`, etc.
* Enums: `MMEPossibleChannelsFields`, `MMEDirectionsFields`, etc.
* Legacy Constants: `MyType`, `CustomChannelType`, `Id` (marked as replaced in specific versions).
* **`DbOperations.TestSetups`**:
* Constants: `HardwareTable`, `DASSettingsTable`, `TestSetupsTable`, etc.
* Enums: `HardwareFields`, `ChannelSettingFields`, `Fields`, `SettingsFields`, etc.
## 3. Invariants
* **Singleton Access**: `LocalOnlyOperations.Connection` and `DbOperations.Connection` are accessed via a singleton pattern protected by a lock (`DbLock`).
* **Schema Consistency**: The `enum` values in `SensorDB`, `MMETables`, and `TestSetups` define the column order or IDs for database tables. `SerialNumber` in `SensorDataFields` is explicitly value `1`.
* **Type Mapping**: `TypeConvertor` maintains a static 1-to-1 mapping between specific .NET types (e.g., `bool`, `DateTime`, `int`) and SQL types (e.g., `Bit`, `DateTime`, `Int`). Unsupported types throw `ApplicationException`.
* **Connection String**: `LocalOnlyOperations` uses Windows Authentication (`Trusted_Connection=TRUE`) exclusively for its connection string.
## 4. Dependencies
* **External Libraries**:
* `System.Data.SqlClient`: Used heavily for SQL Server interaction.
* `System.Xml.Serialization`: Used by `TestHistory` for XML serialization.
* `DTS.Common.Utilities.Logging`: Used for logging (`APILogger.Log`).
* `DbAPI`: Used for connection details and error codes (`DbAPI.Connections.ConnectionDetails`, `DbAPI.Errors.ErrorCodes`).
* **Internal Coupling**:
* `DatabaseServices` depends on `LocalOnlyOperations`, `DbOperations`, and `Utils.Database`.
* `UserMigrationHelper` depends on `DbOperations` to determine if MSSQL or SQLite is being used (`DbOperations._usingMSSQL`).
* `TestHistory` depends on `DbOperations.GetSQLCommand`.
## 5. Gotchas
* **Static Command Reuse**: `LocalOnlyOperations.GetSQLCommand()` reuses a static `SqlCommand` field (`cmd`) by default. If `newCommand` is false, the same object is returned for every call. While `Parameters.Clear()` is called, this creates shared state which may cause issues in multi-threaded scenarios.
* **DateTime Conversion Hack**: In `LocalOnlyOperations.CreateParam`, `DateTime` objects are converted to formatted strings (`yyyy-MM-dd HH:mm:ss`) rather than being passed as native SQL parameters. Additionally, `DateTime` values below `SqlDateTime.MinValue` are clamped to `SqlDateTime.MinValue`. This is likely a workaround for SQL Server `DateTime` range limitations.
* **SQLite vs MSSQL Duality**: `UserMigrationHelper.Commit` checks `DbOperations._usingMSSQL` to switch between `ExecuteCommand` and `ExecuteSQLiteCommand`. However, `LocalOnlyOperations` appears hardcoded to use `SqlConnection` (MSSQL), suggesting the SQLite support is incomplete or localized to specific migration paths.
* **Legacy Schema Constants**: `DbOperations.MMETables` contains constants `MyType`, `CustomChannelType`, and `Id` with comments indicating they were replaced by different string values in software versions 1.3.496 through 1.3.515. Developers should use the current constants (`TYPE`, `ID`) rather than the legacy ones.
* **Typo**: The class `TypeConvertor` is spelled with an "or" suffix instead of the standard "er" (`TypeConverter`).

View File

@@ -0,0 +1,153 @@
---
source_files:
- Common/DTS.Common.Storage/Classes/NoDBAccessException.cs
- Common/DTS.Common.Storage/Classes/DigitalInputSettings.cs
- Common/DTS.Common.Storage/Classes/DbTypeAttr.cs
- Common/DTS.Common.Storage/Classes/DAS.cs
- Common/DTS.Common.Storage/Classes/MMETables.cs
generated_at: "2026-04-16T11:53:30.528055+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "ad177a41b5582582"
---
# DTS.Common.Storage Module Documentation
## 1. Purpose
This module provides data storage schema definitions, custom attributes, and exception handling for the DTS storage layer. It defines database table structures, field enumerations, and hardware prototype identifiers used across the system for data acquisition systems (DAS), digital input settings, and measurement/monitoring equipment (MME) management. The module serves as a central schema contract between the database layer and consuming application code.
---
## 2. Public Interface
### NoDBAccessException
**Signature:** `public class NoDBAccessException : Exception`
**Constructor:**
```csharp
public NoDBAccessException(Exception ex)
```
Wraps an existing exception to indicate a database access failure. Preserves the original exception's message and stack trace by passing it as the inner exception.
---
### DigitalInputSettings
**Signature:** `public class DigitalInputSettings`
Defines the schema for digital input configuration storage.
| Member | Type | Description |
|--------|------|-------------|
| `Table` | `const string` | Value: `"tblDigitalInputSetting"` - the database table name |
| `Fields` | `enum` | Enumeration of column names: `SettingName`, `SettingMode`, `ScaleMultiplier`, `LastModified`, `LastModifiedBy`, `SensorId`, `UserValue1`, `UserValue2`, `UserValue3`, `UserTags` |
---
### DbTypeAttr
**Signature:** `public class DbTypeAttr : Attribute`
A custom attribute for annotating enum members with database type information.
| Member | Signature | Description |
|--------|-----------|-------------|
| `DbType` | `public string DbType { get; private set; }` | The database type string |
| `DbTypeAttr(string attr)` | `internal` constructor | Creates an instance with the specified type. Internal visibility restricts instantiation to this assembly. |
| `GetDbType(object o)` | `public static string GetDbType(object o)` | Uses reflection to retrieve the `DbTypeAttr` value from an object's member. Returns `null` if the object is null, has no members, or lacks the attribute. |
---
### DAS
**Signature:** `public class DAS`
Defines the schema for Data Acquisition System hardware configuration.
**Constants:**
| Member | Value |
|--------|-------|
| `Table` | `"tblDAS"` |
| `TableDASChannels` | `"tblDASChannels"` |
**Prototype Constants (all `const string`):**
- `SLICE1_PROTOTYPE`, `SLICEPRO_PROTOTYPE`, `PROTOTYPE_POSITION`
- `SLICE1_5PROTOTYPE`, `G5_VDSPROTOTYPE`, `G5_IPORTPROTOTYPE`
- `TDASPRO_8MRack`, `TDASPRO_4MRack`, `ECM_PROTOTYPE`
- `SLE_PROTOTYPE`, `SDB_PROTOTYPE`, `Slice_NanoPROTOTYPE`, `Slice_MicroPROTOTYPE`
- `SLICEPRODIM_PROTOTYPE`, `SLICEPROSLD_PROTOTYPE`, `SLICEPROTOM_PROTOTYPE`
- `SLICEPROSLT_PROTOTYPE`, `SLICEPROSIM_PROTOTYPE`, `SLICEPROSLS_PROTOTYPE`
- `SLICE1_5_MicroPROTOTYPE`, `G5_INDUMMYPROTOTYPE`, `SG5_PROTOTYPE`
- `TDASPRO_LabRack`, `SLICE6_PROTOTYPE`, `SLICE6DB_PROTOTYPE`
**Enums:**
| Enum | Fields |
|------|--------|
| `Fields` | `SerialNumber`, `Type`, `MaxModules`, `MaxMemory`, `MaxSampleRate`, `MinSampleRate`, `FirmwareVersion`, `CalDate`, `ProtocolVersion`, `LastModified`, `LastModifiedBy`, `Version`, `LocalOnly`, `LastUsed`, `LastUsedBy`, `Connection`, `Channels`, `Position`, `ChannelTypes`, `Reprogramable`, `Reconfigurable`, `IsModule` |
| `DASChannelFields` | `HardwareId`, `ChannelIdx`, `SupportedBridges`, `SupportedExcitations`, `DASDisplayOrder`, `LocalOnly`, `SupportedDigitalInputModes`, `SupportedSquibFireModes`, `SupportedDigitalOutputModes`, `ModuleSerialNumber`, `ModuleArrayIndex` |
---
### MMETables
**Signature:** `public class MMETables`
Defines schemas for Measurement/Monitoring Equipment reference data tables.
**Legacy Field Name Constants:**
| Constant | Comment |
|----------|---------|
| `MyType` | Exported in versions up to 1.3.496; replaced by `"CustomChannelType"` |
| `CustomChannelType` | Exported in versions 1.3.498 - 1.3.515; replaced by `"TYPE"` |
| `Id` | Exported in versions up to 1.3.515; replaced by `"ID"` |
**Table Constants and Associated Enums:**
| Table Constant | Enum | Notable Fields |
|----------------|------|----------------|
| `MMEPossibleChannelsTable` (`"tblMMEPossibleChannels"`) | `MMEPossibleChannelsFields` | Fields decorated with `[CustomChannelFieldSize(n)]` attribute: `TEST_OBJECT`, `POSITION`, `TRANS_MAIN_LOC`, `FINE_LOC_1/2/3`, `PHYSICAL_DIMENSION`, `DIRECTION`, `DEFAULT_FILTER_CLASS`, `TEXT_L1/L2`, `REMARKS`, `SORTKEY`, `PICTURE_SHORTNAME`, `LAST_CHANGE`, `LAST_CHANGE_TEXT`, `HISTORY` |
| `MMEDirectionsTable` (`"tblMMEDirections"`) | `MMEDirectionsFields` | `s_GUID`, `DIRECTION`, `TEXT_L1/L2`, `VERSION`, `DATE`, `REMARKS`, `EXPIRED`, `SORTKEY`, `LAST_CHANGE`, `LAST_CHANGE_TEXT`, `HISTORY` |
| `MMEFilterClassesTable` (`"tblMMEFilterClasses"`) | `MMEFilterClassesFields` | `s_GUID`, `FILTER_CLASS`, standard metadata fields |
| `MMEFineLocations1Table`/`2Table`/`3Table` | `MMEFineLocations1Fields`/`2Fields`/`3Fields` | `s_GUID`, `FINE_LOC_1/2/3`, standard metadata fields |
| `MMEPhysicalDimensions` (`"tblMMEPhysicalDimensions"`) | `MMEPhysicalDimensionFields` | `s_GUID`, `PHYSICAL_DIMENSION`, `DEFAULT_UNIT`, dimension exponents (`LENGTH_EXP`, `TIME_EXP`, `MASS_EXP`, `ELECTRIC_CURRENT_EXP`, `TEMPERATURE_EXP`, `LUMINOUS_INTENSITY_EXP`, `AMOUNT_OFSUBSTANCE_EXP`) |
| `MMEPositionsTable` (`"tblMMEPositions"`) | `MMEPositionsFields` | `s_GUID`, `POSITION`, standard metadata fields |
| `MMETestObjectsTable` (`"tblMMETestObjects"`) | `MMETestObjectsFields` | `s_GUID`, `TEST_OBJECT`, standard metadata fields |
| `MMEMainLocationTable` (`"tblMMEMainLocations"`) | `MMEMainLocationsFields` | `s_GUID`, `TYPE`, `TRANS_MAIN_LOC`, `PICTURE_SHORTNAME`, standard metadata fields |
---
## 3. Invariants
- **DbTypeAttr construction**: The `DbTypeAttr` constructor is `internal`, ensuring attributes can only be created within this assembly.
- **Field name stability**: The `Fields` enums use implicit integer values (0, 1, 2, ...). Adding new fields to the end of an enum preserves existing values; inserting in the middle would break compatibility.
- **Legacy field name compatibility**: The constants `MyType`, `CustomChannelType`, and `Id` in `MMETables` exist to support data migration from older schema versions (pre-1.3.515).
- **Null safety in GetDbType**: The `DbTypeAttr.GetDbType()` method handles null inputs and missing attributes gracefully by returning `null` rather than throwing.
---
## 4. Dependencies
**This module depends on:**
- `System` namespace (for `Exception`, `Attribute`, reflection types)
- `System.Reflection.MemberInfo` (used in `DbTypeAttr.GetDbType`)
- `CustomChannelFieldSizeAttribute` (referenced in `MMETables.MMEPossibleChannelsFields` but **not defined in these source files**)
**Consumers (inferred):**
- Any module that reads/writes to the defined database tables (`tblDigitalInputSetting`, `tblDAS`, `tblDASChannels`, `tblMME*` tables)
- Hardware detection/configuration logic that references DAS prototype constants
- Database migration tooling that needs to handle legacy field names
---
## 5. Gotchas
1. **Legacy field name migration**: The `MMETables` class contains three legacy field name constants (`MyType`, `CustomChannelType`, `Id`) with explicit version comments. Code reading from or migrating older databases must account for these renamed fields.
2. **Missing attribute definition**: `MMETables.MMEPossibleChannelsFields` uses `[CustomChannelFieldSize(n)]` attribute on multiple fields, but this attribute is not defined in the provided source files. Its location and behavior are unknown.
3. **Reflection performance**: `DbTypeAttr.GetDbType()` performs reflection on every call. In performance-critical paths, consider caching results.
4. **NoDBAccessException loses original type**: Wrapping an exception in `NoDBAccessException` obscures the original exception type. Catch blocks looking for specific exception types (e.g., `SqlException`) will not match.
5. **Typo in enum field**: `MMEPhysicalDimensionFields.AMOUNT_OFSUBSTANCE_EXP` appears to have a missing space in "OFSUBSTANCE" — this may be intentional (matching database column name) or a typo that is now persisted in the schema.

View File

@@ -0,0 +1,127 @@
---
source_files:
- Common/DTS.Common.Storage/Classes/Abstract/MMEPossibleChannels.cs
- Common/DTS.Common.Storage/Classes/Abstract/DbVersions.cs
- Common/DTS.Common.Storage/Classes/Abstract/Settings.cs
- Common/DTS.Common.Storage/Classes/Abstract/VersionTable.cs
- Common/DTS.Common.Storage/Classes/Abstract/TestObjectChannelSettings.cs
- Common/DTS.Common.Storage/Classes/Abstract/Tags.cs
- Common/DTS.Common.Storage/Classes/Abstract/DigitalOutputSettings.cs
- Common/DTS.Common.Storage/Classes/Abstract/LabratoryDetails.cs
- Common/DTS.Common.Storage/Classes/Abstract/Squib.cs
- Common/DTS.Common.Storage/Classes/Abstract/CalculatedChannels.cs
- Common/DTS.Common.Storage/Classes/Abstract/Users.cs
- Common/DTS.Common.Storage/Classes/Abstract/LevelTriggers.cs
- Common/DTS.Common.Storage/Classes/Abstract/SensorDB.cs
- Common/DTS.Common.Storage/Classes/Abstract/TestSetups.cs
generated_at: "2026-04-16T11:55:23.145140+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "275c64f80988749d"
---
# Documentation: DTS.Common.Storage Schema Definitions
## 1. Purpose
This module provides a collection of abstract classes that serve as schema definitions for the DTS storage system. It centralizes database table names and column identifiers into static constants and enumerations. Its primary role is to provide type-safe, compile-time references for database entities—such as Users, Sensors, TestSetups, and various hardware configurations—decoupling the codebase from raw string literals used in SQL queries or data access layers.
## 2. Public Interface
The module consists of the following abstract classes, which cannot be instantiated but provide static members for schema reference.
### `MMEPossibleChannels`
* **`const string Table`**: Value `"tblMMEPossibleChannels"`.
### `DbVersions` (Namespace: `Storage.Classes.Abstract`)
* **`enum DbVersionFields`**: Members: `Version`, `Step`, `Date`, `Remarks`, `UserField`.
### `Settings`
* **`const string Table`**: Value `"tblSettings"`.
* **`enum UserFields`**: Members: `PropertyId`, `PropertyType`, `PropertyValue`, `UserId`.
### `VersionTable`
* **`const string TableName`**: Value `"tblDataPRODbVersion"`.
* **`enum Fields`**: Members: `Version`, `Step`, `Date`, `Remarks`, `UserField`.
### `TestObjectChannelSettings`
* **`const string TableName`**: Value `"tblTestObjectChannelSettings"`.
* **`enum Fields`**: Members: `TestObjectSerial`, `ChannelId`, `Setting`, `SensorSerial`.
### `Tags`
* **`const string Table`**: Value `"tblTags"`.
* **`enum TagFields`**: Members: `TagId`, `TagText`, `Obssolete`.
* **`const string TAGASSIGNMENTS_TABLE`**: Value `"TagAssignments"`.
* **`enum TagAssignmentFields`**: Members: `ObjectID`, `ObjectType`, `TagID`.
### `DigitalOutputSettings`
* **`const string Table`**: Value `"tblTOMDigitalChannels"`.
* **`enum Fields`**: Members: `ChannelDescription`, `DelayMS`, `DurationMS`, `OutputMode`, `LimitDuration`, `LastModified`, `LastModifiedBy`, `Version`, `LocalOnly`, `DurationMSFloat`, `UserTags`.
### `LabratoryDetails`
* **`const string Table`**: Value `"tblLabratoryDetails"`.
* **`enum LabratoryDetailsFields`**: Members: `Name`, `LabratoryName`, `LabratoryContactName`, `LabratoryContactPhone`, `LabratoryContactFax`, `LabratoryContactEmail`, `LabratoryTestRefNumber`, `LabratoryProjectRefNumber`, `LastModified`, `LastModifiedBy`, `LocalOnly`, `Version`.
### `Squib`
* **`const string Table`**: Value `"tblTOMSquibChannels"`.
* **`enum Fields`**: Members: `SquibDescription`, `BypassCurrentFilter`, `BypassVoltageFilter`, `DelayMS`, `DurationMS`, `FireMode`, `ISOCode`, `MeasurementType`, `SquibOutputCurrent`, `SquibToleranceLow`, `SquibToleranceHigh`, `LimitDuration`, `ArticleId`, `LocalOnly`, `Version`, `LastModified`, `LastModifiedBy`, `UserValue1`, `UserValue2`, `UserValue3`, `UserTags`.
### `CalculatedChannels`
* **`const string Table`**: Value `"tblCalculatedChannels"`.
* **`enum Fields`**: Members decorated with `DbTypeAttr`:
* `Id` (`INTEGER PRIMARY KEY NOT NULL`)
* `Operation` (`INTEGER`)
* `CalculatedChannelValueCode` (`NVARCHAR(255)`)
* `InputChannelIds` (`BLOB`)
* `CFCForInputChannels` (`NVARCHAR(255)`)
* `CFCForOutput` (`NVARCHAR(255)`)
* `TestSetupName` (`NVARCHAR(255)`)
* `CCName` (`NVARCHAR(255)`)
### `Users`
* **`const string USERS_TABLE`**: Value `"DataPROUsers"`.
* **`enum UserFields`**: Members: `ID`, `UserName`, `DisplayName`, `Password`, `Role`, `LastModified`, `LastModifiedBy`, `LocalOnly`.
* **`const string UIITEMS_TABLE`**: Value `"UIITEMS"`.
* **`enum UIItemFields`**: Members: `ID`, `Name`.
* **`const string USERUISETTINGS_TABLE`**: Value `"UserUIItemSettings"`.
* **`enum UserUIItemSettingFields`**: Members: `UserId`, `UIItemID`, `Permission`, `Visible`.
### `LevelTriggers`
* **`const string Table`**: Value `"tblLevelTriggers"`.
* **`enum Fields`**: Members decorated with `DbTypeAttr` (e.g., `TestSetupName`, `GroupSerialNumber`, `HardwareChannelId`, `GreaterThanEnabled`, `GreaterThanEU`, etc.).
### `SensorDB`
* **`const string SensorCalibrationTable`**: Value `"tblSensorCalibrations"`.
* **`const string SensorDataTable`**: Value `"tblSensors"`.
* **`const string SensorModelsTable`**: Value `"tblSensorModels"`.
* **`enum SensorDataFields`**: Members include `SerialNumber`, `UserSerialNumber`, `Model`, `Manufacturer`, `Status`, `MeasurementUnit`, `OffsetToleranceLow`, `OffsetToleranceHigh`, `Id`, etc.
* **`enum SensorModelFields`**: Members include `Model`, `Manufacturer`, `UserPartNumber`, `Capacity`, etc.
* **`enum SensorCalibrationFields`**: Members include `SerialNumber`, `CalibrationDate`, `Username`, `NonLinear`, etc.
* **`enum SensorCalibrationRecordFields`**: Members include `Sensitivity`, `Poly`, `AtCapacity`, etc.
### `TestSetups`
* **`const string HardwareTable`**: Value `"tblTestSetupHardware"`.
* **`enum HardwareFields`**: Members: `TestSetupName`, `HardwareId`, `AddOrRemove`.
* **`const string DASSettingsTable`**: Value `"tblTestSetupDASSettings"`.
* **`const string ChannelSettingsTable`**: Value `"tblTestChannelSettings"`.
* **`enum ChannelSettingFields`**: Members: `TestName`, `TestObjectName`, `ChannelId`, `Setting`, `SensorSerial`.
* **`const string TestSetupsTable`**: Value `"tblTestSetups"`.
* **`enum Fields`**: Extensive list including `SetupName`, `SetupDescription`, `AutomaticTestProgression`, `SamplesPerSecond`, `PreTriggerSeconds`, `PostTriggerSeconds`, `ExportFormat`, etc.
* **`const string TestSetupObjectsTable`**: Value `"tblTestSetupObjects"`.
* **`enum TestSetupObjectFields`**: Members: `TestObjectSerialNumber`, `TestSetupName`, `TargetSampleRate`, `ExcitationWarmupTimeMS`, `LocalOnly`, `TestObjectType`, `TestObjectPosition`.
* **`const string TestObjectMetaDataTable`**: Value `"tblTestSetupObjectMetaData"`.
* **`enum TestObjectMetaDataFields`**: Members: `TestObject`, `SetupName`, `PropName`, `PropValue`, `Optional`, `Version`.
* **`const string TestObjectTemplatesTable`**: Value `"tblTestObjectTemplates"`.
* **`enum TestObjectTemplatesFields`**: Members: `TemplateName`, `Icon`, `Description`, `LocalOnly`, `Version`, `LastModifiedBy`, `CRC32`, `TestObject`, `LastModified`, `ParentTemplate`, `SysBuilt`.
* **`const string TestObjectsTable`**: Value `"tblTestObjects"`.
* **`enum TestObjectsFields`**: Members: `SerialNumber`, `LastModifiedBy`, `LastModified`, `Template`, `LocalOnly`, `ParentObject`, `SysBuilt`, `Embedded`, `OriginalTemplate`, `OriginalSerialNumber`.
* **`const string TestGraphsTable`**: Value `"tblTestGraphs"`.
* **`enum GraphFields`**: Members: `GraphName`, `GraphDescription`, `TemplateName`, `Channels`, `UseDomainMin`, `DomainMin`, etc.
## 3. Invariants
* **Abstract Definition**: All schema classes (`MMEPossibleChannels`, `Settings`, `Users`, etc.) are declared `abstract`. They are intended to be used as static containers for constants and enums, not instantiated.
* **Enum Usage**: Nested enums are used to define field names. This implies the system likely casts these enum values to integers or strings (via `.ToString()`) when constructing queries, or uses them for array indexing.
* **Attribute Metadata**: Only `CalculatedChannels` and `LevelTriggers` utilize the `[DbTypeAttr]` attribute. The absence of this attribute on other classes implies that schema type inference (if used) relies on default mappings or a different mechanism for those classes.
## 4. Dependencies
* **Internal Dependencies**: The source files do not contain `using` statements for external libraries, indicating they are self-contained data structures.
* **External Consumers**: Any module handling database persistence (DAOs, Repositories, SQL builders) within the `DTS`

View File

@@ -0,0 +1,73 @@
---
source_files:
- Common/DTS.Common.Storage/Classes/Static/CustomChannelFieldSizeAttribute.cs
generated_at: "2026-04-16T11:54:41.555458+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "96c94c51da2a1b2d"
---
# Documentation: CustomChannelFieldSizeAttribute.cs
## 1. Purpose
This module provides a mechanism for associating fixed size metadata with enum values (specifically `MMETables.MMEPossibleChannelsFields`), enabling retrieval of custom field sizes via reflection. It exists to decouple size configuration from business logic, allowing channel field sizes to be defined declaratively as attributes on enum members rather than hard-coded elsewhere.
---
## 2. Public Interface
### `CustomChannelFieldSizeAttribute` (Class)
A custom attribute that stores an integer size value.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `internal CustomChannelFieldSizeAttribute(int size)` | Creates an instance with the specified size. **Note: Internal access only.** |
| Property | `public int Size { get; private set; }` | Gets the size value. Read-only after construction. |
### `CustomChannelFieldSizeExtensions` (Static Class)
Provides helper methods for retrieving field sizes.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetFieldSize` | `public static int GetFieldSize(MMETables.MMEPossibleChannelsFields field)` | Retrieves the `Size` value from the `CustomChannelFieldSizeAttribute` applied to the given enum value. **Not an extension method**—must be called statically. |
### `EnumExtensions` (Static Class)
Provides generic reflection-based attribute retrieval for enum values.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetAttribute<TAttribute>` | `public static TAttribute GetAttribute<TAttribute>(this Enum value) where TAttribute : Attribute` | Extension method that retrieves a single custom attribute of type `TAttribute` from the given enum value. Returns `null` if not found; throws `InvalidOperationException` if multiple matching attributes exist. |
---
## 3. Invariants
- **Attribute Application**: `GetFieldSize` assumes that `CustomChannelFieldSizeAttribute` is always applied to the passed `MMEPossibleChannelsFields` enum value. If the attribute is missing, a `NullReferenceException` will occur.
- **Single Attribute Constraint**: `GetAttribute<TAttribute>` uses `SingleOrDefault()`, enforcing that at most one attribute of a given type may be present on any enum value. Multiple attributes of the same type will cause an `InvalidOperationException`.
- **Immutability**: The `Size` property is set only at construction and cannot be modified thereafter (private setter).
- **Construction Restriction**: The attribute constructor is `internal`, meaning attributes can only be defined within the same assembly.
---
## 4. Dependencies
### This module depends on:
- `System` (for `Attribute`, `Enum`, `Type` reflection APIs)
- `System.Linq` (for `OfType<T>()`, `SingleOrDefault()`)
- `MMETables.MMEPossibleChannelsFields` — an external enum type that this module is designed to annotate. **Location/assembly not visible in source.**
### What depends on this module:
- Cannot be determined from source alone. Consumers would be any code that needs to retrieve field sizes for `MMEPossibleChannelsFields` enum values.
---
## 5. Gotchas
1. **`GetFieldSize` is NOT an extension method** — Despite being defined in a class named `CustomChannelFieldSizeExtensions`, the method lacks the `this` keyword on its parameter. It must be called as `CustomChannelFieldSizeExtensions.GetFieldSize(field)`, not `field.GetFieldSize()`.
2. **Potential `NullReferenceException`**`GetFieldSize` directly accesses `.Size` on the result of `GetAttribute<CustomChannelFieldSizeAttribute>()` without null-checking. If the enum value lacks this attribute, the method will throw.
3. **Internal constructor limits extensibility** — The `internal` constructor means consumers outside this assembly cannot create new instances of `CustomChannelFieldSizeAttribute`. This is likely intentional to control where/how the attribute is applied, but could be restrictive for testing or extension scenarios.
4. **Tight coupling to specific enum type**`GetFieldSize` is hardcoded to `MMETables.MMEPossibleChannelsFields`, making this utility non-reusable for other enums even though `GetAttribute<T>` is generic.

View File

@@ -0,0 +1,46 @@
---
source_files:
- Common/DTS.Common.Storage/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:53:53.492402+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "4cfe76befa81e318"
---
# Documentation: DTS.Common.Storage Assembly Configuration
## 1. Purpose
This file provides assembly-level metadata and configuration for the `DTS.Common.Storage` component (compiled as "Storage.dll"). It defines the assembly's identity, version, and COM visibility settings. As a standard .NET assembly information file, it serves as the central manifest for the library's attributes within the broader "DTS.Common" namespace.
## 2. Public Interface
This file contains no public classes, methods, or functions. It strictly defines assembly-level attributes using C# attribute syntax.
**Defined Attributes:**
* **`AssemblyTitle`**: Set to `"Storage"`. Provides a friendly name for the assembly.
* **`AssemblyDescription`**: Set to an empty string. Intended for a summary of the assembly's purpose but currently undefined.
* **`AssemblyCompany`**: Set to an empty string.
* **`AssemblyProduct`**: Set to `"Storage"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2012"`.
* **`AssemblyCulture`**: Set to an empty string (neutral culture).
* **`ComVisible`**: Set to `false`. Prevents types within this assembly from being visible to COM components.
* **`Guid`**: Set to `"b62ab8e0-42f4-4a11-bad5-0add30baad84"`. A unique identifier for the assembly, required if COM interop is ever enabled.
* **`AssemblyVersion`**: Set to `"1.0.0.0"`. Defines the version number used by the CLR binding system.
* **`AssemblyFileVersion`**: Set to `"1.0.0.0"`. Defines the version number displayed in the file properties (Win32 file version resource).
## 3. Invariants
* **Version Consistency:** Both `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `"1.0.0.0"`.
* **COM Visibility:** The assembly is explicitly configured to hide types from COM (`ComVisible(false)`). If specific types need to be exposed to COM later, this attribute must be set to `true` or overridden on specific classes.
* **Identity:** The `Guid` attribute provides a permanent unique identity for this specific assembly.
## 4. Dependencies
* **Internal Dependencies (Imports):**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **External Dependents:** Unknown from this source alone. Any project referencing the compiled `DTS.Common.Storage` assembly depends on the version and metadata defined here.
## 5. Gotchas
* **Legacy Timestamp:** The `AssemblyCopyright` attribute contains a hardcoded year of 2012, suggesting this is a legacy codebase that may not have been updated recently.
* **Missing Description:** The `AssemblyDescription` is empty. Developers investigating this assembly via tools or object browsers will not see a summary description of its purpose.
* **Hardcoded Version:** The version numbers are hardcoded to `1.0.0.0`. In modern CI/CD pipelines, this file typically requires patching during the build process to reflect accurate build numbers, or it should be migrated to a modern SDK-style project format where versioning is often handled in the project file (`.csproj`).

View File

@@ -0,0 +1,58 @@
---
source_files:
- Common/DTS.Common.Tests/ChannelTypeUtilityShould.cs
- Common/DTS.Common.Tests/NetworkUtilsShould.cs
- Common/DTS.Common.Tests/LinearizationFormulaShould.cs
- Common/DTS.Common.Tests/GroupChannelShould.cs
- Common/DTS.Common.Tests/FilterClassShould.cs
generated_at: "2026-04-16T11:33:05.077220+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "6d6fac19105f4e74"
---
# DTS.Common.Tests
## Documentation: DTS.Common Module
### 1. Purpose
The `DTS.Common` module provides core utility classes and data structures for handling sensor configuration, signal processing, and network communication within the DTS system. It centralizes logic for parsing sensor identifiers, linearizing raw sensor data using polynomial formulas, managing software filter channel configurations (ISO codes), and parsing network connection strings. This module serves as the foundational layer for sensor data interpretation and device connectivity.
### 2. Public Interface
#### Class: `DTS.Common.Classes.Sensors.ChannelTypeUtility`
A utility class for parsing sensor naming conventions.
* **`string ParseSensorKnownChannelType(string sensorName)`**
* Extracts a known channel type prefix from a sensor name string.
* Returns the string representation of the `KnownChannelTypes` enum if the prefix is valid.
* Returns `string.Empty` if the input is `null`, empty, has fewer than 2 characters, or if the 2-character prefix is not defined in `KnownChannelTypes`.
#### Class: `DTS.Common.Utils.NetworkUtils`
A utility class for network-related string parsing.
* **`bool TryParseConnectionString(string connectionString, out string ipAddress)`**
* Attempts to extract an IP address from a connection string.
* Returns `true` and populates `ipAddress` (excluding port) if a valid IP is found.
* Returns `false` if the connection string is `null` or does not contain a parseable IP address (e.g., a USB device path).
* Supports formats: `IP`, `IP:Port`, `protocol://IP:Port` (e.g., `http`, `udp`).
#### Class: `DTS.Common.Classes.Sensors.LinearizationFormula`
Handles the conversion of raw sensor values to Engineering Units (EU).
* **`double[] PolynomialCoefficients`** (Property)
* An array of doubles representing the coefficients for the linearization polynomial.
* **`NonLinearStyles NonLinearStyle`** (Property)
* Specifies the style of non-linear calculation. Defaults to `NonLinearStyles.Polynomial`.
* **`double GetLinearizedValue(double input, int decimalPlaces, bool? proportional)`**
* Calculates the linearized value based on the `PolynomialCoefficients`.
* `input`: The raw sensor value.
* `decimalPlaces`: Precision of the result (inferred from test context).
* `proportional`: A nullable boolean flag affecting the calculation logic. When `null` or `true`, the calculation differs from when it is `false`.
#### Class: `DTS.Common.Classes.Sensors.FilterClass`
Represents a software filter configuration and provides mapping logic between ISO codes, frequencies, and filter class types.
* **`FilterClassType FClass`** (Property)
* The type of the filter (e.g., `CFC1000`, `AdHoc`).
* **`double Frequency`** (Property)
* The frequency associated with the filter class.
* **`static FilterClass GetFilterClassFromString(string input)`**
* Parses a string (e.g., "CFC 1000", "600", "1700Hz", "None") into a `FilterClass` object.
* Returns

View File

@@ -0,0 +1,282 @@
---
source_files:
- Common/DTS.Common.Utilities/DTS.Utilities.cs
- Common/DTS.Common.Utilities/DegreesFromADC.cs
- Common/DTS.Common.Utilities/TaskbarHelper.cs
- Common/DTS.Common.Utilities/LevelTriggerLogging.cs
- Common/DTS.Common.Utilities/SignalToNoiseRatio.cs
- Common/DTS.Common.Utilities/StandardDev.cs
- Common/DTS.Common.Utilities/LargeArray.NameGeneratorLock.cs
- Common/DTS.Common.Utilities/XmlToObject.cs
- Common/DTS.Common.Utilities/FirmwareVersionToLong.cs
- Common/DTS.Common.Utilities/NaturalStringCompare.cs
- Common/DTS.Common.Utilities/KeywordAlert.cs
- Common/DTS.Common.Utilities/DataFlag.cs
- Common/DTS.Common.Utilities/Time.cs
- Common/DTS.Common.Utilities/PropertyComparer.cs
- Common/DTS.Common.Utilities/Math.DoubleListOperation.cs
- Common/DTS.Common.Utilities/UpdateNotifyingList.cs
- Common/DTS.Common.Utilities/DataWindowAverager.WindowDoesNotExistException.cs
- Common/DTS.Common.Utilities/Property.ConstructionException.cs
- Common/DTS.Common.Utilities/Property.InvalidValueException.cs
- Common/DTS.Common.Utilities/Property.NotInitializedException.cs
- Common/DTS.Common.Utilities/RangeRestrictedIntProperty.InvalidRangeException.cs
- Common/DTS.Common.Utilities/TextLogger.LogPathnameNotInitializedException.cs
- Common/DTS.Common.Utilities/RangeRestrictedDoubleProperty.InvalidRangeException.cs
- Common/DTS.Common.Utilities/LargeArray.MissingScratchFileException.cs
- Common/DTS.Common.Utilities/LargeArray.LargeOverflowException.cs
- Common/DTS.Common.Utilities/DescriptionAttributeCoder.cs
- Common/DTS.Common.Utilities/LargeArray.ScratchFileAlreadyExistsException.cs
- Common/DTS.Common.Utilities/CRC32.cs
- Common/DTS.Common.Utilities/AverageQueue.cs
- Common/DTS.Common.Utilities/ExceptionalForm.cs
- Common/DTS.Common.Utilities/SortableBindingList.cs
- Common/DTS.Common.Utilities/ExceptionalUserControl.cs
- Common/DTS.Common.Utilities/EnumDropDown.cs
- Common/DTS.Common.Utilities/XmlSerializationTagAttribute.cs
- Common/DTS.Common.Utilities/ExceptionalList.cs
- Common/DTS.Common.Utilities/Win32APIs.cs
generated_at: "2026-04-16T11:32:34.054047+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "a50bc074e645dae7"
---
# DTS.Common.Utilities Documentation
## 1. Purpose
`DTS.Common.Utilities` is a general-purpose utility library providing common functionality for DTS applications. It includes mathematical operations (standard deviation, SNR calculation, degree conversion), data structures (sortable binding lists, average queues, notifying lists), Windows Forms helpers (enum dropdowns, exceptional base classes), file/memory operations (CRC32, memory-mapped file support via Win32 APIs), XML serialization helpers, and various framework extensions (property comparers, attribute coders). The library serves as a foundational layer reused across multiple DTS projects.
---
## 2. Public Interface
### Mathematical Utilities
#### `DTS.Common.Utilities.DegreesFromADC`
- `public static double GetDegrees(double Sxyz, double SG)` — Converts ADC values to degrees using arcsin formula: `(180/π) * asin(Sxyz / SG)`.
#### `DTS.Common.Utilities.SignalToNoiseRatio`
- `public static double CalculateSNR(IEnumerable<double> values, double fullScalePP = 65536.0)` — Calculates signal-to-noise ratio given a dataset and full scale peak-to-peak value (defaults to 65536.0 for ADC data).
#### `DTS.Common.Utilities.StandardDev`
- `public static double StandardDeviation(IEnumerable<double> values)` — Calculates sample standard deviation using Bessel's correction (n-1 denominator). Returns 0 for empty collections.
#### `DTS.Common.Utilities.Math.DoubleListOperation` (abstract)
- `public DoubleListOperation(IList<double> domain)` — Abstract base class for mathematical operations on `IList<double>` data. Inherits from `Operation<IList<double>, IList<double>>`.
#### `DTS.Common.Utilities.Crc32`
- `public Crc32()` — Constructor that builds the CRC32 lookup table.
- `public uint Get<T>(IEnumerable<T> byteStream)` — Calculates 32-bit reversed CRC checksum. Throws `FormatException`, `InvalidCastException`, or `OverflowException` if conversion to byte fails.
#### `DTS.Common.Utilities.AverageQueue`
- `public AverageQueue(int length)` — Constructs a fixed-length queue for running average calculation.
- `public double Push(double newValue)` — Adds a value to the queue, returns current average. Thread-safe.
- `public double GetAverage()` — Returns current average. Thread-safe.
- `public void Reset()` — Clears the queue. Thread-safe.
- `public double GetMin()` — Returns minimum value in queue. Thread-safe.
- `public double GetMax()` — Returns maximum value in queue. Thread-safe.
### Time Utilities
#### `DTS.Common.Utilities.Time`
- `public static UInt32 DateTimeToUnixTimestamp(DateTime dateTime)` — Converts DateTime to Unix timestamp (seconds since 1970-01-01). No timezone correction.
- `public static UInt32 CurrentUtcUnixTimestamp()` — Returns current UTC time as Unix timestamp.
- `public static UInt32 CurrentLocalUnixTimestamp()` — Returns current time as Unix timestamp (calculated from UtcNow but with Local kind in epoch).
- `public static DateTime ToDateTime(UInt32 seconds)` — Converts Unix timestamp back to DateTime.
- `public static UInt32 ToUnixTime(DateTime dateTime)` — Alias for `DateTimeToUnixTimestamp`.
- `public static bool IsBeginningOfTime(DateTime dateTime)` — Returns true if DateTime equals Unix epoch (1970-01-01).
### String/Version Utilities
#### `DTS.Common.Utilities.FirmwareVersionToLong`
- `public static long Query(string version)` — Converts firmware version string to long by taking first 4 characters and bit-shifting each character into 16-bit positions (shifts: 48, 32, 16, 0).
#### `DTS.Common.Utilities.NaturalStringComparer` : `IComparer<string>`
- `public int Compare(string x, string y)` — Natural string comparison (like Windows Explorer). Returns -1 if x < y, 1 if x > y, 0 if equal. Null strings sort first.
- `public static int StaticCompare(string x, string y)` — Static version of `Compare`.
### XML Utilities
#### `DTS.Common.Utilities.Xml.XmlToObject<T>`
- `public static T FromXml(string xml)` — Deserializes XML string to object of type T. Returns `default(T)` on any exception (including `InvalidOperationException` from deserialization).
#### `DTS.Common.Utilities.Xml.XmlSerializationTagAttribute` : `Attribute`, `IComparable<XmlSerializationTagAttribute>`
- `public string Value { get; }` — The tag string value.
- `public int Order { get; }` — Sort order for multiple tags.
- `public XmlSerializationTagAttribute(string value)` — Constructor with default order 0.
- `public XmlSerializationTagAttribute(string value, int order)` — Constructor with explicit order.
- `public int CompareTo(XmlSerializationTagAttribute that)` — Compares by Order property.
### Windows/OS Integration
#### `DTS.Utilities.TaskbarHelper`
- `public static extern int SetCurrentProcessExplicitAppUserModelID([MarshalAs(UnmanagedType.LPWStr)] string AppID)` — P/Invoke to `shell32.dll` to set Windows taskbar AppUserModelID. Reference: FB 45077.
### Logging
#### `DTS.Common.Utilities.LTLogging.LevelTriggerLogging`
- `public static void LevelTriggerLog(string msg)` — Thread-safe append to `Logs\LevelTriggerSettings.txt`.
### Collections/Data Structures
#### `DTS.Common.Utilities.SortableBindingList<T>` : `BindingList<T>`
- `public SortableBindingList()` — Default constructor.
- `public SortableBindingList(IEnumerable<T> enumeration)` — Construct from enumeration.
- Protected sorting/searching overrides: `SupportsSortingCore`, `IsSortedCore`, `SortPropertyCore`, `SortDirectionCore`, `SupportsSearchingCore`, `ApplySortCore`, `RemoveSortCore`, `FindCore`.
#### `DTS.Common.Utilities.PropertyComparer<T>` : `IComparer<T>`
- `public PropertyComparer(PropertyDescriptor property, ListSortDirection direction)` — Constructs comparer for specified property and sort direction.
- `public int Compare(T x, T y)` — Compares two objects by the configured property.
- `public void SetPropertyAndDirection(PropertyDescriptor descriptor, ListSortDirection direction)` — Updates property and sort direction.
#### `DTS.Common.Utilities.UpdateNotifyingList<T>` : `Exceptional`
- `public List<T> Items { get; set; }` — Gets/sets the list contents; setter triggers `OnUpdate` event.
- `public delegate void OnUpdateCallback(List<T> updatedContents)` — Callback delegate type.
- `public event OnUpdateCallback OnUpdate` — Event fired when Items is set.
#### `DTS.Common.Utilities.ExceptionalList<T>` : `List<T>`
- `public ExceptionalList()`, `ExceptionalList(int capacity)`, `ExceptionalList(IEnumerable<T> collection)` — Standard list constructors.
- Nested `public class Exception : ApplicationException` — List-specific exception type.
### Windows Forms Components
#### `DTS.Common.Utilities.EnumDropDown<T>` : `System.Windows.Forms.ComboBox` where `T : struct, IComparable`
- `public class EnumListEntry : IComparable<EnumListEntry>` — Wrapper for enum values with DescriptionAttribute decoding.
- `public T Value { get; set; }`
- `public override string ToString()` — Returns decoded description.
- `public delegate bool Filter(T enumEntry)` — Filter delegate type.
- `public Filter EnumFilter { set; }` — Sets filter and repopulates list.
- `public EnumDropDown(Filter defaultFilter)` — Constructor with filter.
- `public void PopulateList()` — Clears and repopulates items based on filter.
- `public EnumListEntry SelectedEntry { get; set; }` — Currently selected entry.
- `public T? SelectedEnum { get; set; }` — Currently selected enum value.
#### `DTS.Common.Utilities.ExceptionalForm` : `Form`
- Nested `public class Exception : ApplicationException` — Form-specific exception type with standard constructors.
#### `DTS.Common.Utilities.ExceptionalUserControl` : `UserControl`
- Nested `public class Exception : ApplicationException` — UserControl-specific exception type with standard constructors.
### Enums and Attributes
#### `DTS.Common.Utilities.DataFlag` (enum)
- `None` (0), `Normal` (1), `Saturated` (2), `ZeroCrossing` (3), `BrokenWire` (4), `Other` (-1)
- Each value has `[Description("...")]` and `[Flag(int)]` attributes.
#### `DTS.Common.Utilities.FlagAttribute` : `Attribute`
- `public int Flag { get; }` — The flag value.
- `public FlagAttribute(int flag)` — Constructor.
#### `DTS.Common.Utilities.DataFlagAttributeCoder` : `AttributeCoder<DataFlag, FlagAttribute, int>`
- `public DataFlagAttributeCoder()` — Constructor for encoding/decoding DataFlag values.
#### `DTS.Common.Utilities.DescriptionAttributeCoder<TTargetType>` : `AttributeCoder<TTargetType, DescriptionAttribute, string>`
- `public DescriptionAttributeCoder()` — Constructor for encoding/decoding DescriptionAttribute values. Uses case-insensitive comparison.
### Keyword Processing
#### `DTS.Common.Utilities.KeywordAlert` (sealed, singleton)
- `public static KeywordAlert Instance { get; }` — Singleton instance.
- `public void ProcessMsg(string msg)` — Queues message for async keyword matching against `Keywords.txt`. Uses PLINQ for parallel matching. **Note:** Matched keys are joined but result is not persisted or returned anywhere visible in source.
### Memory-Mapped File Support
#### `DTS.Common.Utilities.IO.MemoryMap.Win32MapApis` (internal)
- P/Invoke declarations for `kernel32.dll`:
- `CreateFile`, `CreateFileMapping`, `FlushViewOfFile`, `MapViewOfFile`, `OpenFileMapping`, `UnmapViewOfFile`, `CloseHandle`, `GetLastError`.
#### `DTS.Common.Utilities.IO.MemoryMap.LargeArray<T>` (partial)
- `protected class NameGeneratorLock` — Locking object for scratch file name generation.
- `private class MissingScratchFileException : ApplicationException`
- `private class ScratchFileAlreadyExistsException : ApplicationException`
- `private class LargeOverflowException : ApplicationException`
### Exception Types (Various)
#### `DTS.Common.Utilities.DataWindowAverager.WindowDoesNotExistException` : `ApplicationException`
- Standard exception constructors for invalid window access.
#### `DTS.Common.Utilities.DotNetProgrammingConstructs.Property<Type>.ConstructionException` : `Exception`
- Exception for property construction failures.
#### `DTS.Common.Utilities.DotNetProgrammingConstructs.Property<Type>.InvalidValueException` : `Exception`
- Exception for invalid property values.
#### `DTS.Common.Utilities.DotNetProgrammingConstructs.Property<Type>.NotInitializedException` : `Exception`
- Exception for uninitialized property access.
#### `DTS.Common.Utilities.DotNetProgrammingConstructs.RangeRestrictedIntProperty.InvalidRangeException` : `Exception`
- Exception for integer range violations.
#### `DTS.Common.Utilities.DotNetProgrammingConstructs.RangeRestrictedDoubleProperty.InvalidRangeException` : `Exception`
- Exception for double range violations.
#### `DTS.Common.Utilities.Logging.TextLogger.LogPathnameNotInitializedException` : `ApplicationException` (private)
- Exception for uninitialized log pathname.
---
## 3. Invariants
- **StandardDev.StandardDeviation**: Returns 0 for empty collections; uses sample standard deviation (n-1 divisor).
- **AverageQueue**: Always maintains `_queueSum` as the sum of current queue contents; `Queue.Count` never exceeds `QueueLength`.
- **XmlToObject.FromXml**: Always returns `default(T)` on any failure (never throws to caller).
- **NaturalStringComparer.Compare**: Null values are always sorted first (null x returns -1, null y returns 1).
- **FirmwareVersionToLong.Query**: Only processes first 4 characters of version string; shorter strings use available characters.
- **KeywordAlert**: Singleton pattern; `alerts` list is only populated if `Keywords.txt` exists and is readable.
- **Time conversions**: All Unix timestamp methods use `UInt32` (32-bit), limiting date range to 19702106.
- **LargeArray exceptions**: All nested exception classes are `private` to `LargeArray<T>`.
---
## 4. Dependencies
### External Dependencies (Imports)
- `System` (core types, `Math`, `DateTime`, `Exception`)
- `System.Collections.Generic` (`List<T>`, `IEnumerable<T>`, `IList<T>`, `Queue<T>`, `Dictionary<TKey,TValue>`)
- `System.ComponentModel` (`PropertyDescriptor`, `ListSortDirection`, `DescriptionAttribute`, `BindingList<T>`)
- `System.Linq` (LINQ extensions, `AsParallel()`)
- `System.Runtime.InteropServices` (P/Invoke, `DllImport`, `MarshalAs`)
- `System.Runtime.Serialization` (`SerializationInfo`, `StreamingContext`)
- `System.Text` (`StringBuilder`)
- `System.Threading` (`ThreadPool`, `WaitCallback`)
- `System.Threading.Tasks` (`Task`)
- `System.Windows.Forms` (`Form`, `UserControl`, `ComboBox`)
- `System.Xml.Serialization` (`XmlSerializer`)
- `System.IO` (`TextReader`, `StringReader`, `File`)
### Internal Dependencies
- `DTS.Common.Utilities.DotNetProgrammingConstructs` — Referenced by `Property<T>`, `RangeRestrictedIntProperty`, `RangeRestrictedDoubleProperty`, `Exceptional`, `Operation<TInput,TOutput>`.
- `DTS.Common.Utilities.IO.MemoryMap` — Contains `LargeArray<T>` and `Win32MapApis`.
- `DTS.Common.Utilities.LTLogging` — Contains `LevelTriggerLogging`.
- `DTS.Common.Utilities.Logging` — Contains `TextLogger`.
- `DTS.Common.Utilities.Xml` — Contains `XmlToObject<T>`, `XmlSerializationTagAttribute`.
- `DTS.Common.Utilities.Math` — Contains `DoubleListOperation`.
### Referenced but Not Provided
- `DTS.Common.Utilities.Property<T>` — Referenced by `UpdateNotifyingList<T>` and exception partial classes.
- `DTS.Common.Utilities.RangeRestrictedIntProperty` — Referenced by exception partial class.
- `DTS.Common.Utilities.RangeRestrictedDoubleProperty` — Referenced by exception partial class.
- `DTS.Common.Utilities.Exceptional` — Base class for `UpdateNotifyingList<T>`.
- `DTS.Common.Utilities.Operation<TInput, TOutput>` — Base class for `DoubleListOperation`.
- `DTS.Common.Utilities.AttributeCoder<TTarget, TAttribute, TValue>` — Base class for `DescriptionAttributeCoder` and `DataFlagAttributeCoder`.
- `DTS.Common.Utilities.DataWindowAverager` — Referenced by `WindowDoesNotExistException` partial class.
- `DTS.Common.Utilities.LargeArray<T>` — Main class referenced by partial exception files.
- `DTS.Common.Utilities.TextLogger` — Referenced by `LogPathnameNotInitializedException` partial class.
- `DTS.Common.Utilities.Properties.Resources` — Referenced by `XmlSerializationTagAttribute` for error message.
---
## 5. Gotchas
1. **KeywordAlert.DoWork has no observable output**: The `DoWork` method builds `foundKeys` string from matches but never writes, logs, or returns it. The matched keywords are effectively discarded.
2. **Time.CurrentLocalUnixTimestamp naming is misleading**: The method calculates `DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)`. Subtracting UTC now from a Local-kind epoch produces a counterintuitive result that doesn't represent true local Unix time.
3. **StandardDev.StandardDeviation uses Count()-1 for empty check**: The method calls `values.Any()` to check for emptiness, then later calls `values.Count() - 1` as divisor. If the enumerable has exactly one element, this causes division by zero (resulting in `Infinity` or `NaN`).
4. **XmlToObject.FromXml silently swallows all exceptions**: Any exception during XML deserialization returns `default(T)` without any indication of failure. Callers cannot distinguish between "deserialization failed" and "deserialized to default value."
5. **FirmwareVersionToLong.Query uses character values

View File

@@ -0,0 +1,74 @@
---
source_files:
- Common/DTS.Common.Utilities/Properties/AssemblyInfo.cs
- Common/DTS.Common.Utilities/Properties/Resources.Designer.cs
generated_at: "2026-04-16T11:56:30.722696+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "350fbb2a7eb1ba61"
---
# Documentation: DTS.Common.Utilities
## 1. Purpose
`DTS.Common.Utilities` is a class library intended to provide shared infrastructure and helper components for the DTS software ecosystem. Based on the assembly metadata and embedded resource strings, the library encapsulates cross-cutting concerns such as structured logging (specifically for APIs and text files), exception formatting, attribute-based encoding/decoding (potentially for serialization), and specialized property validation logic (range restriction and power-of-two validation). It also appears to manage configuration settings related to an application named "DataPRO".
## 2. Public Interface
The provided source files consist of assembly metadata and an auto-generated resource accessor. The actual implementation classes (e.g., `APILogger`, `TextLogger`) are not present in the source, but their existence and behavior can be inferred from the `Resources` class.
**Assembly Attributes**
* `AssemblyTitle`: "DTS.Common.Utilities"
* `AssemblyVersion`: "1.0.0.0"
* `ComVisible`: `false` (Types are not exposed to COM by default).
**Class: `DTS.Common.Utilities.Properties.Resources`**
This `internal` class provides strongly-typed access to localized string resources used throughout the library.
* **Properties**: The class exposes numerous `internal static string` properties. Key categories include:
* **Logging Configuration**:
* `APILogging_DateTime_Format`: Format string (e.g., "yyyy-MM-dd HH:mm:ss.fff").
* `APILogging_LogEntrySeperatorString`: Visual separator for log entries.
* **Error Messages**:
* `APILogging_LogException_NullWriterDelegateString`: Error for null writer delegate.
* `TextLogger_Start_NullEmptyFilenameString`: Validation error for logger initialization.
* `AttributeCoder_DecodeAttributeExceptionString`: Error for attribute decoding failures.
* **Validation Messages**:
* `RangeRestrictedDoubleProperty_MinMustBeLessThanMaxString`: Invariant error for range properties.
* `PowerOfTwoProperty_GetInvalidValueDescription_ProposedValueIsNotPowerOf2String`: Validation error.
**Inferred Components (Not in source, implied by resources)**
* `APILogger`: Likely a static or singleton class for logging exceptions and strings.
* `TextLogger`: A class managing a background writer thread for text logging. Implies methods `Start`, `Stop`, `AddMessage`, and `Dispose`.
* `AttributeCoder`: A class for encoding/decoding and "dehashing" attribute values.
* `RangeRestrictedDoubleProperty` / `RangeRestrictedIntProperty`: Classes or structures enforcing min/max value constraints.
* `PowerOfTwoProperty`: A class validating that values are powers of two.
## 3. Invariants
* **COM Visibility**: The assembly is marked `ComVisible(false)`. Types must explicitly opt-in to be visible to COM components.
* **Range Validation**: For `RangeRestrictedDoubleProperty` and `RangeRestrictedIntProperty`, the minimum value must always be less than or equal to the maximum value (implied by `RangeRestricted...MinMustBeLessThanMaxString`).
* **Logger State**:
* `TextLogger` requires `Start` to be called before `AddMessage` or `Stop`.
* `TextLogger` cannot `Start` if already running.
* `TextLogger` requires non-null/non-empty folder and filename arguments for `Start`.
* **Resource Access**: The `Resources` class is `internal` and intended only for use within this assembly.
## 4. Dependencies
**Internal Dependencies (Inferred)**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* `System.Resources` (for `ResourceManager`)
* `System.Globalization` (for `CultureInfo`)
* `System.CodeDom.Compiler`
**External Dependencies**
* **DataPRO**: The library appears to interact with or configure an external application named "DataPRO" (referenced in `RegistryDataPROExe` and `NewSettingsCouldNotBeFound` strings).
## 5. Gotchas
* **Namespace Mismatch in ResourceManager**: The `Resources` class is located in the namespace `DTS.Common.Utilities.Properties`, but the `ResourceManager` constructor is initialized with the resource path `"DTS.Utilities.Properties.Resources"`. This discrepancy (missing `.Common`) suggests a potential runtime failure (`MissingManifestResourceException`) if the actual `.resx` file location does not match the hardcoded string, or it indicates a historical namespace refactoring that was not fully applied to the resource generator.
* **Threading Complexity in TextLogger**: The resource strings reveal complex lifecycle management for the `TextLogger`'s background writer thread (e.g., `TextLogger_Dispose_WriteThreadExitFailureString`, `TextLogger_Start_WriteThreadResponseTimeoutString`). Developers implementing or debugging this class must be aware that thread synchronization issues (timeouts, failure to start/stop) are explicitly handled and may result in specific error states rather than silent failures.
* **Hardcoded DateTime Format**: The `APILogging_DateTime_Format` resource suggests a specific fixed format ("yyyy-MM-dd HH:mm:ss.fff") is expected by the logging mechanism, which may not be culture-aware.

View File

@@ -0,0 +1,53 @@
---
source_files:
- Common/DTS.CommonCore/Attributes/VersionAttribute.cs
generated_at: "2026-04-16T12:02:23.720037+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "97df6c62ae44caee"
---
# Documentation: VersionAttribute
## 1. Purpose
`VersionAttribute` is a custom attribute class that allows developers to annotate code elements (classes, methods, properties, etc.) with an integer version number. It provides a simple mechanism for versioning components within the DTS system, which may be used for tracking API evolution, serialization compatibility, or feature versioning.
## 2. Public Interface
### `VersionAttribute` Class
**Namespace:** `DTS.Common.Attributes`
**Base Class:** `System.Attribute`
#### Constructor
```csharp
public VersionAttribute(int version)
```
Creates a new instance of the attribute with the specified version number. The `version` parameter is stored in the read-only `Version` property.
#### Properties
```csharp
public int Version { get; private set; }
```
Returns the version number specified when the attribute was instantiated. This property is read-only externally; it can only be set via the constructor.
## 3. Invariants
- The `Version` property is immutable after construction (private setter).
- The `Version` value is always an `int`; no null state is possible since `int` is a value type.
- No constraints are enforced on the range of `version` (negative values, zero, and positive values are all accepted).
## 4. Dependencies
### This module depends on:
- `System` — Provides the `Attribute` base class.
- `System.Linq` — Imported but **not used** in the current implementation.
### What depends on this module:
- Cannot be determined from the source file alone. This attribute is defined in `DTS.CommonCore`, suggesting it is part of a core utilities library that other modules likely reference.
## 5. Gotchas
- **Unused import:** The `using System.Linq;` directive is present but not utilized in the code. This may be leftover from refactoring or template code.
- **No `AttributeUsage` declaration:** The attribute lacks an `[AttributeUsage]` specification, meaning it can be applied to any target (classes, methods, assemblies, etc.) with default behavior (allowing multiple instances = false, inherited = true). If specific usage constraints are intended, they are not enforced at the attribute definition level.
- **No version validation:** The constructor accepts any integer, including negative values. If semantic versioning or positive-only constraints are expected by consumers, they are not enforced here.

View File

@@ -0,0 +1,172 @@
---
source_files:
- Common/DTS.CommonCore/Behaviors/StringMetaDataAttr.cs
- Common/DTS.CommonCore/Behaviors/TrimTextBoxBehavior.cs
- Common/DTS.CommonCore/Behaviors/InteractivityTemplate.cs
- Common/DTS.CommonCore/Behaviors/TextBoxPasteBehavior.cs
- Common/DTS.CommonCore/Behaviors/MultiSelectionBehavior.cs
generated_at: "2026-04-16T12:04:47.328170+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c2b7aea8fc779731"
---
# DTS.Common.Behaviors Namespace Documentation
## 1. Purpose
This module provides a collection of WPF behaviors, attached properties, and utility attributes for the DTS CommonCore library. It enables declarative UI interactions through `System.Windows.Interactivity`, including text trimming on focus loss, multi-selection synchronization for `ListBox` controls, paste command handling for `TextBox` derivatives, and a mechanism for applying behaviors/triggers via data templates. It also provides a reflection-based attribute system for attaching string metadata to enum values and objects.
---
## 2. Public Interface
### StringMetaDataAttr
**Kind:** Class (inherits `Attribute`)
**Purpose:** Stores string metadata on objects or enum members.
| Member | Signature | Description |
|--------|-----------|-------------|
| `MetaData` | `public string MetaData { get; }` | Read-only property containing the stored metadata string. |
| `GetStringMetaData` | `public static string GetStringMetaData(object o)` | Retrieves the `MetaData` value from a `StringMetaDataAttr` applied to the object's member (typically enum values). Returns `null` if no attribute is found or if the object is null. |
**Constructor:** `internal StringMetaDataAttr(string attr)` — Internal constructor; attributes must be applied declaratively.
---
### TrimTextBoxBehavior
**Kind:** Class (inherits `Behavior<TextBox>`)
**Purpose:** Automatically trims whitespace from a `TextBox` when it loses focus.
| Member | Signature | Description |
|--------|-----------|-------------|
| `OnAttached` | `protected override void OnAttached()` | Subscribes to `AssociatedObject.LostFocus`. |
| `OnDetaching` | `protected override void OnDetaching()` | Unsubscribes from `AssociatedObject.LostFocus`. |
**Behavior:** On `LostFocus`, trims `AssociatedObject.Text`. If the trimmed value differs, updates the text and calls `UpdateSource()` on the `TextBox.TextProperty` binding expression.
---
### InteractivityTemplate
**Kind:** Class (inherits `DataTemplate`)
**Purpose:** Marker class for defining interactivity templates in XAML resources. Contains no additional members.
---
### InteractivityItems
**Kind:** Class (inherits `FrameworkElement`)
**Purpose:** Container for behaviors and triggers that can be loaded from an `InteractivityTemplate`.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Triggers` | `public new List<TriggerBase> Triggers { get; }` | Lazy-initialized list of triggers. Hides inherited `Triggers` property. |
| `Behaviors` | `public List<Behavior> Behaviors { get; }` | Lazy-initialized list of behaviors. |
| `TemplateProperty` | `public static readonly DependencyProperty TemplateProperty` | Attached property for assigning an `InteractivityTemplate` to a `DependencyObject`. |
| `GetTemplate` | `public static InteractivityTemplate GetTemplate(DependencyObject obj)` | Gets the attached `Template` property value. |
| `SetTemplate` | `public static void SetTemplate(DependencyObject obj, InteractivityTemplate value)` | Sets the attached `Template` property value. |
**Behavior:** When `TemplateProperty` changes, loads `InteractivityTemplate` content, casts to `InteractivityItems`, and adds all behaviors/triggers to the target via `Interaction.GetBehaviors()` and `Interaction.GetTriggers()`.
---
### TextBoxPasteBehavior
**Kind:** Static class (attached property host)
**Purpose:** Enables handling paste operations via an `ICommand` binding on `TextBox` and custom controls.
| Member | Signature | Description |
|--------|-----------|-------------|
| `PasteCommandProperty` | `public static readonly DependencyProperty PasteCommandProperty` | Attached property of type `ICommand`. |
| `GetPasteCommand` | `public static ICommand GetPasteCommand(DependencyObject target)` | Gets the attached `PasteCommand`. |
| `SetPasteCommand` | `public static void SetPasteCommand(DependencyObject target, ICommand value)` | Sets the attached `PasteCommand`. |
**Behavior:** When `PasteCommand` is set, registers a handler for `CommandManager.ExecutedEvent` on the target `TextBox`. When a paste command (`ApplicationCommands.Paste` or a `RoutedUICommand` with `Name == "Paste"`) is executed, retrieves clipboard text, splits by newlines, and executes the bound command with the `TextBox` as parameter. Errors are published via `PageErrorEvent`.
**Special handling:** Supports `ChannelCodeBuilder` and `ChannelNameBuilder` controls by extracting their `MainEditBox` property.
---
### MultiSelectionBehavior
**Kind:** Class (inherits `Behavior<ListBox>`)
**Purpose:** Synchronizes a `ListBox`'s `SelectedItems` collection with a bound `IList` source.
| Member | Signature | Description |
|--------|-----------|-------------|
| `SelectedItems` | `public IList SelectedItems { get; set; }` | Dependency property for binding the source collection. |
| `SelectedItemsProperty` | `public static readonly DependencyProperty SelectedItemsProperty` | Backing field for `SelectedItems`. |
| `OnAttached` | `protected override void OnAttached()` | Initializes `AssociatedObject.SelectedItems` from bound collection. |
**Behavior:**
- Two-way sync between `ListBox.SelectedItems` and bound `IList`.
- Listens to `INotifyCollectionChanged.CollectionChanged` on source.
- Listens to `ListBox.SelectionChanged` for UI-driven changes.
- Uses `SelectedItemsStatus.SetUpdating()` to suppress notifications during bulk operations.
- Type-checks added items against `selectedItems.GetType().GenericTypeArguments[0]`.
---
## 3. Invariants
- **StringMetaDataAttr:** The `GetStringMetaData` method always returns `null` for null objects or when no attribute is found. It assumes `o.ToString()` returns a valid member name.
- **TrimTextBoxBehavior:** Only updates the binding source when trimming actually changes the text (`trim != AssociatedObject.Text`).
- **InteractivityItems:** The `TemplateProperty` change handler does nothing if `e.NewValue` is `null`.
- **TextBoxPasteBehavior:**
- The paste handler only executes if `command.CanExecute(null)` returns `true`.
- The command receives the `TextBox` as its parameter, not the clipboard text.
- Clipboard text is split by `Environment.NewLine` but the resulting `lines` array is not passed to the command.
- **MultiSelectionBehavior:**
- Uses `_isUpdatingTarget` and `_isUpdatingSource` flags to prevent recursive update loops.
- Items are only added to `SelectedItems` if they pass `type.IsAssignableFrom(item.GetType())`.
- `SelectedItemsStatus.SetUpdating(SelectedItems, false)` is called before adding the last item in bulk additions.
---
## 4. Dependencies
### This module depends on:
- `System.Windows.Interactivity` — Base classes for behaviors (`Behavior<T>`, `TriggerBase`, `Interaction`)
- `System.Windows` — WPF core types (`DependencyObject`, `DependencyProperty`, `FrameworkElement`, `RoutedEventArgs`)
- `System.Windows.Controls``TextBox`, `ListBox`, `SelectionChangedEventArgs`
- `System.Windows.Input``ICommand`, `CommandManager`, `ApplicationCommands`, `ExecutedRoutedEventArgs`
- `DTS.Common.Controls``ChannelCodeBuilder`, `ChannelNameBuilder` (referenced in `TextBoxPasteBehavior`)
- `DTS.Common.Events``PageErrorEvent`, `PageErrorArg` (used for error publishing)
- `DTS.Common.Enums` — Referenced in `MultiSelectionBehavior` (likely contains `SelectedItemsStatus`)
- `DTS.Common.Utilities.Logging``APILogger.Log()` for exception logging
- `Microsoft.Practices.Prism.Events``IEventAggregator`
- `Microsoft.Practices.ServiceLocation``ServiceLocator`
### What depends on this module:
- Cannot be determined from source alone. Consumers would be XAML views or other modules applying these behaviors.
---
## 5. Gotchas
1. **StringMetaDataAttr constructor is internal:** You cannot instantiate this attribute programmatically; it must be applied declaratively at compile time.
2. **TextBoxPasteBehavior clipboard handling:** The clipboard text is retrieved and split into lines, but the `lines` array is never used—the command is executed with the `TextBox` as the parameter. The split operation appears to be dead code.
3. **TextBoxPasteBehavior null check bug:** In `CommandExecuted`, the line `if (null == sender && sender is ChannelCodeBuilder ccb)` is logically incorrect—it checks if `sender` is null AND is a specific type, which can never be true. This appears to be a copy-paste error; the intended check was likely `if (sender is ChannelCodeBuilder ccb)`.
4. **TextBoxPasteBehavior dependency on ServiceLocator:** Uses service locator pattern to resolve `IEventAggregator`, which is an anti-pattern and makes testing harder.
5. **MultiSelectionBehavior type checking:** Assumes `SelectedItems` is a generic `IList<T>` when accessing `GenericTypeArguments[0]`. Will throw `IndexOutOfRangeException` if bound to a non-generic `IList`.
6. **InteractivityItems.Triggers hides inherited member:** The `new` keyword on `Triggers` hides `FrameworkElement.Triggers`. This could cause confusion if the property is accessed via a `FrameworkElement` reference.
7. **MultiSelectionBehavior Reset handling:** When `NotifyCollectionChangedAction.Reset` is received, clears `AssociatedObject.SelectedItems` but does not re-populate from the source collection.

View File

@@ -0,0 +1,109 @@
---
source_files:
- Common/DTS.CommonCore/BusyIndicatorManager/xBusyIndicator.xaml.cs
- Common/DTS.CommonCore/BusyIndicatorManager/BusyIndicatorManager.cs
generated_at: "2026-04-16T11:56:30.835743+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "85046dce961f12c2"
---
# Documentation: DTS.Common.BusyIndicatorManager
## 1. Purpose
This module provides a centralized mechanism for managing busy indicator UI state across an application. It implements a singleton-based manager (`BusyIndicatorManager`) that tracks multiple concurrent busy operations by unique ID, allowing different parts of the application to show/hide busy indicators without conflicting with each other. The `xBusyIndicator` class serves as a WPF user control for displaying the busy indicator UI.
---
## 2. Public Interface
### `BusyIndicatorManager` (class)
**Inherits from:** `NotificationObject` (Microsoft.Practices.Prism.ViewModel)
#### Singleton Access
```csharp
public static BusyIndicatorManager Instance { get; }
```
Returns the singleton instance of `BusyIndicatorManager`. Thread-safe via lock synchronization on `SyncRoot`.
#### Properties
```csharp
public bool IsBusy { get; }
```
Indicates whether any busy operation is currently active. Read-only from external callers; set internally via `ShowBusy`/`CloseBusy`. Raises `PropertyChanged` notification.
```csharp
public string Message { get; }
```
The current message to display in the busy indicator. Read-only from external callers. Raises `PropertyChanged` notification.
#### Methods
```csharp
public void ShowBusy(int id, string busyMessage)
```
Registers a busy operation with the given `id` and displays `busyMessage`. If the `id` already exists, updates the message. Sets `IsBusy` to `true` and updates `Message`.
```csharp
public void CloseBusy(int id)
```
Removes the busy operation identified by `id`. If no busy operations remain, sets `IsBusy` to `false` and clears `Message`. If other operations remain, keeps `IsBusy` as `true` and sets `Message` to the last entry's value in `busyParameters`.
---
### `xBusyIndicator` (class)
**Inherits from:** Not explicitly shown; appears to be a WPF partial class (likely `UserControl`).
```csharp
public xBusyIndicator()
```
Default constructor that calls `InitializeComponent()`.
```csharp
public void Connect(int connectionId, object target)
```
Method present in the class but **implementation is empty**. Purpose unclear from source alone.
---
## 3. Invariants
- **Singleton guarantee:** Only one instance of `BusyIndicatorManager` can exist per process. Access is always through `BusyIndicatorManager.Instance`.
- **Thread-safe initialization:** The singleton is lazily initialized with lock-based synchronization.
- **ID uniqueness:** Each busy operation is identified by a unique `int` ID. Callers are responsible for ensuring IDs do not collide.
- **State consistency:** `IsBusy` is `true` if and only if `busyParameters.Count > 0`.
- **Message consistency:** When `IsBusy` is `false`, `Message` is an empty string. When `IsBusy` is `true`, `Message` reflects the most recently added/updated busy message.
- **Property change notifications:** `IsBusy` and `Message` raise `PropertyChanged` via `RaisePropertyChanged()` when modified.
---
## 4. Dependencies
### This module depends on:
- `Microsoft.Practices.Prism.ViewModel` — specifically `NotificationObject` for `INotifyPropertyChanged` implementation
- `System.Collections.Generic``Dictionary<TKey, TValue>`
- `System.Linq``Enumerable.Last()` extension method
- `System.Windows.Controls` — referenced in `xBusyIndicator`
- `Xceed.Wpf.Toolkit` — referenced in `xBusyIndicator` (likely provides the actual busy indicator control)
### What depends on this module:
- **Cannot be determined from source alone.** Consumers would bind to `BusyIndicatorManager.Instance.IsBusy` and `Message` properties, or instantiate `xBusyIndicator` in XAML views.
---
## 5. Gotchas
1. **`xBusyIndicator.Connect` is empty:** The method signature suggests it may be generated code (common in WPF for `IComponentConnector`), but the empty implementation has no documented purpose.
2. **Dictionary ordering assumption:** `CloseBusy` uses `busyParameters.Last().Value` to determine the next message to display. While .NET Framework 4.7+ and .NET Core preserve insertion order in `Dictionary`, this is not guaranteed by the interface contract. The "last" message may not be the most recently added in all runtime environments.
3. **No validation of `busyMessage`:** `ShowBusy` accepts any string, including `null` or empty strings, without validation.
4. **No exception handling for missing IDs in `CloseBusy`:** The method silently ignores calls to close non-existent IDs (it checks `ContainsKey` before removing).
5. **Message always updated on `ShowBusy`:** Even if an ID already exists with the same message, `Message` is reassigned and property change notification fires, which may trigger unnecessary UI updates.

View File

@@ -0,0 +1,306 @@
---
source_files:
- Common/DTS.CommonCore/Classes/StatusAndProgressBarEventArgs.cs
- Common/DTS.CommonCore/Classes/Singleton.cs
- Common/DTS.CommonCore/Classes/ImportData.cs
- Common/DTS.CommonCore/Classes/RegionNames.cs
- Common/DTS.CommonCore/Classes/ServiceCall.cs
- Common/DTS.CommonCore/Classes/TagAwareBase.cs
- Common/DTS.CommonCore/Classes/Utility.cs
- Common/DTS.CommonCore/Classes/Tags.cs
generated_at: "2026-04-16T11:58:55.221476+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "ab2980ca84007830"
---
# DTS.CommonCore/Classes Module Documentation
---
## 1. Purpose
This module provides foundational infrastructure classes for the DTS application, including a thread-safe singleton pattern implementation, a sequential service call queue, UI region name constants, tag management with database persistence, data transfer objects for import operations, and utility helpers for database reader type conversion. These classes serve as core building blocks used throughout the system for common patterns like status reporting, service coordination, and data import workflows.
---
## 2. Public Interface
### StatusAndProgressBarEventArgs
**Namespace:** `DTS.Common.Classes`
A POCO event argument class for status and progress bar updates.
| Property | Type | Description |
|----------|------|-------------|
| `StatusColor` | `Color` | The color to display for status text |
| `StatusText` | `string` | The status message text |
| `ProgressValue` | `double` | The progress bar value |
| `ProgressBarVisibility` | `Visibility` | Controls progress bar visibility |
| `Requester` | `IBaseViewModel` | Reference to the requesting view model |
| `ErrorText` | `string` | Error message text |
---
### Singleton\<T>
**Namespace:** `DTS.Common.Classes`
Generic singleton base class. Derive via `class MyClass : Singleton<MyClass>`.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Instance` | `public static T Instance { get; }` | Returns the singleton instance, lazily created |
| Constructor | `protected Singleton()` | Protected constructor that throws `InvalidOperationException` if instance already exists |
---
### ServiceCall
**Namespace:** `DTS.Common.Classes`
Represents a unit of work for the service queue.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Started` | `public bool Started { get; set; }` | Indicates if the call has started execution |
| `WorkAction` | `public Action WorkAction { get; set; }` | The action to execute |
| `Name` | `public string Name { get; set; }` | Identifier for the service call |
| `MarkDone` | `public void MarkDone()` | Marks the call as finished, triggering next item in queue |
| Constructor | `public ServiceCall(string name)` | Creates a named service call |
---
### ServiceQueue
**Namespace:** `DTS.Common.Classes`
Manages sequential execution of service calls.
| Member | Signature | Description |
|--------|-----------|-------------|
| `Enqueue` | `public static void Enqueue(ServiceCall call)` | Adds a service call to the queue; starts immediately if queue is empty |
| `MarkFinished` | `public static void MarkFinished(ServiceCall call)` | Removes completed call and starts next if available |
---
### RegionNames
**Namespace:** `DTS.Common.Classes`
Static class containing region name constants for UI composition (likely Prism regions).
**Constants include:**
- `FrontRegion`, `MainRegion`
- `ViewerEuRegion`, `ViewerMvRegion`, `ViewerEdcRegion`, `ViewerTestsRegion`
- `ViewerGraphRegion`, `ViewerGraphsRegion`, `ViewerGraphMainRegion`, `ViewerGraphListRegion`, `ViewerGraphChannelRegion`
- `ViewerTestModificationRegion`, `ViewerLegendRegion`, `ViewerSearchRegion`, `ViewerSettingsRegion`
- `ViewerDiagRegion`, `ViewerDisplayRegion`, `ViewerChartOptionsRegion`, `ViewerStatsRegion`, `ViewerCursorRegion`
- `ViewerFiterRegion` (note: typo preserved from source)
- `MenuRegion`, `NavigationRegion`, `BottomRegion`, `RightRegion`, `TopRegion`
- `VerticalTabRegion`, `HorizontalTabRegion`, `RibbonRegion`
- `PropertyDisplayRegion`, `PropertyModifyRegion`, `PropertyAddRegion`
- `PSDDataSelectRegion`, `PSDGraphRegion`
- `ReportChartOptionsRegion`, `ReportResultsRegion`
---
### ImportPageType
**Namespace:** `DTS.Common.Classes`
Enum defining import types.
| Value | Description |
|-------|-------------|
| `ImportSensor` | Sensor import operation |
| `ImportTestSetup` | Test setup import operation |
---
### SensorImportData
**Namespace:** `DTS.Common.Classes`
DTO for sensor import operations.
| Property | Type |
|----------|------|
| `GroupNameSensorListLookup` | `Dictionary<string, List<string>>` |
| `SensorGroupNameLookup` | `Dictionary<string, string>` |
| `SensorGroupTypeLookup` | `Dictionary<string, string>` |
| `GroupNameTestObjectLookup` | `Dictionary<string, string>` |
| `Errors` | `List<string>` (initialized to empty list) |
| `SensorISOCode` | `Dictionary<string, string>` |
| `SensorISOChannelName` | `Dictionary<string, string>` |
| `SensorUserCode` | `Dictionary<string, string>` |
| `SensorUserChannelName` | `Dictionary<string, string>` |
| `SensorDASSerialNumber` | `Dictionary<string, string>` |
| `SensorChannelIndex` | `Dictionary<string, int>` |
---
### TestSetupImportData
**Namespace:** `DTS.Common.Classes`
DTO for test setup import operations.
| Property | Type | Default |
|----------|------|---------|
| `Name` | `string` | — |
| `Description` | `string` | — |
| `SamplesPerSecond` | `double` | — |
| `PosttriggerSeconds` | `double` | — |
| `PretriggerSeconds` | `double` | — |
| `RecordingMode` | `RecordingModes` | — |
| `CalibrationBehavior` | `CalibrationBehaviors` | — |
| `Version` | `int` | — |
| `TestChannelOrders` | `List<string>` | — |
| `Tags` | `List<string>` | — |
| `ClockMasterInput` | `InputClockSource` | `InputClockSource.None` |
| `ClockMasterOutput` | `OutputClockSource` | `OutputClockSource.None` |
| `ManageClocksOutsideOfDataPROMaster` | `bool` | `false` |
| `ManageClocksOutsideOfDataPROSlave` | `bool` | `false` |
| `ClockSlaveInput` | `OutputClockSource` | `OutputClockSource.None` |
| `ClockSlaveOutput` | `OutputClockSource` | `OutputClockSource.None` |
| `SampleRateForDAS` | `Dictionary<string, int>` | empty dictionary (readonly) |
| `DomainIdForDAS` | `Dictionary<string, uint>` | empty dictionary (readonly) |
| `IsClockMaster` | `Dictionary<string, bool>` | empty dictionary (readonly) |
---
### TagAwareBase
**Namespace:** `DTS.Common.Classes`
Abstract base class for objects that support tagging.
| Member | Signature | Description |
|--------|-----------|-------------|
| `TagType` | `public abstract TagTypes TagType { get; }` | Abstract property defining tag type |
| `TagsBlobBytes` | `public byte[] TagsBlobBytes { get; set; }` | Serializes/deserializes TagIDs as byte array |
| `TagIDs` | `public int[] TagIDs { get; set; }` | Array of tag IDs; defaults to empty array |
| `SetTagsFromCommaSeparatedString` | `public void SetTagsFromCommaSeparatedString(string tagText, Tags.GetSqlCommandDelegate getSqlCommand)` | Parses comma-separated tags and sets them |
| `SetTags` | `public virtual void SetTags(string[] tagsText, Tags.GetSqlCommandDelegate getSqlCommand)` | Sets tags from string array |
| `GetTagsAsCommaSeparatedString` | `public string GetTagsAsCommaSeparatedString(Tags.GetSqlCommandDelegate getSqlCommand)` | Returns tags as comma-separated string |
| `GetTagsArray` | `public virtual string[] GetTagsArray(Tags.GetSqlCommandDelegate getSqlCommand)` | Returns tag text array from IDs |
| `GetTagIDs` | `public virtual int[] GetTagIDs()` | Returns TagIDs array |
| `RemoveTags` | `public virtual void RemoveTags(string[] tagsText)` | Removes tags (implementation incomplete in source) |
| `TagCompatible(string, delegate)` | `public bool TagCompatible(string tags, Tags.GetSqlCommandDelegate getSqlCommand)` | Checks if any tag in comma-separated string matches |
| `TagCompatible(int[])` | `public virtual bool TagCompatible(int[] tags)` | Checks for intersecting tag IDs |
| `HasIntersectingTag` | `public virtual bool HasIntersectingTag(int[] tags)` | Returns true if any tag ID intersects |
| `InsertTagsFromCommaSeparatedString` | `public void InsertTagsFromCommaSeparatedString(int id, TagTypes tagType, string tags, Tags.GetSqlCommandDelegate getSqlCommand)` | Sets and commits tags in one operation |
| `Commit` | `public void Commit(int id, TagTypes tagType, Tags.GetSqlCommandDelegate getSqlCommand)` | Persists tag assignments to database |
| `GetTagIdList` | `public List<int> GetTagIdList(int objectId, TagTypes tagType, Tags.GetSqlCommandDelegate getSqlCommand)` | Retrieves tag IDs for an object from database |
**Nested Enum: TagTypes**
| Value | Description |
|-------|-------------|
| `User` | User tag type |
| `Group` | Group tag type |
| `Template` | Template tag type |
| `TestSetup` | Test setup tag type |
| `Sensors` | Sensor tag type |
| `SensorModels` | Sensor model tag type |
---
### Tags
**Namespace:** `DTS.Common.Classes`
Manages tag persistence and caching.
| Member | Signature | Description |
|--------|-----------|-------------|
| `GetSqlCommandDelegate` | `public delegate SqlCommand GetSqlCommandDelegate(bool bNewConnection)` | Delegate for database command creation |
| `GetTagsInstance` | `public static Tags GetTagsInstance(GetSqlCommandDelegate getSqlCommand)` | Returns singleton instance |
| `AddTag` | `public static bool AddTag(string tagText, GetSqlCommandDelegate getSqlCommand)` | Adds tag if not present; returns true if added |
| `MigrateTag` | `public static bool MigrateTag(string tagText, GetSqlCommandDelegate getSqlCommand)` | Adds/updates tag during migration |
| `AddRange` | `public static bool[] AddRange(string[] tagText, GetSqlCommandDelegate getSqlCommand)` | Adds multiple tags; trims start whitespace |
| `GetIDFromTagText` | `public static int GetIDFromTagText(string tagText, GetSqlCommandDelegate getSqlCommand)` | Gets ID from database for tag text |
| `GetIDsFromTagText` | `public static int[] GetIDsFromTagText(string[] tagText, GetSqlCommandDelegate getSqlCommand)` | Converts tag text array to ID array |
| `GetTagTextFromID` | `public static string GetTagTextFromID(int tagID, GetSqlCommandDelegate getSqlCommand)` | Gets tag text from cached lookup |
| `GetTagTextFromIDs` | `public static string[] GetTagTextFromIDs(int[] tagId, GetSqlCommandDelegate getSqlCommand)` | Converts ID array to tag text array |
| `ContainsTag` | `public bool ContainsTag(string text)` | Checks if tag exists in cache |
| `UpdateList` | `public void UpdateList(GetSqlCommandDelegate getSqlCommand)` | Refreshes tag cache from database |
**Nested Class: Tags.Tag**
| Member | Signature | Description |
|--------|-----------|-------------|
| `INVALID_ID` | `public const int INVALID_ID = -1` | Constant for invalid tag ID |
| `ID` | `public int ID { get; set; }` | Tag identifier |
| `Text` | `public string Text { get; set; }` | Tag text |
| `IsObsolete` | `public bool IsObsolete { get; set; }` | Obsolescence flag |
| Constructor | `public Tag(string tagText, int tagId)` | Creates tag with text and ID |
| Constructor | `public Tag(Tag copy)` | Copy constructor |
| Constructor | `public Tag(IDataRecord reader)` | Creates tag from data reader |
| Constructor | `public Tag(DataRow dr)` | Creates tag from data row |
| `Clone` | `public object Clone()` | ICloneable implementation |
---
### Utility
**Namespace:** `DTS.Common.Classes`
Static utility class with helper methods.
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetBytesFromStringArray` | `public static byte[] GetBytesFromStringArray(string[] array, string separator)` | Joins array with separator and converts to UTF8 bytes |
| `GetAllErrorMessages` | `public static string GetAllErrorMessages(Exception ex)` | Returns all exception messages including inner exceptions |
| `PingNetwork` | `public static bool PingNetwork(string hostNameOrAddress)` | Pings host with 4-second timeout; returns success status |
| `GetUShort` | `public static ushort GetUShort(IDataReader reader, string column, ushort defaultValue = 0)` | Safely reads ushort from reader |
| `GetUInt` | `public static uint GetUInt(IDataReader reader, string column, uint defaultValue = 0)` | Safely reads uint from reader |
| `GetString` | `public static string GetString(IDataReader reader, string column, string defaultValue = "")` | Safely reads string from reader |
| `GetStringArray` | `public static string[] GetStringArray(IDataReader reader, string column, string[] defaultValue, string separator)` | Reads byte array from reader, decodes to UTF8, splits by separator |
| `GetInt` | `public static int GetInt(IDataReader reader, string column, int defaultValue = 0)` | Safely reads int from reader |
| `GetDouble` | `public static double GetDouble(IDataReader reader, string column, double defaultValue = 0D)` | Safely reads double from reader |
| `GetShort` | `public static short GetShort(IDataReader reader, string column, short defaultValue = 0)` | Safely reads short from reader |
| `GetNullableDateTime` | `public static DateTime? GetNullableDateTime(IDataReader reader, string column)` | Reads nullable DateTime from reader |
| `GetUlong` | `public static ulong GetUlong(IDataReader reader, string column, ulong defaultValue = 0)` | Safely reads ulong from reader |
| `GetNullableInt` | `public static int? GetNullableInt(IDataReader reader, string column)` | Reads nullable int from reader |
| `GetByteArray` | `public static byte[] GetByteArray(IDataReader reader, string column)` | Reads byte array; returns empty array for null/DBNull |
| `GetBool` | `public static bool GetBool(IDataReader reader, string column, bool defaultValue = false)` | Safely reads bool from reader |
| `GetDateTime` | `public static DateTime GetDateTime(IDataReader reader, string column, DateTime defaultValue)` | Safely reads DateTime from reader |
| `GetLong` | `public static long GetLong(IDataReader reader, string column, long defaultValue = 0)` | Safely reads long from reader |
---
## 3. Invariants
### Singleton\<T>
- The generic type `T` must have a public parameterless constructor (`where T : new()`).
- `Instance` will always return the same object reference after first creation.
- Calling `new T()` directly after `Instance` has been accessed will throw `InvalidOperationException`.
- If the singleton constructor throws, the exception is captured and re-thrown on subsequent `Instance` access.
### ServiceQueue
- Work items execute sequentially, never concurrently.
- Only the first item in the queue is ever marked as `Started = true`.
- `MarkFinished` must be called by the `WorkAction` to advance the queue.
- Queue operations are thread-safe via `QueueLock`.
### Tags
- `Tag.INVALID_ID` is `-1`.
- Tag IDs of `0` are skipped during cache population.
- Tag text is trimmed of leading whitespace before database operations in `AddRange`.
- The `_tagsLookup` dictionary is keyed by tag text, not ID.
### TagAwareBase
- `TagIDs` is never null; it defaults to an empty array.
- `TagsBlobBytes` format: 4 bytes per int (sizeof(int)), using `Buffer.BlockCopy`.
### Utility
- All `IDataReader` helper methods handle `DBNull.Value` and return default values.
- `GetByteArray` returns an empty array (not null) for null/DBNull columns.
- `PingNetwork` timeout is fixed at 4444ms.
---
## 4. Dependencies
### External Dependencies (Imports)
| Module | Dependencies |
|--------|--------------|
| StatusAndProgressBarEventArgs | `System.Windows`, `System.Windows.Media`, `DTS.Common.Base` (IBaseViewModel) |
| Singleton\<T> | `System` |
| ImportData | `DTS.Common.Enums`, `DTS.Common.Enums.Sensors`, `DTS.Common.Interface.Sensors`, `System`, `System.Collections.Generic` |
| RegionNames | None |
| ServiceCall | `DTS.Common.Utilities.Logging`, `System`, `System.Collections.Generic`, `System.Linq`, `System.Threading.Tasks` |
| TagAwareBase | `System`, `System.Collections.Generic`, `System.Data`, `System.Data.SqlClient`, `System.Linq`, `System.Text`, `DTS.Common.Utilities.Logging` |
| Tags | `System`, `System.Collections.Generic`, `System.Data`, `System.Data.SqlClient`, `System.Linq`, `DTS.Common.Utilities.Logging` |
| Utility | `System`, `System.Text`, `System.Net.NetworkInformation`, `System.Data`, `DTS.Common.Utilities.Logging`, `System

View File

@@ -0,0 +1,233 @@
---
source_files:
- Common/DTS.CommonCore/Constant/XamlConstants.xaml.cs
- Common/DTS.CommonCore/Constant/DigitalInputs.cs
- Common/DTS.CommonCore/Constant/EmbeddedSensors.cs
- Common/DTS.CommonCore/Constant/Constants.cs
generated_at: "2026-04-16T12:03:56.985206+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "02cf11f3a90b1f89"
---
# Documentation: DTS.Common.Constant
## 1. Purpose
This module provides a centralized collection of application-wide constants and configuration values for the DTS (Data Translation System) software. It defines hardware thresholds for digital inputs, sensor range limits and sample rates for embedded devices, graph display parameters, streaming configuration limits, clock synchronization profiles, recording mode definitions, NMEA parsing constants, and database version markers. These constants ensure consistent behavior across the system and serve as the single source of truth for hardware-specific magic numbers, validation boundaries, and default values.
---
## 2. Public Interface
### `DTS.Common.Constant.XamlConstants` (partial class)
- **Signature:** `public partial class XamlConstants`
- **Behavior:** Empty partial class intended as code-behind for XAML resource definitions. No members defined in source.
---
### `DTS.Common.Constant.DigitalInputs` (static class)
| Member | Signature | Description |
|--------|-----------|-------------|
| `ConstantCurrentBreakPointDefault` | `public const double` | Default breakpoint value (19005.0) for contact closure detection. "Magic number from CPB." |
| `VoltageInputBreakPointDefault` | `public const double` | Default breakpoint value (19661.0) for voltage input modes THL and TLH (1.5V with sig- grounded). |
| `DisplaySPDADCDefault` | `public const bool` | Default display setting for SLICE PRO Digital ADC (false). |
| `ConstantCurrentBreakPoint` | `public static double { get; set; }` | Runtime value for constant current breakpoint. Initialized to `ConstantCurrentBreakPointDefault`. Does NOT query storage; relies on external initialization. |
| `VoltageInputBreakPoint` | `public static double { get; set; }` | Runtime value for voltage input breakpoint. Initialized to `VoltageInputBreakPointDefault`. Does NOT query storage. |
| `DisplaySPDADC` | `public static bool { get; set; }` | Runtime control for displaying SLICE Pro Digital analog ADC. Initialized to `DisplaySPDADCDefault`. Does NOT query storage. |
---
### `DTS.Common.Constant.EmbeddedSensors` (static class)
**Power Management / Wake Up:**
| Member | Value | Description |
|--------|-------|-------------|
| `MotionDetectInactivitySMaximum` | 300 | Maximum motion detect inactivity timeout (5 minutes). |
| `MagnetTimeoutMsMaximum` | 300000 | Maximum magnet timeout in milliseconds (5 minutes). |
**Device Trigger Ranges:**
| Member | Value | Description |
|--------|-------|-------------|
| `EmbeddedLowGLinearAccelerometerRange` | 8 | Low-G linear accelerometer range. |
| `EmbeddedHighGLinearAccelerometerRange` | 400 | High-G linear accelerometer range. |
| `EmbeddedAngularAccelerometerRange` | 2000 | Angular accelerometer range. |
| `EmbeddedAngularRateSensorRange` | 2000 | Angular rate sensor range. |
| `HumidityMinimum` / `HumidityMaximum` | 10 / 100 | Humidity valid range. |
| `PressureMinimum` / `PressureMaximum` | 5 / 15 | Pressure valid range. |
| `TemperatureMinimum` / `TemperatureMaximum` | 0 / 65 | Temperature valid range (°C). |
| `TimedIntervalEventDurationMsMinimum` / `Maximum` | 30 / 300000 | Timed interval event duration range. |
| `TimedIntervalNumberOfEventsMaximum` | 100 | Maximum number of timed interval events. |
| `IntervalBetweenEventStartsMinutesMaximum` | 1440 | Maximum interval between event starts (24 hours). |
**Sample Rate Limits (Hz):**
| Sensor | Minimum | Maximum | Default |
|--------|---------|---------|---------|
| Low-G Linear Accelerometer | 1 | 6400 | 6400 |
| High-G Linear Accelerometer | 1 | 5120 | 5120 |
| Angular Accelerometer | 1 | 1600 | 1600 |
| Angular Accelerometer & Rate Sensor | 1 | 5120 | 5120 |
| Atmospheric Sensor | 1 | 157 | 157 |
---
### `DTS.Common.Constants` (static class)
**String Constants:**
| Member | Value | Description |
|--------|-------|-------------|
| `ROI_TAG` | "ROI" | Region of interest tag. |
| `ALL_TAG` | "ALL" | All-encompassing tag. |
| `DAS_TEST_SETUPS` | "DASTestSetup" | DAS test setup identifier. |
| `USB` | "USB" | USB connection identifier. |
| `BACKUP_HEADER_EXTENSION` | ".header.bak" | Backup header file extension. |
| `BACKUP_FILE_EXTENSION` | ".bak" | Backup file extension. |
| `DAS_CONFIGS` | "DASConfigs" | DAS configuration directory name. |
| `TEMP_FILE_EXTENSION` | ".tmp" | Temporary file extension. |
| `UDP_STREAM_CH10_TF2` | "2HDR" | UDP streaming Chapter 10 tag. |
| `EventNumber` | "_Event Number" | Event number identifier. |
| `UseMeasuredExcitation` | "UseMeasuredExcitation" | Measured excitation flag. |
| `ManualsFolder` | "Manuals" | Manuals directory name. |
| `WindowsExplorer` | "explorer.exe" | Windows Explorer executable. |
| `NoValue` | "NOVALUE" | No-value placeholder. |
| `ISO_CH_ONLY_PREFIX` | "__ISO_CH_ONLY__" | ISO channel-only prefix. |
| `DUMMY_MOD_DESCRIP_S6DB` | "slice6db module" | Dummy module description. |
| `DUMMY_MOD_DESCRIP_POWERPRO` | "powerpro module" | Dummy module description. |
| `ISOTestInfo` | "_" | ISO test info marker. |
| `NMEA_GPRMC_HEADER` | "$GPRMC" | NMEA RMC sentence header. |
| `NMEA_GPGGA_HEADER` | "$GPGGA" | NMEA GGA sentence header. |
**Graph & Display Constants:**
| Member | Value | Description |
|--------|-------|-------------|
| `MINIMUM_VOLTAGE_INSERTION_RANGE_MV_SLICE` | 10 | Minimum voltage insertion range for SLICE (mV). |
| `GRAPH_MIN_AUTOZOOM` | 0.01D | Minimum auto-zoom as % of full scale (capacity). |
| `GRAPH_MAX_AUTOZOOM` | 1.2D | Maximum auto-zoom as % of full scale (signal). |
| `MAX_VIEWER_POINTS` | 45000000 | Maximum points for a Viewer graph. |
**Runtime-Configurable Properties:**
| Member | Default | Description |
|--------|---------|-------------|
| `CheckStatusLinesInRealtime` | true | Whether to check status lines during realtime polling. |
| `UpdateIntervalRealtimeCharts` | 100 | Sleep time (ms) between chart updates. |
| `PING_ICMP_TIMEOUT` | 500 | Max time (ms) to wait for individual ping attempt. |
**Hardware & Streaming Constants:**
| Member | Value | Description |
|--------|-------|-------------|
| `XML_HEADER_LENGTH` | 8 | XML header length in bytes. |
| `XML_STORE_MAGIC_BYTES` | `{0xAA, 0x55, 0xA5, 0x5A}` | Magic bytes for XML storage. |
| `FILE_STORE_DSP_FILTER_ID` | 104 | DSP filter ID for file storage. |
| `DEVICE_STREAMING_ONLY` | 1 | Device streaming-only flag. |
| `TDAS_TOM_DIGITAL_OUT_DURATION_MAX` | 1600 | Maximum TDAS Tom digital out duration. |
| `BITS_PER_MINOR_FRAME_S6A` | 128 | Bits per minor frame for SLICE6AIR. |
| `BITS_PER_MINOR_FRAME_TSRAIR` | 320 | Bits per minor frame for TSR AIR. |
| `ADC_MIDPOINT` | 32767 | ADC midpoint (16-bit DAC, 2^15 - 1). |
| `SLICE2_NO_AAF_REALTIME_RATE` | 100000F | AAF realtime rate when disabled via config. |
| `UDP_STREAMPROFILES_MAX` | 15 | Maximum UDP stream profiles. |
| `UART_MODE_MAX_SAMPLERATE` | 30000 | Maximum sample rate in UART recording modes. |
| `SLICE6AIR_STREAMING_DIGITAL_FILTERING_MAX_SAMPLERATE` | 10000 | Max sample rate for digital filtering. |
| `SLICE6AIR_STREAMING_DIGITAL_FILTERING_MAX_SAMPLERATE_20k` | 20000 | Extended max sample rate for digital filtering. |
| `SLICE6AIR_20K_DIGITAL_FILTER_MIN_PROTOCOL` | 46 | Minimum protocol version for 20k digital filter. |
| `MaxAAFilterRateHz` | 200000 | Maximum AA filter rate. |
| `NANOS_PER_SECOND` | 1000000000m | Nanoseconds per second. |
| `TEN_MILLIS_IN_SEC` | 0.01D | Ten milliseconds in seconds. |
| `EXECUTABLE_TIMEOUT` | 30000 | Wait timeout for 3rd party executables (ms). |
**Clock Synchronization Profiles:**
| Member | Type | Description |
|--------|------|-------------|
| `MasterProfiles` | `readonly ClockSyncProfile[]` | Valid clock master profile selections (14 profiles). |
| `SlaveProfiles` | `readonly ClockSyncProfile[]` | Valid clock slave profile selections (4 profiles). |
| `OnePPSOutProfiles` | `readonly ClockSyncProfile[]` | Profiles supporting 1PPS output (13 profiles). |
**Recording Modes:**
| Member | Type | Description |
|--------|------|-------------|
| `NonStreamingRecordingModes` | `readonly RecordingModes[]` | Non-streaming recording mode selections (15 modes). |
**NMEA Parsing Constants:**
| Member | Value | Description |
|--------|-------|-------------|
| `NMEA_GPRMC_TIME_POSN` | 1 | Position of time in GPRMC sentence. |
| `NMEA_GPRMC_VALID_POSN` | 2 | Position of validity flag in GPRMC. |
| `NMEA_GPRMC_LAT_POSN` / `LAT_LEN` / `LATD_POSN` | 3 / 9 / 4 | Latitude position, length, and direction. |
| `NMEA_GPRMC_LONG_POSN` / `LONG_LEN` / `LONGD_POSN` | 5 / 10 / 6 | Longitude position, length, and direction. |
| `NMEA_GPRMC_VELO_POSN` / `DIR_POSN` / `DATE_POSN` | 7 / 8 / 9 | Velocity, direction, and date positions. |
| `NMEA_GPGGA_TIME_POSN` / `VALID_POSN` / `ALT_POSN` / `ALTU_POSN` | 1 / 6 / 9 / 10 | GPGGA time, validity, altitude, and altitude unit positions. |
**Database Version Markers:**
| Member | Value | Description |
|--------|-------|-------------|
| `ROITables_DB_VERSION` | 92 | ROI tables feature version. |
| `EnableRepeat_DB_VERSION` | 92 | Enable repeat feature version. |
| `IgnoreShorted_DB_VERSION` | 92 | Ignore shorted feature version. |
| `ONEPPS_OUT_DB_VERSION` | 92 | 1PPS out feature version. |
| `UNIX_EPOCH_TIME` | 93 | Unix epoch time feature version. |
| `TMATS_INTERVAL_VERSION` | 93 | TMATS interval UI support version. |
| `ALLOWED_DOWNLOAD_FILE_LENGTH` | 260 | Maximum Windows file name length. |
| `ALLOWED_DOWNLOAD_DIRECTORY_LENGTH` | 248 | Maximum Windows directory name length. |
| `ADC_TO_UART_DB_VERSION` | 93 | ADC to UART feature version. |
| `SLICE6AIR_BR_DB_VERSION` | 95 | SLICE6AIR BR feature version. |
| `PTP_DOMAIN_ID_DB_VERSION` | 95 | PTP domain ID feature version. |
| `BULK_GROUPCHANNELSETTINGS_GET_DB_VERSION` | 95 | Bulk group channel settings version. |
| `MULTIPLE_EVENT_UART_DB_VERSION` | 96 | Multiple-event UART support version. |
| `RECORD_ON_BOOT_VERSION` | 96 | Record on boot feature version. |
**Other:**
| Member | Type | Description |
|--------|------|-------------|
| `ExportNameFilters` | `readonly Dictionary<string, string>` | Name sanitization for exports (maps "(Voltage)" → "Voltage", "(Current)" → "Current"). |
| `PSD_DEFAULT_MAX_POW10` / `MIN_POW10` | 0 / -12 | PSD default power-of-10 bounds. |
---
## 3. Invariants
1. **Digital Input Breakpoints:** `ConstantCurrentBreakPoint` and `VoltageInputBreakPoint` must be set externally before use; they do not auto-initialize from persistent storage.
2. **Sample Rate Defaults:** All default sample rates in `EmbeddedSensors` are set to their respective maximum values.
3. **Clock Sync Profile Arrays:** `MasterProfiles`, `SlaveProfiles`, and `OnePPSOutProfiles` are `readonly` and cannot be modified at runtime.
4. **Database Version Ordering:** Version numbers are monotonically increasing (92 → 93 → 95 → 96). Note: Version 94 is not present in the defined constants.
5. **NMEA Position Indices:** Position constants are 1-indexed (based on NMEA sentence structure), not 0-indexed.
6. **ADC Midpoint:** Fixed at 32767 (2^15 - 1) for 16-bit DACs; this is a hardware constraint.
7. **Windows Path Limits:** `ALLOWED_DOWNLOAD_FILE_LENGTH` (260) and `ALLOWED_DOWNLOAD_DIRECTORY_LENGTH` (248) reflect Windows API limitations.
---
## 4. Dependencies
**This module depends on:**
- `DTS.Common.Enums` — for `ClockSyncProfile` and `RecordingModes` enum types (imported in `Constants.cs`)
**What depends on this module:**
- Unclear from source alone. Given the central nature of these constants, likely consumed by:
- Device communication/hardware abstraction layers
- Data acquisition and streaming components
- UI components (graph rendering, configuration dialogs)
- Export/import functionality
- Database migration logic
---
## 5. Gotchas
1. **Static Properties Without Storage Persistence:** The properties `ConstantCurrentBreakPoint`, `VoltageInputBreakPoint`, and `DisplaySPDADC` in `DigitalInputs` are explicitly documented as NOT querying values from storage. They rely on being set separately, which could lead to uninitialized or stale values if the initialization sequence is not properly managed.
2. **Magic Numbers Without Clear Origin:** `ConstantCurrentBreakPointDefault` (19005) is documented as a "magic number from CPB" with no explanation of its derivation. The voltage breakpoint (19661) corresponds to "1.5V with sig- grounded" but the conversion formula is not documented.
3. **Commented-Out Clock Sync Profiles:** Several profiles in `MasterProfiles`, `SlaveProfiles`, and `OnePPSOutProfiles` are commented out with notes like "Combinations that are possible in UI, but no device supports." This suggests potential UI/backend mismatch if these values are used elsewhere.
4. **Missing Database Version 94:** The version constants jump from 93 to 95 with no version 94 defined. The significance of this gap is unclear from source.
5. **Hardcoded Internal URLs:** Comments reference internal URLs (e.g., `http://manuscript.dts.local/f/cases/...`) which may be inaccessible outside the development environment.
6. **Mixed Naming Conventions:** Some constants use SCREAMING_SNAKE_CASE (e.g., `ROI_TAG`), others use PascalCase (e.g., `NanosecondsPerSecond` would be expected, but actual is `NANOS_PER_SECOND`). This inconsistency may cause confusion.
7. **Graph Auto-Zoom Units:** `GRAPH_MIN_AUTOZOOM` and `GRAPH_MAX_AUTOZOOM` have different semantic bases—one references "capacity" full scale, the other "signal" full scale. The distinction is subtle and could lead to misuse.

View File

@@ -0,0 +1,343 @@
---
source_files:
- Common/DTS.CommonCore/Controls/RoundedBox.xaml.cs
- Common/DTS.CommonCore/Controls/TestIDView.xaml.cs
- Common/DTS.CommonCore/Controls/checkbox.xaml.cs
- Common/DTS.CommonCore/Controls/GridLengthAnimation.cs
- Common/DTS.CommonCore/Controls/ISOPopup.xaml.cs
- Common/DTS.CommonCore/Controls/LookupPopup.xaml.cs
- Common/DTS.CommonCore/Controls/TestIdPreFixSuffixHelper.cs
- Common/DTS.CommonCore/Controls/AutoSizedGridView.cs
- Common/DTS.CommonCore/Controls/DynamicGrid.cs
- Common/DTS.CommonCore/Controls/TestIDViewModel.cs
- Common/DTS.CommonCore/Controls/TestIDControl.xaml.cs
- Common/DTS.CommonCore/Controls/GridViewColumnHeaderSelectable.xaml.cs
- Common/DTS.CommonCore/Controls/GridViewColumnHeaderSearchable.xaml.cs
- Common/DTS.CommonCore/Controls/GridViewColumnHeaderSearchableCheckBox.xaml.cs
generated_at: "2026-04-16T12:02:29.779799+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "1aa96c65b3ed084a"
---
# DTS.Common.Controls Documentation
## 1. Purpose
This module provides a collection of custom WPF controls and helpers for the DTS application. It includes specialized controls for test ID generation and display, animated grid layouts, popup-based lookup and ISO input validation, and enhanced GridView column headers with search, selection, and filtering capabilities. The controls integrate with the Prism EventAggregator for cross-component communication and support data binding through dependency properties and `INotifyPropertyChanged`.
---
## 2. Public Interface
### RoundedBox
```csharp
public partial class RoundedBox : UserControl
public RoundedBox() // Constructor
public void Connect(int connectionId, object target) // Stub method (implementation commented out)
```
A simple UserControl. The `Connect` method is defined but its implementation is commented out.
---
### TestIDView
```csharp
public partial class TestIDView : UserControl
public TestIDView() // Constructor
```
A simple UserControl with no additional public members beyond the constructor.
---
### checkbox
```csharp
public partial class checkbox
public void ToolTipEventHandler(object sender, ToolTipEventArgs e)
```
Handles tooltip events by publishing a `HelpTextEvent` via the `IEventAggregator`. Sets `e.Handled = true` and forwards the event arguments to subscribers.
---
### GridLengthAnimation
```csharp
public class GridLengthAnimation : AnimationTimeline
public GridLengthAnimation() // Constructor
public GridLength From { get; set; } // Dependency property
public static readonly DependencyProperty FromProperty
public GridLength To { get; set; } // Dependency property
public static readonly DependencyProperty ToProperty
public override Type TargetPropertyType // Returns typeof(GridLength)
public override object GetCurrentValue(object defaultOriginValue, object defaultDestinationValue, AnimationClock animationClock)
protected override Freezable CreateInstanceCore() // Returns new GridLengthAnimation()
```
Custom animation timeline for animating `GridLength` values. Supports both pixel and star-based grid units, preserving the `GridUnitType` from the `To` property.
---
### ISOPopup
```csharp
public partial class ISOPopup : Popup
public ISOPopup() // Constructor
// Private event handlers (wired via XAML):
private void ISOPart_OnPreviewKeyUp(object sender, KeyEventArgs e) // Filters input to alphanumeric and control keys only
private void ISOPart_OnGotMouseCapture(object sender, MouseEventArgs e) // Selects all text in TextBox
private void ISOPart_OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) // Selects all text in TextBox
```
A Popup control that restricts input to letters (A-Z), digits (0-9, NumPad0-9), and control keys (Enter, Tab, Delete, Back, Home, End, OemQuestion, OemBackTab).
---
### LookupPopup
```csharp
public partial class LookupPopup : Popup
public LookupPopup() // Constructor
public IEnumerable<IChannelCode> AllChannelCodes { get; private set; }
public delegate void ChannelCodeSelectedEventHandler(object sender, string code, string name);
public event ChannelCodeSelectedEventHandler ChannelCodeSelected
public static readonly DependencyProperty PossibleChannelsProperty
public IList PossibleChannels { get; set; } // Default: empty list with anonymous objects
// Private event handlers:
private void LookupPopup_OnOpenedClosed(object sender, EventArgs e) // Commented-out implementation
private void PossibleChannels_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) // Raises ChannelCodeSelected
```
A Popup for selecting channel codes from a DataGrid. Uses reflection to extract `Code` and `Name` properties from items.
---
### TestIdPreFixSuffixHelper & Related Classes
```csharp
public enum TestIdFixedPrefixSuffixValues
{
NotFixed = -1,
None = 0,
TimeStamp = 1,
TestSetupName = 2
}
public class TestIdPreFixSuffix
public TestIdPreFixSuffix(TestIdFixedPrefixSuffixValues fixedPrefixSuffix)
public TestIdPreFixSuffix(string dbPrefixSuffix)
public TestIdFixedPrefixSuffixValues FixedValue { get; } // Default: NotFixed
public override string ToString() // Returns "TESTID_PREFIX_SUFFIX_{value}" or the db string
public class TestIdPreFixSuffixHelper : BasePropertyChanged
public TestIdPreFixSuffixHelper(string testIdPreFixSuffix)
public TestIdPreFixSuffixHelper(TestIdFixedPrefixSuffixValues testIdPreFixSuffix)
public TestIdPreFixSuffix TestIdPreFixSuffix { get; }
public override string ToString() // Looks up localized string via ResourceManager
public override bool Equals(object obj)
```
Helper classes for managing test ID prefix/suffix values with support for both fixed enumerated values and database-defined strings.
---
### AutoSizedGridView
```csharp
public class AutoSizedGridView : GridView
protected override void PrepareItem(ListViewItem item)
```
A GridView that automatically resizes columns marked with `Width="Auto"` and restores lost width bindings. Tracks columns via hash codes.
---
### DynamicGrid
```csharp
public class DynamicGrid : Grid, INotifyPropertyChanged
public DynamicGrid() // Constructor, calls Refresh()
public byte GridColumns { get; set; } // Default: 2
public void Refresh()
// INotifyPropertyChanged implementation:
public event PropertyChangedEventHandler PropertyChanged
protected bool SetProperty<T>(ref T storage, T value, string propertyName = null)
protected void OnPropertyChanged(string propertyName = null)
```
A Grid that automatically arranges children in a configurable number of columns. All columns except the last use `Auto` width; the last uses `Star`. Adds a final `Star`-height row at the bottom.
---
### TestIDViewModel
```csharp
public class TestIDViewModel : INotifyPropertyChanged
public string TestSetupLabel { get; set; } // Default: string.Empty
public Visibility TestSetupLabelVisibility { get; } // Collapsed if label is empty
public string TestIdEditableText { get; set; } // Default: string.Empty
public string TestName { get; set; }
public void PopulateAllTestIdPrefixSuffixValues(string[] serializedValues)
public TestIdPreFixSuffixHelper[] AllTestIdPrefixSuffixValues { get; }
public TestIdPreFixSuffixHelper SelectedTestIdPrefixValueItem { get; set; } // Default: None
public TestIdPreFixSuffixHelper SelectedTestIdSuffixValueItem { get; set; } // Default: TimeStamp
public string GetTestId()
public string GetTestIdTimestamp() // Format: "YYYY_MM_DD HH_MM"
```
ViewModel for constructing test IDs from prefix, label, editable text, and suffix components.
---
### TestIdControl
```csharp
public partial class TestIdControl : UserControl, INotifyPropertyChanged
public TestIdControl() // Constructor
// Same public interface as TestIDViewModel:
public string TestSetupLabel { get; set; }
public Visibility TestSetupLabelVisibility { get; }
public string TestIdEditableText { get; set; }
public string TestName { get; set; }
public void PopulateAllTestIdPrefixSuffixValues(string[] serializedValues)
public TestIdPreFixSuffixHelper[] AllTestIdPrefixSuffixValues { get; }
public TestIdPreFixSuffixHelper SelectedTestIdPrefixValueItem { get; set; }
public TestIdPreFixSuffixHelper SelectedTestIdSuffixValueItem { get; set; }
public string GetTestId()
public string GetTestIdTimestamp()
```
**Note:** Comment indicates this control should be removed after TTS module deletion and migration to new test setup wizard.
---
### GridViewColumnHeaderSelectable
```csharp
public partial class GridViewColumnHeaderSelectable : UserControl, IBasePropertyChanged
public GridViewColumnHeaderSelectable() // Constructor, subscribes to ListViewStatusEvent
public string ListviewId { get; set; } // Dependency property, default: ""
public string HeaderTitle { get; set; } // Dependency property, default: "Awesome"
public bool ToggleButtonIsChecked { get; set; } // Default: false
// Routed events:
public static readonly RoutedEvent OpenChangedEvent
public event RoutedEventHandler OpenChanged
public static readonly RoutedEvent ClickEvent
public event RoutedEventHandler ClickHandler
public static readonly RoutedEvent SelectAllEvent
public event RoutedEventHandler SelectAll
```
A column header with a toggle button popup for selection. Raises `OpenChanged`, `ClickHandler`, and `SelectAll` routed events.
---
### GridViewColumnHeaderSearchable
```csharp
public partial class GridViewColumnHeaderSearchable : UserControl, IBasePropertyChanged
public GridViewColumnHeaderSearchable() // Constructor, subscribes to ListViewStatusEvent
public string ListviewId { get; set; } // Dependency property
public string HeaderTitle { get; set; } // Dependency property, default: "Awesome"
public bool ToggleButtonIsChecked { get; set; }
public string HeaderSearchTerm { get; set; } // Dependency property, default: ""
public Geometry ToggleIconGeometry { get; } // Returns DownArrowIconGeometry or FilterIconGeometry
// Routed events:
public static readonly RoutedEvent OpenChangedEvent
public event RoutedEventHandler OpenChanged
public static readonly RoutedEvent ClickEvent
public event RoutedEventHandler ClickHandler
public static readonly RoutedEvent SearchEvent
public event RoutedEventHandler Search
// Converter:
public class BoolToInvertedBoolConverter : IValueConverter
```
A searchable column header with a popup. Displays different icons based on whether a search term is active.
---
### GridViewColumnHeaderSearchableCheckBox
```csharp
public partial class GridViewColumnHeaderSearchableCheckBox : UserControl, IBasePropertyChanged
public GridViewColumnHeaderSearchableCheckBox() // Constructor, subscribes to ListViewStatusEvent
public string ListviewId { get; set; } // Dependency property
public string HeaderTitle { get; set; } // Dependency property, default: "Awesome"
public bool ToggleButtonIsChecked { get; set; }
public string HeaderSearchTerm { get; set; } // Dependency property
public Geometry ToggleIconGeometry { get; }
// Routed events:
public static readonly RoutedEvent OpenChangedEvent
public event RoutedEventHandler OpenChanged
public static readonly RoutedEvent ClickEvent
public event RoutedEventHandler ClickHandler
public static readonly RoutedEvent SearchEvent
public event RoutedEventHandler Search
public static readonly RoutedEvent FilterEvent
public event RoutedEventHandler Filter // Raised with "All", "True", or "False"
```
A column header combining search and boolean filtering with All/True/False buttons.
---
## 3. Invariants
- **GridLengthAnimation**: The `GridUnitType` (Star or Pixel) is always taken from the `To` property, not `From`.
- **ISOPopup**: Input is restricted to alphanumeric characters and specific control keys; all other keys set `e.Handled = true`.
- **DynamicGrid**: The last column always has `GridUnitType.Star`; all others have `GridUnitType.Auto`. A final row with `Star` height is always appended.
- **AutoSizedGridView**: Column tracking uses `GetHashCode()`; if column collection changes, internal caches are rebuilt.
- **LookupPopup**: Items in `PossibleChannels` must have `Code` and `Name` properties accessible via reflection.
- **TestIdPreFixSuffixHelper.Equals**: Two helpers are equal if they have the same `FixedValue` (when not `NotFixed`), or if both are `NotFixed` and their string representations match.
- **TestIDViewModel/TestIdControl**: `GetTestId()` joins non-empty components with underscores in order: prefix → TestSetupLabel → TestIdEditableText → suffix.
- **GridViewColumnHeader* controls**: All subscribe to `ListViewStatusEvent` and clear state when receiving `Unloaded` status matching their `ListviewId`.
---
## 4. Dependencies
### This module depends on:
- `System.Windows` (WPF core)
- `System.Windows.Controls`
- `System.Windows.Controls.Primitives`
- `System.Windows.Data`
- `System.Windows.Input`
- `System.Windows.Media.Animation`
- `Microsoft.Practices.ServiceLocation` (ServiceLocator)
- `Microsoft.Practices.Prism.Events` (IEventAggregator, ThreadOption)
- `DTS.Common.Base` (BasePropertyChanged, IBasePropertyChanged)
- `DTS.Common.Events` (HelpTextEvent, HelpTextEventArg, ListViewStatusEvent, ListViewStatusArg)
- `DTS.Common.Interface.Channels.ChannelCodes` (IChannelCode)
- `DTS.Common.Utilities.Logging` (imported but usage not visible in provided source)
- `DTS.Strings.Strings` (ResourceManager for localization)
### What depends on this module:
- Cannot be determined from source alone; these are UI controls likely used by various modules throughout the DTS application.
---
## 5. Gotchas
1. **TestIdControl is deprecated**: The source explicitly states "Remove this control after deleting the TTS module and migrating to new test setup wizard." New code should use `TestIDViewModel` instead.
2. **LookupPopup uses reflection**: `PossibleChannels_OnMouseDoubleClick` uses `GetProperty("Code")` and `GetProperty("Name")` via reflection on anonymous-type-like objects. This is fragile and will fail silently (returning null) if properties don't exist.
3. **RoundedBox.Connect is a stub**: The method throws `NotImplementedException` (commented out). Its purpose is unclear from source.
4. **GridViewColumnHeaderSelectable.OnListviewStatusEvent has empty body**: When `arg.Id == ListviewId`, there's no actual logic executed—just an empty if block.
5. **AutoSizedGridView uses hash codes for column identity**: Column tracking relies on `GetHashCode()`, which could theoretically collide (though unlikely in practice).
6. **checkbox class lacks constructor**: The partial class `checkbox` has no constructor shown; `InitializeComponent()` must be called from the XAML-generated part.
7. **BoolToInvertedBoolConverter.ConvertBack throws**: The `ConvertBack` method throws `NotImplementedException`, making it unsuitable for two-way bindings.
8. **GridLengthAnimation doesn't validate animationClock.CurrentProgress**: `GetCurrentValue` accesses `animationClock.CurrentProgress.Value` without null checking; could throw if progress is null.
9. **DynamicGrid.Refresh clears and rebuilds all definitions**: Called on every `GridColumns` change and every visual child change; may have performance implications for grids with many children.
10. **TestIDViewModel.TestIdEditableText property notification missing**: The property setter doesn't raise `PropertyChanged`, unlike other properties.

View File

@@ -0,0 +1,138 @@
---
source_files:
- Common/DTS.CommonCore/Converters/BooleanToBorderThicknessConverter.cs
- Common/DTS.CommonCore/Converters/BooleanToBorderBrushConverter.cs
- Common/DTS.CommonCore/Converters/BooleanOrMultiConverter.cs
- Common/DTS.CommonCore/Converters/BooleanToGreenBorderConverter.cs
- Common/DTS.CommonCore/Converters/DateTimeWithMillisecondsToStringConverter.cs
- Common/DTS.CommonCore/Converters/EnumVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/InverseEnumVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/ActiveContentConverter.cs
- Common/DTS.CommonCore/Converters/FaultedTextConverter.cs
- Common/DTS.CommonCore/Converters/TriggerTextConverter.cs
- Common/DTS.CommonCore/Converters/NullableFloatConverter.cs
- Common/DTS.CommonCore/Converters/TriggerColorConverter.cs
- Common/DTS.CommonCore/Converters/FaultedColorConverter.cs
- Common/DTS.CommonCore/Converters/DateConverter.cs
- Common/DTS.CommonCore/Converters/InverseEnumEnabledConverter.cs
- Common/DTS.CommonCore/Converters/IsLessThanConverter.cs
- Common/DTS.CommonCore/Converters/ListToStringConverter.cs
- Common/DTS.CommonCore/Converters/IsGreaterThanConverter.cs
- Common/DTS.CommonCore/Converters/NonZeroToColorConverter.cs
- Common/DTS.CommonCore/Converters/HeightConverter.cs
- Common/DTS.CommonCore/Converters/ErrorToBooleanConverter.cs
- Common/DTS.CommonCore/Converters/WidthConverter.cs
- Common/DTS.CommonCore/Converters/StringListToVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/StatusToBorderThicknessConverter.cs
- Common/DTS.CommonCore/Converters/ArrayVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/ErrorToColorConverter.cs
- Common/DTS.CommonCore/Converters/GreaterThanToBoolConverter.cs
- Common/DTS.CommonCore/Converters/BooleanToColorConverter.cs
- Common/DTS.CommonCore/Converters/BooleanToItalicFontStyleConverter.cs
- Common/DTS.CommonCore/Converters/IntervalToVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/DiagStatusShuntColorConverter.cs
- Common/DTS.CommonCore/Converters/DiagStatusOffsetColorConverter.cs
- Common/DTS.CommonCore/Converters/InverseBooleanToOpacityConverter.cs
- Common/DTS.CommonCore/Converters/StatusToColorConverter.cs
- Common/DTS.CommonCore/Converters/ColorToSolidColorBrushConverter .cs
- Common/DTS.CommonCore/Converters/BooleanAndToVisibiltyMultiConverter.cs
- Common/DTS.CommonCore/Converters/BooleanOrToVisibilityMultiConverter.cs
- Common/DTS.CommonCore/Converters/DoubleFromThousandthUnitToBaseUnit.cs
- Common/DTS.CommonCore/Converters/BooleanToOpacityConverter.cs
- Common/DTS.CommonCore/Converters/DASStatusArmTextConverter.cs
- Common/DTS.CommonCore/Converters/EnumBooleanConverter.cs
- Common/DTS.CommonCore/Converters/InitialOffsetToIEPESensorOffsetConverter.cs
- Common/DTS.CommonCore/Converters/DASStatusColorConverter.cs
- Common/DTS.CommonCore/Converters/DASStatusArmColorConverter .cs
- Common/DTS.CommonCore/Converters/PercentConverter.cs
- Common/DTS.CommonCore/Converters/NumericStringFormatConverter.cs
- Common/DTS.CommonCore/Converters/VisibilityToRowHeightConverter.cs
- Common/DTS.CommonCore/Converters/GroupImportErrorToStringConverter.cs
- Common/DTS.CommonCore/Converters/GroupNameToVisibilityConverter.cs
- Common/DTS.CommonCore/Converters/FilePathsToShortStringConverter.cs
- Common/DTS.CommonCore/Converters/InverseBooleanConverter.cs
- Common/DTS.CommonCore/Converters/EnumDescriptionTypeConverter.cs
- Common/DTS.CommonCore/Converters/TestDataToRegionOfInterestMaximumConverter.cs
generated_at: "2026-04-16T12:00:34.413877+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8cec2e1657d13038"
---
# Documentation: DTS.Common.Converters
## 1. Purpose
This module provides a comprehensive library of WPF value converters (implementing `IValueConverter` and `IMultiValueConverter`) for the DTS application. It facilitates the binding of UI elements to backend data models by transforming data types (e.g., Booleans to Visibility or Colors, Enums to Strings, numeric formatting) and applying conditional logic within XAML. It serves as the bridge between raw data properties and presentation logic, supporting the MVVM architectural pattern.
## 2. Public Interface
This module contains the following classes:
### Boolean Converters
* **`BooleanToBorderThicknessConverter`** (`IValueConverter`)
* `Convert`: Returns `1` if `value` is `true`, otherwise `2`.
* `ConvertBack`: Returns `null`.
* **`BooleanToBorderBrushConverter`** (`IValueConverter`)
* `Convert`: Returns `BrushesAndColors.Brush_Warning` if `value` is `true`, otherwise `Brushes.Transparent`.
* `ConvertBack`: Returns `null`.
* **`BooleanToGreenBorderConverter`** (`IValueConverter`)
* `Convert`: Returns `BrushesAndColors.BrushApplicationStatusPowerGreen` if `value` is `true`, otherwise `BrushesAndColors.BrushFlatControlDarkForeground`.
* `ConvertBack`: Returns `null`.
* **`BooleanOrMultiConverter`** (`IMultiValueConverter`)
* `Convert`: Returns `true` if any value in the `values` array is `true`. Returns `false` if any value is not a `bool`.
* `ConvertBack`: Throws `NotImplementedException`.
* **`BooleanToColorConverter`** (`IValueConverter`)
* Properties: `Background` (bool), `Inverted` (bool), `AttentionBrush` (bool), `WarningBrush` (bool).
* `Convert`: Returns specific brushes based on boolean `value` and configured properties. Defaults to error/attention brushes for `false`.
* `ConvertBack`: Returns `null`.
* **`BooleanToItalicFontStyleConverter`** (`IValueConverter`)
* `Convert`: Returns `FontStyles.Italic` if `value` is `true`, otherwise `FontStyles.Normal`.
* `ConvertBack`: Returns `null`.
* **`BooleanToOpacityConverter`** (`IValueConverter`)
* `Convert`: Returns `0.5` if `value` is `true`, otherwise `1`.
* `ConvertBack`: Returns `null`.
* **`InverseBooleanToOpacityConverter`** (`IValueConverter`)
* `Convert`: Returns `1.0` if `value` is `true`, otherwise `0.5`.
* `ConvertBack`: Returns `null`.
* **`InverseBooleanConverter`** (`IValueConverter`)
* `Convert`: Returns the logical negation of the boolean `value`.
* `ConvertBack`: Returns the logical negation of the boolean `value`.
* **`BooleanAndToVisibilityMultiConverter`** (`IMultiValueConverter`)
* `Convert`: Returns `Visibility.Visible` if all values are `true`. Supports parameter flags "FALSE" (inverts logic) and "HIDE" (uses `Hidden` instead of `Collapsed`).
* `ConvertBack`: Throws `NotImplementedException`.
* **`BooleanOrToVisibilityMultiConverter`** (`IMultiValueConverter`)
* `Convert`: Returns `Visibility.Visible` if any value is `true`. Supports parameter flags "FALSE" and "HIDE".
* `ConvertBack`: Throws `NotImplementedException`.
### Enum Converters
* **`EnumVisibilityConverter`** (`IValueConverter`)
* `Convert`: Returns `Visibility.Visible` if `value.Equals(parameter)`, otherwise `Visibility.Hidden`.
* `ConvertBack`: Returns `parameter` if `value` is `Visibility.Visible`, otherwise `Binding.DoNothing`.
* **`InverseEnumVisibilityConverter`** (`IValueConverter`)
* `Convert`: Returns `Visibility.Hidden` if `value.Equals(parameter)`, otherwise `Visibility.Visible`.
* `ConvertBack`: Returns `parameter` if `value` is `Visibility.Hidden`, otherwise `Binding.DoNothing`.
* **`InverseEnumEnabledConverter`** (`IValueConverter`)
* `Convert`: Returns `false` if `value.Equals(parameter)`, otherwise `true`.
* `ConvertBack`: Returns `parameter` if `value` is `false`, otherwise `Binding.DoNothing`.
* **`EnumBooleanConverter`** (`IValueConverter`)
* `Convert`: Returns `value.Equals(parameter)`.
* `ConvertBack`: Returns `parameter` if `value` is `true`, otherwise `Binding.DoNothing`.
* **`EnumDescriptionTypeConverter`** (`EnumConverter`)
* `ConvertTo`: Returns the `DescriptionAttribute` value of the enum, looking up the string in `Strings.Strings.ResourceManager`.
* `GetEnumDescription`: Static helper to retrieve description string for an Enum value.
### Numeric & Comparison Converters
* **`IsLessThanConverter`** (`IValueConverter`)
* `Convert`: Parses `value` and `parameter` as decimals. Returns `true` if `left < right`.
* `ConvertBack`: Returns `DependencyProperty.UnsetValue`.
* **`IsGreaterThanConverter`** (`IValueConverter`)
* `Convert`: Parses `value` and `parameter` as decimals. Returns `true` if `left > right`.
* `ConvertBack`: Returns `DependencyProperty.UnsetValue`.
* **`GreaterEqualThanToBoolConverter`** (`IValueConverter`)
* `Convert`: Returns `true` if `value >= parameter`. Handles `int`, `double`, and `ushort`.
* `ConvertBack`: Returns `false`.
* **`

View File

@@ -0,0 +1,102 @@
---
source_files:
- Common/DTS.CommonCore/Dialogs/IRegionManagerAware.cs.cs
- Common/DTS.CommonCore/Dialogs/IPopupWindowActionAware.cs
- Common/DTS.CommonCore/Dialogs/ConfirmationEx.cs
- Common/DTS.CommonCore/Dialogs/ConfirmationWindow.xaml.cs
- Common/DTS.CommonCore/Dialogs/NotificationWindow.xaml.cs
- Common/DTS.CommonCore/Dialogs/PopupWindowAction.cs
- Common/DTS.CommonCore/Dialogs/BrowseForFolderDialog.cs
generated_at: "2026-04-16T12:05:57.382273+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "e520922d284c9033"
---
# Documentation: DTS.Common.Dialogs
## 1. Purpose
This module provides a custom dialog management infrastructure for WPF applications built on the Prism framework. It extends Prism's `InteractionRequest` patterns to support custom window styling (such as hiding the system close button), region management within popups, and specific dialog types like confirmations and notifications. Additionally, it provides a wrapper (`BrowseForFolderDialog`) around the Win32 API `SHBrowseForFolder` for folder selection capabilities not natively available in standard WPF dialogs.
## 2. Public Interface
### Interfaces
**`IRegionManagerAware`**
- `IRegionManager RegionManager { get; set; }`: Allows a view or view model to receive a scoped `IRegionManager` when hosted inside a popup window.
**`IPopupWindowActionAware`**
- `Window HostWindow { get; set; }`: Provides access to the hosting window instance.
- `Notification HostNotification { get; set; }`: Provides access to the notification context (e.g., `Confirmation` or `Notification` object) passed to the window.
### Classes
**`ConfirmationEx`** (Inherits `Confirmation`)
- `MessageBoxButton Buttons { get; set; }`: Defaults to `MessageBoxButton.OKCancel`. Defines buttons shown in the confirmation.
- `MessageBoxImage Image { get; set; }`: Defaults to `MessageBoxImage.Question`. Defines the icon shown.
- `MessageBoxResult Result { get; set; }`: Stores the result of the user interaction.
**`ConfirmationWindow`** (Inherits `Window`)
- `DataTemplate ConfirmationTemplate { get; set; }`: Dependency property used to define the visual presentation of the confirmation content.
- `void Connect(int connectionId, object target)`: Throws `NotImplementedException`.
**`NotificationWindow`** (Inherits `Window`)
- `DataTemplate NotificationTemplate { get; set; }`: Dependency property for the notification content layout.
- `Uri ImageUri { get; set; }`: Dependency property for the notification icon. Defaults to a pack URI pointing to `warning_48.png`.
- `void Connect(int connectionId, object target)`: Empty implementation.
**`PopupWindowAction`** (Inherits `TriggerAction<FrameworkElement>`)
- **Properties**:
- `FrameworkElement WindowContent`: The root visual element to display in the popup.
- `DataTemplate ContentTemplate`: The template applied to the content.
- `bool IsModal`: Determines if the window blocks interaction with the owner.
- `WindowPositions StartupPosition`: Enum (`CenterOwner`, `CenterScreen`). Defaults to `CenterScreen`.
- `bool AllowMultipleNotificationWindows`: Prevents or allows concurrent notification windows.
- **Methods**:
- `protected override void Invoke(object parameter)`: Executes the trigger, creates the window, sets up region managers, and shows the dialog.
- `protected Window GetWindow(Notification notification)`: Factory method returning the appropriate `Window` wrapper.
- `protected Window CreateWindow(Notification notification)`: Creates a `ConfirmationWindow` or `NotificationWindow` if `WindowContent` is null.
**`BrowseForFolderDialog`**
- **Properties**:
- `string SelectedFolder`: The path chosen by the user.
- `string Title`: The text displayed above the tree view.
- `string InitialFolder`: The path selected on startup.
- `string InitialExpandedFolder`: The path selected and expanded on startup.
- `string OKButtonText`: Custom text for the confirmation button.
- `BrowseInfoFlags BrowserDialogFlags`: Win32 flags controlling dialog behavior (defaults to `BIF_NEWDIALOGSTYLE`).
- **Methods**:
- `Nullable<bool> ShowDialog()`: Shows the dialog modally.
- `Nullable<bool> ShowDialog(Window owner)`: Shows the dialog modally with a WPF window owner.
## 3. Invariants
1. **Window System Menu Removal**: Both `ConfirmationWindow` and `NotificationWindow` modify the window style upon initialization (`SourceInitialized`) to remove the `WS_SYSMENU` flag. This effectively hides the system menu and the close button from the title bar.
2. **Region Management**: When `PopupWindowAction` invokes a dialog with `WindowContent` set, it guarantees that a scoped `IRegionManager` is attached to that content if one is not already present.
3. **Visual Tree Parenting**: `PopupWindowAction.Invoke` will exit immediately without showing a window if `WindowContent` is already a child of another visual element (`WindowContent.Parent != null`).
4. **Default Dialog Creation**: If `PopupWindowAction.WindowContent` is null, the action defaults to creating either a `ConfirmationWindow` (if the notification is `Confirmation`) or a `NotificationWindow` (if the notification content is `NotificationContentEventArgs`).
## 4. Dependencies
**Internal Dependencies (Inferred):**
- `DTS.Common.Enums`: Required for `PopupWindowImage` enum used in `PopupWindowAction.GetImageUri`.
- `DTS.Common.Events`: Required for `NotificationContentEventArgs` used in `PopupWindowAction.CreateWindow`.
**External Dependencies:**
- `Microsoft.Practices.Prism.Regions`: Used for `IRegionManager` and region scoping.
- `Microsoft.Practices.Prism.Interactivity.InteractionRequest`: Used for `Notification`, `Confirmation`, `InteractionRequestedEventArgs`, and `TriggerAction`.
- `System.Windows.Interactivity`: Used for `TriggerAction<FrameworkElement>`.
- `System.Windows`: Core WPF types.
- `user32.dll`: P/Invoke for window styling (`SetWindowLong`, `GetWindowLong`) and messaging.
- `shell32.dll`: P/Invoke for folder browsing (`SHBrowseForFolderW`, `SHGetPathFromIDList`).
## 5. Gotchas
1. **Hardcoded Clipboard Text**: `NotificationWindow` contains an event handler `CoppyToClibord_Click` (note the typo in method name) that sets the clipboard text to the hardcoded string "Hello, clipboard". This appears to be debug/test code left in the production source.
2. **Inconsistent Image Paths**:
- `NotificationWindow` defaults its `ImageUri` to a path containing `RibbonControl/Images/warning_48.png`.
- `PopupWindowAction.GetImageUri` constructs paths pointing to `Images/` (without `RibbonControl`).
- This inconsistency suggests a refactoring mismatch or missing resource files; developers adding new icons should verify the correct pack URI structure.
3. **Unimplemented Interface Method**: The `Connect` method in `ConfirmationWindow` throws `NotImplementedException`. This method is typically associated with the `IComponentConnector` interface generated by the WPF compiler for XAML parsing. The manual implementation throwing an exception suggests the code-behind may be out of sync with the XAML or manually implementing an interface it shouldn't.
4. **COM Initialization Requirement**: `BrowseForFolderDialog` defaults to `BIF_NEWDIALOGSTYLE`. The Win32 documentation for this flag states that `OleInitialize` must be called before using the API. This class does not call `OleInitialize`; the consuming application is responsible for COM initialization.
5. **Commented Out Features**: Both `ConfirmationEx` and `PopupWindowAction` contain significant blocks of commented-out code related to "Timeout" functionality (auto-closing dialogs). This suggests unfinished or deprecated features that may confuse developers looking for timeout capabilities.

View File

@@ -0,0 +1,395 @@
---
source_files:
- Common/DTS.CommonCore/Enums/IsoRestrictionLevels.cs
- Common/DTS.CommonCore/Enums/GPSSentenceTypes.cs
- Common/DTS.CommonCore/Enums/UartDataFormat.cs
- Common/DTS.CommonCore/Enums/NetworkSelection.cs
- Common/DTS.CommonCore/Enums/ScriptTypes.cs
- Common/DTS.CommonCore/Enums/InitializationTypes.cs
- Common/DTS.CommonCore/Enums/Strings.cs
- Common/DTS.CommonCore/Enums/MigrationResult.cs
- Common/DTS.CommonCore/Enums/SLICE6MulticastProperties.cs
- Common/DTS.CommonCore/Enums/RibbonTabNames.cs
- Common/DTS.CommonCore/Enums/IsoSupportLevels.cs
- Common/DTS.CommonCore/Enums/ImportFormats.cs
- Common/DTS.CommonCore/Enums/TabControlOperation.cs
- Common/DTS.CommonCore/Enums/IncludeOverwriteName.cs
- Common/DTS.CommonCore/Enums/RibbonControlOperation.cs
- Common/DTS.CommonCore/Enums/UICultures.cs
- Common/DTS.CommonCore/Enums/T0Mode.cs
- Common/DTS.CommonCore/Enums/VelocityUnit.cs
- Common/DTS.CommonCore/Enums/ImportStatus.cs
- Common/DTS.CommonCore/Enums/IsoViewMode.cs
- Common/DTS.CommonCore/Enums/PopupWindowImage.cs
- Common/DTS.CommonCore/Enums/UIItemStatus.cs
- Common/DTS.CommonCore/Enums/DigitalOutputs.cs
- Common/DTS.CommonCore/Enums/DigitalInputs.cs
- Common/DTS.CommonCore/Enums/DataFlag.cs
- Common/DTS.CommonCore/Enums/Squibs.cs
- Common/DTS.CommonCore/Enums/SupportedExportFormatBitFlags.cs
- Common/DTS.CommonCore/Enums/UartBaudRate.cs
- Common/DTS.CommonCore/Enums/EnumBindingSourceExtension.cs
- Common/DTS.CommonCore/Enums/UDPStreamProfile.cs
- Common/DTS.CommonCore/Enums/ExcitationVoltageOptions.cs
- Common/DTS.CommonCore/Enums/RecordingModes.cs
- Common/DTS.CommonCore/Enums/ApplicationStatusTypes.cs
- Common/DTS.CommonCore/Enums/ExportHeaderLine.cs
- Common/DTS.CommonCore/Enums/StreamDigitalFilterTypes.cs
- Common/DTS.CommonCore/Enums/CFCFilter.cs
- Common/DTS.CommonCore/Enums/ClockSource.cs
generated_at: "2026-04-16T12:00:02.414495+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b809df2688f575c2"
---
# Documentation: DTS.CommonCore.Enums
## 1. Purpose
This module defines the canonical enumeration types and related utility classes for the DTS (Data Acquisition System) common core library. It provides strongly-typed constants for hardware configuration (UART, digital I/O, squibs, excitation voltages), data processing (CFC filters, recording modes, streaming profiles), application state management (status types, import/export formats), and UI concerns (cultures, popup images, ribbon controls). The enums serve as the shared vocabulary between hardware drivers, business logic, and presentation layers.
## 2. Public Interface
### Enums
#### `GPSSentenceTypes`
```csharp
public enum GPSSentenceTypes { GPGGA, GPRMC }
```
Defines NMEA GPS sentence types for parsing GPS data streams.
#### `UartDataFormat`
```csharp
public enum UartDataFormat { Binary, PlainText, NMEA }
```
Specifies the data format for UART communication.
#### `NetworkSelection`
```csharp
public enum NetworkSelection { Default, NetworkId, NetworkDesc }
```
Defines network selection criteria.
#### `ScriptTypes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum ScriptTypes { Migration, Initialization }
```
Categorizes script execution types.
#### `InitializationTypes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum InitializationTypes { Aero, Crash, TSRAIR }
```
Defines initialization type categories.
#### `StringReplacementMode`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum StringReplacementMode { All, First, Last }
```
Controls string replacement behavior.
#### `MigrationResult`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum MigrationResult { OK, ExceptionThrown, WarningAllowStreamingModesWasNotMigrated }
```
Indicates the outcome of a migration operation.
#### `SLICE6Properties`
```csharp
public enum SLICE6Properties { SLICE6MulticastAddress, SLICE6MulticastCommandPort, SLICE6MulticastResponsePort }
```
Properties for SLICE6 UDP broadcast autodiscovery.
#### `IsoSupportLevels`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum IsoSupportLevels {
[Description("ISO 13499")] ISO_ONLY,
[Description("User specified channel codes")] TRANSITORY,
[Description("No ISO")] NO_ISO
}
```
Defines ISO 13499 channel code support levels.
#### `ImportFormats`
```csharp
public enum ImportFormats {
NOT_SPECIFIED = 1, DTS_XML = 2, ISF = 3, TSF = 4, DTS_CSV = 5,
TTS_XML = 6, CrashDesigner_XML = 7, E2X = 8, TTS_CSV = 9
}
```
Specifies supported import file formats with explicit integer values.
#### `TabControlOperation` / `RibbonControlOperation`
```csharp
public enum TabControlOperation { AddedItem, RemovedItem }
public enum RibbonControlOperation { AddedItem, RemovedItem }
```
Defines UI control modification operations.
#### `IncludeOverwriteName`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum IncludeOverwriteName { IncludedCheckBox, OverwriteCheckBox, ImportingTestSetupName }
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum ExportChoices { ExportType, UnfilteredEUCheckBox, FilteredEUCheckBox, MVCheckBox, ADCCheckBox }
```
Import/export UI selection options.
#### `UICultures`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum UICultures {
[DescriptionResource("UICultures_de-DE")] de_DE,
[DescriptionResource("UICultures_en-US")] en_US,
[DescriptionResource("UICultures_es-ES")] es_ES,
[DescriptionResource("UICultures_fr-FR")] fr_FR,
[DescriptionResource("UICultures_it-IT")] it_IT,
[DescriptionResource("UICultures_ja-JP")] ja_JP
}
```
Supported UI localization cultures.
#### `T0Mode`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum T0Mode {
[Description("DAS")] DAS = 0,
[Description("Test")] Test = 1
}
```
Defines T0 (time zero) reference mode.
#### `VelocityUnit`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum VelocityUnit {
[Description("EditTestSetupObjectMeta_VelocityUnit_KilometerPerHour")] KilometerPerHour = 0,
[Description("EditTestSetupObjectMeta_VelocityUnit_MeterPerSecond")] MeterPerSecond = 1
}
```
Velocity measurement units.
#### `ImportExtraStatus` / `PossibleStatus`
```csharp
public enum ImportExtraStatus { None, NormalizingIds, ReadingCalibrations, ReadingChannels, ReadingCustomerDetails, ReadingEngineerDetails, ReadingGroups, ReadingHardware, ReadingLabDetails, ReadingSensors, ReadingTestSetups, ReadingUsers, ReadingXML }
public enum PossibleStatus { Waiting, Working, Done, Failed, Reading, Importing }
```
Import operation status indicators.
#### `IsoViewMode`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum IsoViewMode {
[Description("ISOOnly")] ISOOnly,
[Description("ISOAndUserCode")] ISOAndUserCode,
[Description("UserCodeOnly")] UserCodeOnly,
[Description("ChannelNameOnly")] ChannelNameOnly
}
```
Channel display naming convention.
#### `PopupWindowImage`
```csharp
public enum PopupWindowImage { Warning = 0, Error = 1, Question = 2, Information = 3 }
```
Defines popup window icon types.
#### `UIItemStatus`
```csharp
public enum UIItemStatus { None, Success, Failed, Error, Warning }
```
UI item operation status.
#### `DigitalOutputModes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum DigitalOutputModes {
[Description("Off")] NONE = 0,
[DescriptionResource("DigitalOutputMode_FVLH")] FVLH = 1 << 0,
[DescriptionResource("DigitalOutputMode_FVHL")] FVHL = 1 << 1,
[DescriptionResource("DigitalOutputMode_CCNO")] CCNO = 1 << 2,
[DescriptionResource("DigitalOutputMode_CCNC")] CCNC = 1 << 3
}
```
Digital output configuration modes (bitwise flags).
#### `DigitalInputModes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum DigitalInputModes {
NONE = 1 << 0,
[DescriptionResource("DigitalInputMode_TLH")] TLH = 1 << 1,
[DescriptionResource("DigitalInputMode_THL")] THL = 1 << 2,
[DescriptionResource("DigitalInputMode_CCNO")] CCNO = 1 << 3,
[DescriptionResource("DigitalInputMode_CCNC")] CCNC = 1 << 4
}
```
Digital input configuration modes (bitwise flags).
#### `DataFlag`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum DataFlag {
[Description("None")] None = 0,
[Description("Normal")] Normal = 1,
[Description("Saturated")] Saturated = 2,
[Description("Zero Crossing Error")] ZeroCrossing = 3,
[Description("Broken Wire")] BrokenWire = 4,
[Description("Other")] Other = -1
}
```
Data quality/status flags for channel data.
#### `SquibMeasurementType` / `SquibFireMode`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum SquibMeasurementType { NONE = 0, CURRENT = 1 << 0, INIT_SIGNAL = 1 << 1, VOLTAGE = 1 << 2 }
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum SquibFireMode {
NONE = 1 << 0,
[DescriptionResource("SquibFireMode_Cap")] CAP = 1 << 1,
[DescriptionResource("SquibFireMode_CC")] CONSTANT = 1 << 2,
AC = 1 << 3
}
```
Squib (explosive initiator) configuration modes.
#### `SupportedExportFormatBitFlags`
```csharp
[Flags]
public enum SupportedExportFormatBitFlags {
none = 0x0, csvunfiltered = 0x1, diademadc = 0x2, isounfiltered = 0x4,
somatunfiltered = 0x8, tdmsadc = 0x10, toyotaunfiltered = 0x20, tsvunfiltered = 0x40,
csvfiltered = 0x80, isofiltered = 0x200, somatfiltered = 0x400, tdasadc = 0x800,
toyotafiltered = 0x1000, tsvfiltered = 0x2000, rdfadc = 0x4000, ChryslerDDAS = 0x8000,
HDFUnfiltered = 0x10000, HDFFiltered = 0x20000, HDFMV = 0x40000, HDFADC = 0x80000,
xlsxfiltered = 0x100000, xlsxunfiltered = 0x200000, CSVADC = 0x400000, CSVMV = 0x800000,
Ch10FilteredEU = 0x1000000, Ch10UnfilteredEU = 0x2000000, FIATASC = 0x4000000
}
```
Bitwise flags for supported export formats.
#### `UartBaudRate`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum UartBaudRate : uint {
_110 = 110, _300 = 300, _600 = 600, _1200 = 1200, _2400 = 2400,
_4800 = 4800, _9600 = 9600, _14400 = 14400, _19200 = 19200, _38400 = 38400,
_57600 = 57600, _115200 = 115200, _230400 = 230400, _460800 = 460800, _921600 = 921600
}
```
Standard UART baud rates; enum name prefixed with underscore, value equals actual baud rate.
#### `UDPStreamProfile`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum UDPStreamProfile : byte {
RTCStreaming = 0, DTS_UDP = 1, CH10_MANUAL_CONFIG = 2, CH10_PCM128_MM = 3,
CH10_ANALOG = 4, CH10_PCM_STANDARD = 5, CH10_PCM_SUPERCOM = 6,
CH10_PCM_128BIT_2HDR = 7, CH10_ANALOG_2HDR = 8, CH10_PCM_STANDARD_2HDR = 9,
CH10_PCM_SUPERCOM_2HDR = 10, TMNS_PCM_STANDARD = 11, TMNS_PCM_SUPERCOM = 12,
IENA_PTYPE_STREAM = 13, UART_STREAM = 14
}
```
UDP streaming profiles for data transmission (Chapter 10, TmNS, IENA formats).
#### `ExcitationVoltageOptions.ExcitationVoltageOption`
```csharp
public enum ExcitationVoltageOption {
[VoltageMagnitude(0.0)][Description("Undefined")] Undefined = 1,
[VoltageMagnitude(2.0)][Description("2.0")] Volt2 = 2,
[VoltageMagnitude(2.5)][Description("2.5")] Volt2_5 = 4,
[VoltageMagnitude(3.0)][Description("3.0")] Volt3 = 8,
[VoltageMagnitude(5.0)][Description("5.0")] Volt5 = 16,
[VoltageMagnitude(10.0)][Description("10.0")] Volt10 = 32,
[VoltageMagnitude(1.0)][Description("1.0")] Volt1 = 64
}
```
Sensor excitation voltage options with custom `VoltageMagnitudeAttribute` for extracting numerical values.
#### `RecordingModes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum RecordingModes {
CircularBuffer, Recorder, HybridRecorder, S6A_DeviceStreamingOnly,
CircularBufferPlusUART, RecorderPlusUART, MultipleEventCircularBuffer,
MultipleEventRecorder, ContinuousRecorder, RecorderAndStreamSubSample,
CircularBufferAndStreamSubSample, Active, MultipleEventActive,
MultipleEventHybridRecorder, Streaming, Scheduled, Interval,
MultipleEventCircularBufferPlusUART, MultipleEventRecorderPlusUART,
ContinuousRecorderPlusUART, RAMActive, MultipleEventRAMActive,
RecordOnBoot, RecordOnBootPlusUART, MultipleEventHybridAndStream,
HybridAndStream, MultipleEventCircularBufferAndStream,
MultipleEventRecorderAndStream
}
```
DAS recording mode configurations.
#### `ApplicationStatusTypes`
```csharp
public enum ApplicationStatusTypes {
IDLE, SettingConfiguration, ClearingFlash, Arm, AutoArmPrepare,
WaitingForStart, WaitingForTrigger, WaitingForStartWithEvent,
WaitingForTriggerCheck, WaitingForAutoArm, WaitingForStreaming,
Passed, FailedStart, FailedTrigger, Done, FailedArm, FailedDisarm,
// ... (70+ total status values)
}
```
Comprehensive application state machine status values.
#### `FtssHeaderLine` / `XLSXExportHeaderLine`
```csharp
public enum FtssHeaderLine {
[Description("Headers")] Headers = 0,
[Description("Test Date")] TestDate,
// ... (30+ header line types)
}
```
Defines header line content for CSV and XLSX file exports.
#### `StreamDigitalFilterTypes`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum StreamDigitalFilterTypes {
NO_DSP_FILTER = 0,
CH10_IIR_6TH_OPTION_80X = 5,
CH10_FIR_45T65T_OPTION_80X = 6,
ALL_RT_IIR_6TH_OPTION_80X = 13,
ALL_RT_FIR_45T65T_OPTION_80X = 14
}
```
DSP IIR/FIR filter profiles for streaming data.
#### `CFCFilter`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum CFCFilter {
[Description("None")] None = 0,
[Description("Unfiltered")] Unfiltered = -2,
[Description("CFC 10")] Class10 = 17,
[Description("CFC 60")] Class60 = 100,
[Description("CFC 180")] Class180 = 300,
[Description("CFC 600")] Class600 = 1000,
[Description("CFC 1000")] Class1000 = 1650
}
```
SAE CFC (Channel Frequency Class) filter definitions per ISO 6487.
#### `ClockSyncProfile` / `InputClockSource` / `OutputClockSource`
```csharp
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum ClockSyncProfile : byte { None = 0, Manual, Slave_E2E, Master_E2E, Auto_E2E, /* 30+ profiles */ }
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum InputClockSource : byte { None = 0, PTP = 1 << 0, IRIG = 1 << 1, GPS = 1 << 2, OnePPS = 1 << 3, /* combinations */ }
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum OutputClockSource : byte { None = 0, PTP =

View File

@@ -0,0 +1,153 @@
---
source_files:
- Common/DTS.CommonCore/Events/LoginUserEvent.cs
- Common/DTS.CommonCore/Events/TextPastedEvent.cs
- Common/DTS.CommonCore/Events/BusyIndicatorChangeNotification.cs
- Common/DTS.CommonCore/Events/ComActiveEvent.cs
- Common/DTS.CommonCore/Events/CloseApplicationRequested.cs
- Common/DTS.CommonCore/Events/TabControlSelectionChanged.cs
- Common/DTS.CommonCore/Events/RaiseNotification.cs
- Common/DTS.CommonCore/Events/PageSetActiveEvent.cs
- Common/DTS.CommonCore/Events/GroupTemplateChangeNotification.cs
- Common/DTS.CommonCore/Events/DatabaseVersionChangedEvent.cs
- Common/DTS.CommonCore/Events/SetSaveButton.cs
- Common/DTS.CommonCore/Events/DBConnectionEvent.cs
- Common/DTS.CommonCore/Events/AutomaticModeStatusEvent.cs
- Common/DTS.CommonCore/Events/SetPageVisibilityEvent.cs
- Common/DTS.CommonCore/Events/LogoutUserEvent.cs
- Common/DTS.CommonCore/Events/PageNameEvent.cs
- Common/DTS.CommonCore/Events/TestEvent.cs
- Common/DTS.CommonCore/Events/PageSelectionChanged.cs
- Common/DTS.CommonCore/Events/UserEvent.cs
- Common/DTS.CommonCore/Events/ListViewStatusEvent.cs
- Common/DTS.CommonCore/Events/HelpTextEvent.cs
- Common/DTS.CommonCore/Events/PageModifiedEvent.cs
- Common/DTS.CommonCore/Events/FeedbackEvent.cs
- Common/DTS.CommonCore/Events/AssemblyListNotification.cs
- Common/DTS.CommonCore/Events/CancelProcess.cs
- Common/DTS.CommonCore/Events/TabControlSelectionEventArgs.cs
- Common/DTS.CommonCore/Events/SLICE6MulticastPropertyEvent.cs
- Common/DTS.CommonCore/Events/AppStatusEvent.cs
- Common/DTS.CommonCore/Events/PageErrorEvent.cs
- Common/DTS.CommonCore/Events/PageNavigationRequestEvent.cs
- Common/DTS.CommonCore/Events/ProgressBarEvent.cs
- Common/DTS.CommonCore/Events/NotificationContentEventArgs.cs
- Common/DTS.CommonCore/Events/ShowStatus.cs
generated_at: "2026-04-16T12:07:09.645358+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "9cee3f5e2ea58fa5"
---
# Documentation: DTS.Common.Events
## 1. Purpose
This module defines the application-wide event aggregation contract for the DTS system using the Microsoft Prism Library (`Microsoft.Practices.Prism.Events`). It provides a centralized catalog of event types (`CompositePresentationEvent`) and their associated payload classes (EventArgs) to facilitate loosely-coupled communication between components. The events cover a broad range of concerns including user authentication, database connectivity, UI state management (busy indicators, tabs, notifications), hardware communication (COM status, SLICE6), and page lifecycle management.
## 2. Public Interface
### Event Classes
All event classes inherit from `CompositePresentationEvent` and are designed to be used with an `IEventAggregator`.
| Event Class | Payload Type | Description |
| :--- | :--- | :--- |
| **`AppStatusEvent`** | `AppStatusArg` (enum) | Notifies the application to mark itself as busy, available, or handle shutdown/close/logout states. |
| **`AppStatusExEvent`** | `AppStatusExArg` | Extended app status notification including the name of the process notifying the status. |
| **`AssemblyListNotification`** | `AssemblyListInfo` | Used to display notification content regarding assembly lists. |
| **`AssemblyListNotificationViewer`** | `AssemblyListInfo` | Viewer-specific event for assembly list notifications. |
| **`AutomaticModeStatusEvent`** | `AutomaticModeStatusEventArgs` | Informs the app that Automatic Mode status has changed. |
| **`BusyIndicatorChangeNotification`** | `bool` | Notifies changes to the busy indicator state. |
| **`CancelProcessEvent`** | `CancelProcess` | Used by services to display status or cancel the current process. |
| **`CloseApplicationRequested`** | `object` | Notifies subscribers that the application is requested to be closed. |
| **`CommActiveEvent`** | `ComStatusArg` (enum) | Informs the app that COM status has changed (CommandStart/ResponseStart). |
| **`DatabaseVersionChangedEvent`** | `DatabaseVersionChangedEventArgs` | Informs the app that the database version has changed. |
| **`DBConnectionEvent`** | `DBConnectionArg` | Informs the app about database connection status (Connected/DBName/Server). |
| **`FeedbackEvent`** | `FeedbackArg` | Informs the feedback page to update with severity and message. |
| **`GroupTemplateChangeNotification`** | `IBaseModel` | Notifies that the selected Group Template has changed. |
| **`HelpTextEvent`** | `HelpTextEventArg` | Handles tooltip events for help text. |
| **`ListViewStatusEvent`** | `ListViewStatusArg` | Notifies ListView status changes (Unloaded/ScrollToBottom). |
| **`LoginUserEvent`** | `LoginUserArg` | Event related to user login. |
| **`LogoutUserEvent`** | `LogoutUserArg` | Event related to user logout, includes reason (e.g., DatabaseSwitch). |
| **`PageErrorEvent`** | `PageErrorArg` | Surfaces page errors to the application. |
| **`PageModifiedEvent`** | `PageModifiedArg` | Notifies that a page has been modified, cleared, or saved. |
| **`PageNameEvent`** | `PageNameEventArg` | Informs the app that a page name has been updated. |
| **`PageNavigationRequestEvent`** | `PageNavigationRequest` | Requests navigation to a specific destination (Sensor/TestSetups). |
| **`PageSelectionChanged`** | `PageSelectionChangedArg` | Notifies that page selection has changed. |
| **`PageSetActiveEvent`** | `PageSetActiveEventArg` | Informs that a page has been set active. |
| **`ProgressBarEvent`** | `ProgressBarEventArg` | Notification event for progress bars (color, percentage, text, visibility). |
| **`RaiseNotification`** | `NotificationContentEventArgs` | Displays notification content (message, details, icon, title). |
| **`SetPageHeaderVisibilityEvent`** | `SetPageHeaderVisibilityEventArgs` | Sets the visibility of the page header. |
| **`SetSaveButton`** | `SaveButtonUsability` | Enables or disables the Save button. |
| **`ShowStatus`** | `StatusInfo` | Used by services to display current process status (Idle/Busy/Done). |
| **`SLICE6MulticastPropertyEventChanged`** | `SLICE6MulticastPropertyEventArgs` | Notifies changes to SLICE6 multicast properties. |
| **`TabControlSelectionChanged`** | `TabControlSelectionEventArgs` | Indicates that a TabControl's tab has been changed (Added/Removed). |
| **`TestEvent`** | `TestEventArg` | Informs the app that a test status has changed (Started/Ended). |
| **`TextPastedEvent`** | `ITextPastedEventArgs` | Handles text paste operations. |
| **`UserEvent`** | `UserEventArg` | Notifies user-related events (e.g., ViewingUserChanged). |
### Key Payload Classes & Arguments
* **`AppStatusArg` (enum)**: `Busy`, `Available`, `Shutdown`, `Close`, `UserLogout`.
* **`AppStatusExArg`**:
* `Status` (`AppStatusArg`): The status being notified.
* `Name` (`string`): Name of the process notifying.
* **`AutomaticModeStatusEventArgs`**:
* `TextSet` (`bool`): Default `false`.
* `Text` (`string`): Default `string.Empty`.
* **`CancelProcess`**:
* `IsBusy` (`bool`): Indicates if the process is busy.
* `ProcessId` (`int`): ID of the process.
* **`ComStatusArg` (enum)**: `CommandStart`, `ResponseStart`.
* **`DatabaseVersionChangedEventArgs`**:
* `Version` (`string`): The new version string.
* **`DBConnectionArg`**:
* `Connected` (`bool`).
* `DBName` (`string`).
* `Server` (`string`).
* **`FeedbackArg`**:
* `Severity` (`Severity` enum): `Information`, `Warning`, `Error`, `ResponseStarting`, `CommandStarting`.
* `Message` (`string`).
* **`ListViewStatusArg`**:
* `Status` (`ListViewStatus` enum): `Unloaded`, `ScrollToBottom`.
* `Id` (`string`).
* **`LogoutUserArg`**:
* `Reason` (`Reasons` enum): Currently only supports `DatabaseSwitch`.
* **`NotificationContentEventArgs`**:
* `Message` (`string`).
* `MessageDetails` (`string`).
* `Image` (`PopupWindowImage` enum): Default is `Error`.
* `Title` (`string`).
* **`PageErrorArg`**:
* `Errors` (`string[]`).
* `Page` (`object`).
* `Handled` (`bool`).
* **`PageModifiedArg`**:
* `PageStatus` (`Status` enum): `Clear`, `Modified`, `Saved`.
* `Page` (`object`).
* `Handled` (`bool`).
* **`PageNavigationRequest`**:
* `Destination` (`Destinations` enum): `Sensor`, `TestSetups`.
* `DestinationArg` (`object`).
* `Caller` (`object`).
* **`ProgressBarEventArg`**:
* `ProgressBarName` (`string`): Default constructor sets to "Footer".
* `ProgressBarColor` (`Color`).
* `ProgressBarPercentage` (`double`).
* `ProgressBarText` (`string`).
* `ProgressBarVisibility` (`Visibility`).
* Boolean flags: `SetPercentage`, `SetText`, `SetVisibility`.
* **`StatusInfo`**:
* `CurrentState` (`StatusState` enum): `Idle`, `Busy`, `DoneNoError`, `DoneFailed`.
* `IsBusy` (`bool`): Calculated property (true if `Busy`).
* `IsOk` (`bool`).
* `Percentage` (`decimal`).
* `Text` (`string`).
* `ProcessId` (`int`).
* Method: `Unsubscribe(ShowStatus showStatus)` (Resets Text and State).
* **`TabControlSelectionEventArgs`**:
* `Operation` (`TabControlOperation`).
* `Item` (`object`).
### Special Methods
* **`PageErrorEvent.SurfaceApplicationError(string msg)`**
* A `static` helper method that resolves `IEventAg

View File

@@ -0,0 +1,44 @@
---
source_files:
- Common/DTS.CommonCore/Exceptions/OutOfDataException.cs
generated_at: "2026-04-16T12:01:09.381744+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "fdc72f1eddeb3763"
---
# Documentation: OutOfDataException
## 1. Purpose
This module defines a custom exception class, `OutOfDataException`, within the `DTS.Common.Exceptions` namespace. It is designed to signal that a read operation has attempted to access data beyond the available bounds of a stream or buffer. It extends the standard `System.Exception` class by capturing the specific location (`Index`) where the failure occurred, facilitating easier debugging of data parsing or deserialization errors.
## 2. Public Interface
### Class: `OutOfDataException`
Inherits from: `System.Exception`
**Constructor**
```csharp
public OutOfDataException(string ex, long index)
```
Initializes a new instance of the `OutOfDataException` class.
* `string ex`: The message that describes the error (passed to the base `Exception` class).
* `long index`: The position in the data stream or buffer where the out-of-bounds access occurred.
**Properties**
```csharp
public long Index { get; private set; }
```
Gets the numerical index where the data exhaustion was detected. This property is read-only from outside the class.
## 3. Invariants
* **Immutability of Index:** Once an instance of `OutOfDataException` is created, the `Index` property cannot be modified externally (the setter is `private`).
* **Base Type Guarantee:** The type always behaves as a standard CLR exception regarding stack traces and HResult, as it inherits directly from `System.Exception`.
## 4. Dependencies
* **Dependencies:** This module depends on `System` (specifically `System.Exception`).
* **Dependents:** Unknown from the source file alone, but intended for use by data readers, parsers, or stream processors within the `DTS` codebase.
## 5. Gotchas
* **Misleading Parameter Name:** The constructor argument `string ex` uses a naming convention typically reserved for an inner exception object (e.g., `Exception ex`). However, in this signature, it represents the exception message string. Developers might mistakenly expect a constructor signature of `(string message, Exception innerException)`.
* **Serialization Support:** The class does not explicitly implement the `ISerializable` pattern (a serialization constructor is missing). If this exception needs to be serialized (e.g., crossing AppDomain boundaries), the `Index` property may be lost depending on the serialization mechanism used.

View File

@@ -0,0 +1,360 @@
---
source_files:
- Common/DTS.CommonCore/Interface/ITabView.cs
- Common/DTS.CommonCore/Interface/IMainView.cs
- Common/DTS.CommonCore/Interface/IMenuView.cs
- Common/DTS.CommonCore/Interface/IShellView.cs
- Common/DTS.CommonCore/Interface/INavigationView.cs
- Common/DTS.CommonCore/Interface/IViewerShellView.cs
- Common/DTS.CommonCore/Interface/ITabViewModel.cs
- Common/DTS.CommonCore/Interface/IMenuViewModel.cs
- Common/DTS.CommonCore/Interface/INavigationViewModel.cs
- Common/DTS.CommonCore/Interface/IPluginComponent.cs
- Common/DTS.CommonCore/Interface/IShellViewModel.cs
- Common/DTS.CommonCore/Interface/IViewerShellViewModel.cs
- Common/DTS.CommonCore/Interface/IMainViewModel.cs
- Common/DTS.CommonCore/Interface/IAssemblyInfo.cs
- Common/DTS.CommonCore/Interface/IDataPROPage.cs
generated_at: "2026-04-16T11:57:51.242968+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c067eaab6be3056e"
---
# Documentation: DTS.Common.Interface Namespace
## 1. Purpose
This module defines the core abstraction layer for the DTS application's WPF-based UI framework, establishing the view and view-model contracts that implement the Model-View-ViewModel (MVVM) pattern. It provides interfaces for shell containers, navigation components, tab views, menu systems, plugin integration, and DataPRO page definitions. These interfaces enable loose coupling between UI components and their consumers, supporting a modular, plugin-friendly architecture.
---
## 2. Public Interface
### View Interfaces
#### `ITabView`
```csharp
public interface ITabView : IBaseView { }
```
Marker interface for tab view components. Inherits from `IBaseView`.
#### `IMainView`
```csharp
public interface IMainView : IBaseView { }
```
Marker interface for main view components. Inherits from `IBaseView`.
#### `IMenuView`
```csharp
public interface IMenuView : IBaseView { }
```
Marker interface for menu view components. Inherits from `IBaseView`.
#### `IShellView`
```csharp
public interface IShellView : IBaseWindow { }
```
Marker interface for shell window views. **Note:** Inherits from `IBaseWindow`, not `IBaseView`.
#### `INavigationView`
```csharp
public interface INavigationView : IBaseView { }
```
Marker interface for navigation view components. Inherits from `IBaseView`.
#### `IViewerShellView`
```csharp
public interface IViewerShellView : IBaseView { }
```
Marker interface for viewer shell view components. Inherits from `IBaseView`.
---
### ViewModel Interfaces
#### `ITabViewModel`
```csharp
public interface ITabViewModel : IBaseViewModel
{
ITabView View { get; }
}
```
Contract for tab view models. Provides access to the associated `ITabView` instance.
#### `IMenuViewModel`
```csharp
public interface IMenuViewModel : IBaseViewModel
{
IMenuView View { get; }
}
```
Contract for menu view models. Provides access to the associated `IMenuView` instance.
#### `INavigationViewModel`
```csharp
public interface INavigationViewModel : IBaseViewModel
{
INavigationView NavigationView { get; }
}
```
Contract for navigation view models. Provides access to the associated `INavigationView` instance via `NavigationView` property.
#### `IShellViewModel`
```csharp
public interface IShellViewModel : IBaseWindowModel
{
IShellView View { get; }
List<FrameworkElement> GetRegions();
object ContextMainRegion { get; set; }
}
```
Contract for shell view models. Inherits from `IBaseWindowModel`. Provides:
- `View`: The associated `IShellView` instance
- `GetRegions()`: Returns a list of `FrameworkElement` regions
- `ContextMainRegion`: Gets/sets the main region context object
#### `IViewerShellViewModel`
```csharp
public interface IViewerShellViewModel : IBaseViewModel
{
IViewerShellView View { get; }
List<FrameworkElement> GetRegions();
Object ContextMainRegion { get; set; }
}
```
Contract for viewer shell view models. Inherits from `IBaseViewModel`. Provides:
- `View`: The associated `IViewerShellView` instance
- `GetRegions()`: Returns a list of `FrameworkElement` regions
- `ContextMainRegion`: Gets/sets the main region context object
#### `IMainViewModel`
```csharp
public interface IMainViewModel : IBaseViewModel
{
IBaseView View { get; }
object ContextNavigationRegion { get; set; }
object ContextGraphRegion { get; set; }
object ContextTestsRegion { get; set; }
object ContextGraphsRegion { get; set; }
object ContextLegendRegion { get; set; }
object ContextDiagRegion { get; set; }
object ContextStatsRegion { get; set; }
object ContextCursorRegion { get; set; }
object ContextPropertyRegion { get; set; }
List<FrameworkElement> GetRegions();
}
```
Contract for main view models with multiple named regions. Provides context properties for: Navigation, Graph, Tests, Graphs, Legend, Diag, Stats, Cursor, and Property regions.
---
### Plugin Interface
#### `IPluginComponent`
```csharp
public interface IPluginComponent
{
string ProgId { get; }
}
```
Contract for plugin modules. The `ProgId` property provides a program identifier used to instantiate the plugin object.
---
### Assembly Metadata Interfaces and Attributes
#### `IAssemblyImageAttribute`
```csharp
public interface IAssemblyImageAttribute
{
string AssemblyName { get; }
BitmapImage AssemblyImage { get; }
eAssemblyRegion AssemblyRegion { get; }
Type GetType();
BitmapImage GetAssemblyImage();
string GetAssemblyName();
eAssemblyRegion GetAssemblyRegion();
}
```
#### `ImageAttribute` (Abstract)
```csharp
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public abstract class ImageAttribute : Attribute, IAssemblyImageAttribute
{
public abstract string AssemblyName { get; }
public abstract string AssemblyGroup { get; }
public abstract eAssemblyRegion AssemblyRegion { get; }
public abstract BitmapImage AssemblyImage { get; }
public abstract Type GetAttributeType();
public abstract BitmapImage GetAssemblyImage();
public abstract string GetAssemblyName();
public abstract string GetAssemblyGroup();
public abstract eAssemblyRegion GetAssemblyRegion();
}
```
Abstract attribute for assembly-level image metadata. Restricted to single instance per assembly.
#### `IAssemblyNameAttribute`
```csharp
public interface IAssemblyNameAttribute
{
String AssemblyName { get; }
Type GetType();
string GetAssemblyName();
}
```
#### `TextAttribute` (Abstract)
```csharp
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public abstract class TextAttribute : Attribute, IAssemblyNameAttribute
{
public abstract string AssemblyName { get; }
public abstract Type GetAttributeType();
public abstract string GetAssemblyName();
}
```
Abstract attribute for assembly-level name metadata. Restricted to single instance per assembly.
---
### DataPRO Page Interface
#### `IDataPROPage`
```csharp
public interface IDataPROPage : INotifyPropertyChanged
```
Comprehensive interface for DataPRO UI pages. Key members include:
**Properties:**
| Property | Type |
|----------|------|
| `TestSetupChangeButtonVisible` | `Visibility` |
| `AutomaticModeStatusVisible` | `Visibility` |
| `PageName` | `string` |
| `PageImage` | `ImageSource` |
| `IsAdd` | `bool` |
| `UsesModifyEnhancements` | `bool` |
| `EditIDString` | `string` |
| `AddIDString` | `string` |
| `ModifiedObjectName` | `string` |
| `AutomaticProgression` | `bool` |
| `RecoveryDownloadMode` | `bool` |
| `UniqueId` | `string` (read-only) |
| `TileColor` | `Color` (read-only) |
| `CurrentSearchTerm` | `string` |
| `UsesNAVControl` | `bool` |
| `UsesSearchControl` | `bool` |
| `UsesSelectControl` | `bool` |
| `HasBackButton` | `bool` |
| `HasRefreshButton` | `bool` |
| `HasCancelButton` | `bool` |
| `HasSaveButton` | `bool` |
| `HasNextButton` | `bool` |
| `ContentBackgroundColor` | `Color` |
| `MainContent` | `object` |
| `ControlInOnSetActive` | `bool` |
**Methods:**
- `string GetName()`
- `long GetID()`
- `void SetID(long id)`
- `void SetTileColor(Color c)`
- `void SavePage(object obj)`
- `void ClearSearchTerm()`
- `void SetEnabled(bool bEnable)`
- `void VerifyProgress(object o)`
- `void SaveAndExit()`
- `void RefreshButtonPressed()`
- `void SetDoneButtonIsEnabled(bool bEnabled)`
- `void SetBackButtonIsEnabled(bool bEnabled)`
- `void DoneButtonPress()`
- `void SetCancelEnabled(bool bEnabled)`
- `ContentControl GetMainContentControl()`
- `void SetReturning()`
- `bool Validate(ref List<string> errors, ref List<string> warnings, bool displayWindow)`
- `bool OKToProceed()`
- `void FormClosing(Action OnComplete = null)`
- `void OnSetActive()`
- `void UnSet()`
- `void SetCurrentItem(object o)`
- `void SetupPageAvailable()`
#### `DataProPageProperties` (Enum)
```csharp
public enum DataProPageProperties
{
UsesModifyEnhancements,
TestSetupChangeButtonVisible,
AutomaticModeStatusVisible,
PageName,
PageImage,
IsAdd,
EditIDString,
AddIDString,
ModifiedObjectName,
AutomaticProgression,
RecoveryDownloadMode,
UsesNAVControl,
UsesSearchControl,
UsesSelectControl,
HasBackButton,
HasRefreshButton,
HasCancelButton,
HasSaveButton,
HasNextButton,
ContentBackgroundColor,
MainContent,
GenerateReportsVisible
}
```
Enumeration of mutable `IDataPROPage` properties that may require external observation or reaction.
---
## 3. Invariants
- **View Hierarchy**: All view interfaces (`ITabView`, `IMainView`, `IMenuView`, `INavigationView`, `IViewerShellView`) inherit from `IBaseView`, except `IShellView` which inherits from `IBaseWindow`.
- **ViewModel Hierarchy**: All view-model interfaces inherit from `IBaseViewModel`, except `IShellViewModel` which inherits from `IBaseWindowModel`.
- **Attribute Restrictions**: `ImageAttribute` and `TextAttribute` are decorated with `[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]`, meaning they can only be applied to assemblies and only one instance of each is permitted per assembly.
- **Abstract Attributes**: Both `ImageAttribute` and `TextAttribute` are abstract classes; concrete implementations must override all abstract members.
- **IDataPROPage Identity**: `UniqueId` and `TileColor` are read-only properties; values must be set via `SetID(long)` and `SetTileColor(Color)` methods respectively.
- **IDataPROPage Validation**: The `Validate` method accepts errors and warnings by reference, suggesting callers must initialize these lists before invocation.
---
## 4. Dependencies
### External Dependencies (Inferred from imports)
- **`DTS.Common.Base`** - Provides base interfaces: `IBaseView`, `IBaseWindow`, `IBaseViewModel`, `IBaseWindowModel`
- **`System.Windows`** - For `FrameworkElement`, `Visibility`, `ContentControl`, `DependencyObject`, `UIElement`
- **`System.Windows.Media`** - For `ImageSource`, `Color`
- **`System.Windows.Media.Imaging`** - For `BitmapImage`
- **`System.ComponentModel`** - For `INotifyPropertyChanged`
- **`System.Collections.Generic`** - For `List<T>`
- **`System`** - For `Type`, `Object`, `String`, `Action`, `Attribute`
### Consumers
- Unknown from source alone. These interfaces are likely consumed by:
- Concrete view and view-model implementations
- Plugin modules implementing `IPluginComponent`
- Assembly metadata classes deriving from `ImageAttribute` or `TextAttribute`
- Page implementations conforming to `IDataPROPage`
---
## 5. Gotchas
1. **IShellView Base Interface Difference**: `IShellView` inherits from `IBaseWindow` while all other view interfaces inherit from `IBaseView`. This suggests shell views represent top-level windows rather than embedded controls.
2. **INavigationViewModel Property Naming Inconsistency**: `INavigationViewModel` exposes `NavigationView` property, while `ITabViewModel`, `IMenuViewModel`, `IViewerShellViewModel`, and `IShellViewModel` expose `View` property. This naming inconsistency may cause confusion.
3. **IDataPROPage Interface Size**: The `IDataPROPage` interface is exceptionally large (30+ members), violating the Interface Segregation Principle. Implementers must provide all members even if some are unused.
4. **Mixed Property/Method Patterns in IDataPROPage**: Some state is accessed via properties (e.g., `TileColor` is read-only property) while similar state requires methods (e.g., `SetTileColor(Color)`). The `UniqueId` property has no corresponding setter method visible, but `SetID(long)` exists for a numeric ID.
5. **eAssemblyRegion Type Undefined**: The `eAssemblyRegion` enum type is referenced in `IAssemblyImageAttribute` and `ImageAttribute` but is not defined in the provided source files. Its definition must exist elsewhere in `DTS.Common.Base` or another namespace.
6. **IDataPROPage.Validate Ref Parameters**: The `Validate` method uses `ref` parameters for error/warning lists, requiring callers to initialize collections before calling. Failure to do so would result in compiler error or runtime issues.

View File

@@ -0,0 +1,126 @@
---
source_files:
- Common/DTS.CommonCore/Interface/BuildTestSetup/IBuildTestSetup.cs
generated_at: "2026-04-16T12:17:19.769596+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5d29553a439a7fc1"
---
# Documentation: IBuildTestSetup
## 1. Purpose
The `IBuildTestSetup` interface defines a data contract for configuring a "Build Test Setup" within the DTS system. It appears to model the configuration state for a Data Acquisition System (DAS) test execution, encapsulating settings for hardware checks (voltage, squib resistance, sensors), data acquisition parameters (sampling rates, triggers), data export formats (CSV, HDF, ISO, etc.), and user interface behaviors. By inheriting from `INotifyPropertyChanged`, it is designed to support data-binding scenarios, likely for a configuration UI or view model where property changes must notify observers.
## 2. Public Interface
The interface contains the following members. All properties are read/write.
**Identification & Metadata**
* `string DASSerialNumber { get; set; }`: Serial number of the DAS unit.
* `string SetupName { get; set; }`: Name of the test setup configuration.
* `string SetupDescription { get; set; }`: Description of the test setup.
* `string LastModified { get; set; }`: Timestamp of the last modification.
* `string LastModifiedBy { get; set; }`: User who last modified the setup.
**Execution Modes & Timing**
* `string AutomaticMode { get; set; }`: Setting for automatic operation mode.
* `string AutomaticModeDelay { get; set; }`: Delay duration for automatic mode.
* `string RecordingMode { get; set; }`: Defines how recording is handled.
* `string SamplesPerSecond { get; set; }`: Sampling rate configuration.
* `string PreTriggerSeconds { get; set; }`: Duration of pre-trigger data capture.
* `string PostTriggerSeconds { get; set; }`: Duration of post-trigger data capture.
* `string NumberOfEvents { get; set; }`: Number of events to capture.
* `string WakeUpMotionTimeout { get; set; }`: Timeout setting for wake-up motion.
* `string Streaming { get; set; }`: Streaming configuration.
**User Interface & Behavior**
* `string ViewRealtime { get; set; }`: Flag/setting to view data in realtime.
* `string WarnOnBatteryFail { get; set; }`: Flag to warn if battery fails.
* `string StrictDiagnostics { get; set; }`: Enables strict diagnostic checks.
* `string RequireConfirmationOnErrors { get; set; }`: UI behavior for error handling.
* `string QuitTestWithoutWarning { get; set; }`: Flag to suppress quit warnings.
* `string CommonStatusLine { get; set; }`: Status line text.
* `string RealtimeCharts { get; set; }`: Configuration for realtime charts.
**Hardware Checks & Diagnostics**
* `string PerformArmChecklist { get; set; }`: Flag to perform arming checklist.
* `string CheckInputVoltage { get; set; }`: Enables input voltage check.
* `string CheckBatteryVoltage { get; set; }`: Enables battery voltage check.
* `string CheckSquibResistance { get; set; }`: Enables squib resistance check.
* `string MeasureSquibResistances { get; set; }`: Enables squib resistance measurement.
* `string CheckSensorIds { get; set; }`: Enables sensor ID verification.
* `string CheckStartEventLines { get; set; }`: Enables start event line checks.
* `string CheckTiltSensor { get; set; }`: Enables tilt sensor check.
* `string CheckTemperature { get; set; }`: Enables temperature check.
* `string RequireAllUnitsPassArmCheckList { get; set; }`: Validation rule for arming.
* `string PostTestDiagnostics { get; set; }`: Post-test diagnostic settings.
* `string CalibrationBehavior { get; set; }`: Defines calibration actions.
* `string TriggerCheckStep { get; set; }`: Trigger check configuration.
**Data Management (Download/ROI/Upload)**
* `string ROIDownload { get; set; }`: Region of Interest download setting.
* `string ViewROIDownload { get; set; }`: UI setting for viewing ROI downloads.
* `string DownloadAll { get; set; }`: Flag to download all data.
* `string ViewDownloadAll { get; set; }`: UI setting for viewing full downloads.
* `string ROIStart { get; set; }`: Start time/point for Region of Interest.
* `string ROIEnd { get; set; }`: End time/point for Region of Interest.
* `string DownloadFolder { get; set; }`: Target directory for downloads.
* `string UploadData { get; set; }`: Flag to enable data upload.
* `string UploadDataFolder { get; set; }`: Source directory for uploads.
**Export Configuration**
* `string Export { get; set; }`: General export setting.
* `string ExportFolder { get; set; }`: Destination directory for exports.
* `string ExportCh10FilteredEUDesired { get; set; }`: Export flag for filtered Ch10 EU data.
* `string ExportChryslerDDASDesired { get; set; }`: Export flag for Chrysler DDAS format.
* `string ExportCSVADCDesired { get; set; }`: Export flag for CSV ADC format.
* `string ExportCSVFilteredDesired { get; set; }`: Export flag for filtered CSV.
* `string ExportCSVMVDesired { get; set; }`: Export flag for CSV MV format.
* `string ExportCSVUnfilteredDesired { get; set; }`: Export flag for unfiltered CSV.
* `string ExportDiademADCDesired { get; set; }`: Export flag for Diadem ADC format.
* `string ExportHDFADCDesired { get; set; }`: Export flag for HDF ADC format.
* `string ExportHDFMVDesired { get; set; }`: Export flag for HDF MV format.
* `string ExportHDFUnfilteredDesired { get; set; }`: Export flag for unfiltered HDF.
* `string ExportISOFilteredDesired { get; set; }`: Export flag for filtered ISO format.
* `string ExportISOUnfilteredDesired { get; set; }`: Export flag for unfiltered ISO format.
* `string ExportRDFADCDesired { get; set; }`: Export flag for RDF ADC format.
* `string ExportTDASADCDesired { get; set; }`: Export flag for TDAS ADC format.
* `string ExportTDMSADCDesired { get; set; }`: Export flag for TDMS ADC format.
* `string ExportToyotaUnfilteredDesired { get; set; }`: Export flag for unfiltered Toyota format.
* `string ExportTSVFilteredDesired { get; set; }`: Export flag for filtered TSV.
* `string ExportTSVUnfilteredDesired { get; set; }`: Export flag for unfiltered TSV.
* `string ExportXLSXFilteredDesired { get; set; }`: Export flag for filtered XLSX.
* `string ExportXLSXUnfilteredDesired { get; set; }`: Export flag for unfiltered XLSX.
* `string ExportASCDesired { get; set; }`: Export flag for ASC format.
**Miscellaneous Configuration**
* `string AllowSensorIdToBlankChannel { get; set; }`: Permission setting for sensor IDs.
* `string ExcitationWarmupTimeMS { get; set; }`: Warmup time in milliseconds.
* `string UseLabDetails { get; set; }`: Flag to use lab details.
* `string UseCustomerDetails { get; set; }`: Flag to use customer details.
* `string UseTestEngineerDetails { get; set; }`: Flag to use test engineer details.
* `string AllowMissingSensors { get; set; }`: Permission to proceed with missing sensors.
* `string SuppressMissingSensorsWarning { get; set; }`: UI warning suppression.
* `string NotAllChannelsRealTime { get; set; }`: Setting regarding realtime channel limits.
* `string NotAllChannelsViewer { get; set; }`: Setting regarding viewer channel limits.
* `string UserTags { get; set; }`: User-defined tags for the setup.
* `string AutoArm { get; set; }`: Auto-arm feature setting.
**Complex Types**
* `List<GroupXMLClass> Groups { get; set; }`: A list of groups, presumably defining channel groups or sensor groupings, utilizing the `DTS.Common.XMLUtils.GroupXMLClass` type.
## 3. Invariants
* **INotifyPropertyChanged Contract:** Any class implementing `IBuildTestSetup` must implement the `PropertyChanged` event (from `System.ComponentModel`). Consumers expect this event to be raised when any of the string properties or the `Groups` list is modified.
* **String-based Values:** Despite many properties representing numeric values (e.g., `SamplesPerSecond`), boolean flags (e.g., `CheckInputVoltage`), or enumerations, the interface defines them strictly as `string`. Implementations may require parsing/validation logic to convert these to appropriate types for internal use.
## 4. Dependencies
* **System.ComponentModel:** Required for the `INotifyPropertyChanged` interface.
* **System.Collections.Generic:** Required for the `List` generic collection used by the `Groups` property.
* **DTS.Common.XMLUtils:** Required for the `GroupXMLClass` type used in the `Groups` property.
* **Consumers:** Unknown from the source alone, but likely includes ViewModels, Serializers (XML/JSON), and Test Configuration managers within the DTS ecosystem.
## 5. Gotchas
* **"Stringly-Typed" Configuration:** The interface uses `string` for almost all properties, including those that logically represent numbers (`ExcitationWarmupTimeMS`, `SamplesPerSecond`) or boolean flags (`AutoArm`, `CheckBatteryVoltage`). This suggests a lack of strong typing which could lead to runtime parsing errors or invalid state representation (e.g., setting `SamplesPerSecond` to "abc").
* **Commented-Out Properties:** The source contains several commented-out properties (e.g., `ExportFormat`, `ExportCh10UnfilteredEUDesired`, `ExportSomatFilteredDesired`). This indicates legacy features or deprecated export formats that were removed from the interface contract but not cleaned up, which may cause confusion regarding supported features.
* **Naming Inconsistencies:** Some export properties end in `Desired` (e.g., `ExportCSVADCDesired`), implying a request or preference, whereas others (like `Export`) do not. The semantic difference between `Export` and the specific `Export[Format]Desired` properties is not defined in the interface.

View File

@@ -0,0 +1,279 @@
---
source_files:
- Common/DTS.CommonCore/Interface/Channels/IChannelSettingRecord.cs
- Common/DTS.CommonCore/Interface/Channels/IGroupChannelSettingRecord.cs
- Common/DTS.CommonCore/Interface/Channels/IChannelCode.cs
- Common/DTS.CommonCore/Interface/Channels/IChannelSetting.cs
- Common/DTS.CommonCore/Interface/Channels/IChannelDbRecord.cs
- Common/DTS.CommonCore/Interface/Channels/IGroupChannel.cs
generated_at: "2026-04-16T12:23:05.212303+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "cbc4fb29d29bc466"
---
# Channel Interfaces Documentation
## 1. Purpose
This module defines the core abstraction layer for channel management in the DTS (Data Test System) application. It provides interfaces for channel configuration, settings persistence, and group channel operations. These interfaces serve as the contract between the database layer, business logic, and UI components for managing physical measurement channels, sensor assignments, hardware configurations, and various channel types (analog, digital, squib, UART, stream, etc.) within test setups.
---
## 2. Public Interface
### IChannelSettingRecord
Simple data contract for a channel setting type definition.
| Member | Type | Description |
|--------|------|-------------|
| `Id` | `int` | Unique identifier for the setting record. |
| `SettingName` | `string` | Name of the setting. |
| `DefaultValue` | `string` | Default value for the setting. |
---
### IGroupChannelSettingRecord
Associates a setting value with a specific channel.
| Member | Type | Description |
|--------|------|-------------|
| `ChannelId` | `long` | ID of the channel this setting applies to. |
| `SettingId` | `int` | ID of the setting type. |
| `SettingValue` | `string` | The value assigned to this setting. |
---
### IChannelCode
Represents a channel code with its metadata.
| Member | Type | Description |
|--------|------|-------------|
| `Id` | `int` | Unique identifier (read-only). |
| `Code` | `string` | The code string (read-only). |
| `Name` | `string` | Display name (read-only). |
| `CodeType` | `ChannelEnumsAndConstants.ChannelCodeType` | Type classification of the code (read-only). |
---
### IChannelSetting
Represents a configurable setting on a channel with typed value access.
| Member | Type | Description |
|--------|------|-------------|
| `ChannelId` | `long` | ID of the associated channel. |
| `SettingTypeId` | `int` | Type identifier for this setting (read-only). |
| `SettingName` | `string` | Name of the setting (read-only). |
| `DefaultValue` | `string` | Default value (read-only). |
| `Value` | `string` | Current string value. |
| `IntValue` | `int` | Integer representation of the value. |
| `DoubleValue` | `double` | Double representation of the value. |
| `BoolValue` | `bool` | Boolean representation of the value. |
| `Clone()` | `IChannelSetting` | Creates a copy of this setting. |
---
### IChannelDbRecord
Interface describing a Channel record as stored in the database. Includes Entity Framework data annotations.
| Member | Type | Description |
|--------|------|-------------|
| `Id` | `long` | Primary key, mapped to column "Id". |
| `GroupId` | `int` | ID of the group this channel belongs to. |
| `IsoCode` | `string` | ISO standard code for the channel. |
| `IsoChannelName` | `string` | ISO standard channel name. |
| `UserCode` | `string` | User-defined code. |
| `UserChannelName` | `string` | User-defined channel name. |
| `DASId` | `int` | Data Acquisition System ID. |
| `DASChannelIndex` | `int` | Physical channel index on the DAS. |
| `GroupChannelOrder` | `int` | Ordering within the group. |
| `TestSetupOrder` | `int` | Ordering within the test setup. |
| `SensorId` | `int` | ID of the assigned sensor. |
| `Disabled` | `bool` | Whether the channel is disabled. |
| `LastModified` | `DateTime` | Timestamp of last modification. |
| `LastModifiedBy` | `string` | User who last modified the record. |
---
### IGroupChannel
Primary interface for channel operations, extending `IChannelDbRecord` and `IComparable<IGroupChannel>`. Contains extensive properties and methods for channel configuration.
#### Key Properties
| Member | Type | Description |
|--------|------|-------------|
| `RangeLowG` | `SensorConstants.AvailableRangesLowG` | Low-G range setting. |
| `VoltageInsertionSensor` | `bool` | Indicates if channel has a calibration-less voltage measurement channel (read-only). |
| `RangeModifiableSensorLowG` | `bool` | Whether channel has an embedded range modifiable low-g sensor (read-only). |
| `RangeModifiableSensorARS` | `bool` | Whether channel has an embedded range modifiable ARS sensor (read-only). |
| `AvailableInitialOffsets` | `InitialOffset[]` | Available initial offsets (requires sensor with calibration). |
| `IEPESupport` | `string` | IEPE support status (read-only). |
| `Group` | `IGroup` | The group this channel belongs to. |
| `GroupName` | `string` | Display name of the group. |
| `GroupNameValid` | `bool` | Whether the group name is valid. |
| `IsoCodeValid` | `bool` | Whether ISO code is set. |
| `IsoChannelNameValid` | `bool` | Whether ISO channel name is set. |
| `UserCodeValid` | `bool` | Whether user code is set. |
| `UserChannelNameValid` | `bool` | Whether user channel name is set. |
| `HardwareValid` | `bool` | Whether hardware has been assigned (read-only). |
| `HardwareId` | `string` | Legacy hardware identifier in format `[das serial]:[channel index]`. |
| `TestSampleRate` | `double` | Sample rate of the associated DAS. |
| `SensorValid` | `bool` | Whether a sensor has been assigned (read-only). |
| `IsDisabled` | `bool` | Whether channel should be used for data collection. |
| `CanMoveUp` / `CanMoveDown` | `bool` | UI state for ordering controls. |
| `DeleteShouldBeEnabled` | `bool` | UI state for delete button. |
| `RemoveSensorVisibility` | `System.Windows.Visibility` | UI visibility state. |
| `PasteCommand` | `ICommand` | Command for paste operations. |
| `ChannelSettings` | `IChannelSetting[]` | Array of channel settings (range, polarity, etc.). |
| `Hardware` | `string` | UI display string for hardware. |
| `Sensor` | `string` | UI display string for sensor (read-only). |
| `SensorData` | `ISensorData` | Sensor data object (read-only). |
| `HardwareChannel` | `IHardwareChannel` | Assigned hardware channel (read-only). |
| `DragAndDropItem` | `IDragAndDropItem` | Drag-and-drop item (read-only). |
| `SensorCalibration` | `ISensorCalibration` | Sensor calibration data (read-only). |
| `HasEID` | `bool` | Whether channel has EID (read-only). |
| `Range` | `double` | Range setting value. |
| `Capacity` | `double` | Capacity of the sensor (read-only). |
| `FilterClass` | `IFilterClass` | Filter class setting (FB 13120). |
| `Polarity` | `string` | Polarity setting. |
| `Units` | `string` | Units (read-only). |
| `ZeroMethod` | `ZeroMethodType` | Zero method type. |
| `ZeroMethodStart` / `ZeroMethodEnd` | `double` | Zero method time range. |
| `Sensitivity` | `string` | Sensitivity (read-only). |
| `InitialOffset` | `InitialOffset` | Initial offset setting. |
#### Squib/Digital Output Properties
| Member | Type | Description |
|--------|------|-------------|
| `SquibLimitDuration` | `bool` | Whether squib duration is limited. |
| `SquibDuration` | `double` | Squib duration value. |
| `SquibDelay` | `double?` | Squib delay (nullable for UI purposes - FB 14623). |
| `SquibCurrent` | `double` | Squib current value. |
| `SquibFireMode` | `SquibFireMode` | Fire mode setting. |
| `DigitalOutLimitDuration` | `bool` | Whether digital out duration is limited. |
| `DigitalOutDuration` | `double` | Digital out duration. |
| `DigitalOutDurationMax` | `double` | Maximum allowed digital out duration (FB 28107). |
| `DigitalOutDelay` | `double` | Digital out delay. |
| `DigitalOutputMode` | `DigitalOutputModes` | Output mode setting. |
| `DigitalInputMode` | `DigitalInputModes` | Input mode setting. |
| `ActiveValue` | `string` | Active value setting. |
| `DefaultValue` | `string` | Default value setting. |
#### UART Properties
| Member | Type | Description |
|--------|------|-------------|
| `UartBaudRate` | `uint` | Baud rate. |
| `UartDataBits` | `uint` | Data bits. |
| `UartStopBits` | `StopBits` | Stop bits configuration. |
| `UartParity` | `Parity` | Parity configuration. |
| `UartFlowControl` | `Handshake` | Flow control (read-only, always NONE per FB 30486). |
| `UartDataFormat` | `UartDataFormat` | Data format. |
#### Stream Properties
| Member | Type | Description |
|--------|------|-------------|
| `StreamInUDPAddress` | `string` | UDP address for stream input. |
| `StreamOutUDPProfile` | `UDPStreamProfile` | UDP profile for stream output. |
| `StreamOutUDPAddress` | `string` | UDP address for stream output. |
| `StreamOutUDPTimeChannelId` | `ushort` | Time channel ID for UDP streaming. |
| `StreamOutUDPDataChannelId` | `ushort` | Data channel ID for UDP streaming. |
| `StreamOutUDPTmNSConfig` | `string` | TMNS configuration. |
| `StreamOutIRIGTimeDataPacketIntervalMs` | `ushort` | IRIG data packet interval in ms. |
| `StreamOutTMATSIntervalMs` | `ushort` | TMATS interval while streaming (FB 29987). |
#### Channel Type Detection Properties (all read-only)
| Member | Returns `true` when |
|--------|---------------------|
| `IsAnalog` | Channel has analog sensor assigned (or non-blank without sensor). |
| `IsSquib` | Channel has squib sensor assigned (or non-blank without sensor). |
| `IsDigitalIn` | Channel has digital input sensor assigned (or non-blank without sensor). |
| `IsDigitalOut` | Channel has digital output sensor assigned (or non-blank without sensor). |
| `IsClock` | Channel is from an RTC module. |
| `IsUart` | Channel is from a UART module. |
| `IsStreamIn` | Channel is from a stream-in module. |
| `IsStreamOut` | Channel is from a stream-out module. |
#### Difference Tracking Properties
| Member | Type | Purpose |
|--------|------|---------|
| `IsRangeDifferent` | `bool` | Tracks range differences. |
| `IsFilterClassDifferent` | `bool` | Tracks filter class differences. |
| `IsPolarityDifferent` | `bool` | Tracks polarity differences. |
| `IsZeroMethodDifferent` | `bool` | Tracks zero method differences. |
| `IsZeroMethodStartDifferent` | `bool` | Tracks zero method start differences. |
| `IsZeroMethodEndDifferent` | `bool` | Tracks zero method end differences. |
| `IsInitialOffsetDifferent` | `bool` | Tracks initial offset differences. |
| `IsSquibFireModeDifferent` | `bool` | Tracks squib fire mode differences. |
| `IsSquibDelayDifferent` | `bool` | Tracks squib delay differences. |
| `IsSquibLimitDurationDifferent` | `bool` | Tracks squib limit duration differences. |
| `IsSquibDurationDifferent` | `bool` | Tracks squib duration differences. |
| `IsSquibCurrentDifferent` | `bool` | Tracks squib current differences. |
| `IsDigitalOutputModeDifferent` | `bool` | Tracks digital output mode differences. |
| `IsDigitalOutDelayDifferent` | `bool` | Tracks digital out delay differences. |
| `IsDigitalOutLimitDurationDifferent` | `bool` | Tracks digital out limit duration differences. |
| `IsDigitalOutDurationDifferent` | `bool` | Tracks digital out duration differences. |
| `IsDigitalInputModeDifferent` | `bool` | Tracks digital input mode differences. |
| `IsDefaultValueDifferent` | `bool` | Tracks default value differences. |
| `IsActiveValueDifferent` | `bool` | Tracks active value differences. |
| `BorderShouldShowOutOfDate` | `bool` | UI state for out-of-date indicator. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void SetHardwareChannel(IHardwareChannel hardwareChannel)` | Assigns a hardware channel to this channel. |
| `void SetSensor(IDragAndDropItem sensor, IChannelSetting[] channelDefaults, bool applySensorDataToBlankChannels)` | Assigns a sensor with optional defaults application. |
| `bool CompareValue(string property)` | Compares a property value. |
| `bool SetDifferent(string property)` | Marks a property as different. |
| `void SetNotDifferent()` | Clears all difference flags. |
| `void SetRange(CACOption option)` | Sets the range based on an option. |
| `bool IsBlank()` | Returns `true` if channel is a new, non-edited channel. |
| `void Clear()` | Clears hardware and sensor assignments. |
| `bool Filter(string term)` | Returns `true` if channel contains the search term. |
| `string GetChannelName(IsoViewMode isoViewMode)` | Returns channel name based on view mode. |
| `string GetChannelCode(IsoViewMode isoViewMode)` | Returns channel code based on view mode. |
| `void Copy(IGroupChannel groupChannel)` | Creates a memory copy from another channel. |
| `void SetSensorCalibration(ISensorCalibration calibration)` | Sets the sensor calibration. |
| `void SetSensorData(ISensorData sensorData, IDragAndDropItem dragAndDropItem, bool decideSettings = false)` | Sets sensor data with optional settings decision. |
| `IFilterClass GetFilterClassFromISOCode(ISoftwareFilter[] filters, string isoCode)` | Gets filter class from ISO code (FB 15574, FB 13120). |
| `void SetSettingsFromSensor(ISensorData sd)` | Sets channel settings from sensor settings. |
| `string GetChangeList(ISensorData sensor)` | Returns list of parameter differences vs sensor. |
#### Other Members
| Member | Type | Description |
|--------|------|-------------|
| `CoerceISOCodeFunc` | `CoerceISOCodeDelegate` | Function for ISO code coercion. |
| `ChannelStatus` | `UIItemStatus` | Status considering completeness and sensor calibration. |
---
## 3. Invariants
1. **Comparability**: `IGroupChannel` implements `IComparable<IGroupChannel>`, implying ordering semantics must be defined (likely by `GroupChannelOrder` or `TestSetupOrder`).
2. **IEPE Support Logic**: `IEPESupport` follows a priority chain:
- If sensor assigned → depends on sensor bridge
- If no sensor but hardware assigned → depends on hardware channel support
- If neither assigned → IEPE is available
3. **Channel Type Detection Fallback**: Properties `IsAnalog`, `IsSquib`, `IsDigitalIn`, `IsDigitalOut` return `true` for non-blank channels even without a sensor assigned. They return `false` only for blank channels.
4. **Initial Offsets Dependency**: `AvailableInitialOffsets` requires a sensor with calibration to be assigned.
5. **Database Mapping**: `IChannelDbRecord` properties are explicitly mapped to database columns via `[Column("...")]` attributes.
6. **Primary Key**: `IChannelDbRecord.Id` is marked with `[Key]` attribute.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Enums.Channels` - Channel-related enumerations
- `DTS.Common.Enums

View File

@@ -0,0 +1,69 @@
---
source_files:
- Common/DTS.CommonCore/Interface/CheckChannels/ICheckChannelsView.cs
- Common/DTS.CommonCore/Interface/CheckChannels/ICheckChannelsViewModel.cs
- Common/DTS.CommonCore/Interface/CheckChannels/ICheckChannelsMenuView.cs
- Common/DTS.CommonCore/Interface/CheckChannels/ICheckChannelsMenuViewModel.cs
generated_at: "2026-04-16T12:13:50.837632+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "3a5d65945568970d"
---
# Documentation: CheckChannels Interfaces
## 1. Purpose
This module defines four interfaces for the "CheckChannels" feature within the DTS system, following the Model-View-ViewModel (MVVM) architectural pattern. These interfaces establish contracts for the main CheckChannels view and its associated ribbon menu view, enabling loose coupling between UI components and facilitating dependency injection. The interfaces serve as type markers that extend base view and viewmodel abstractions, allowing the CheckChannels feature to integrate consistently with the broader application framework.
## 2. Public Interface
### ICheckChannelsView
```csharp
namespace DTS.Common.Interface
public interface ICheckChannelsView : IBaseView { }
```
A marker interface for the main CheckChannels view. Inherits from `IBaseView` (defined in `DTS.Common.Base`). No additional members are defined.
### ICheckChannelsViewModel
```csharp
namespace DTS.Common.Interface
public interface ICheckChannelsViewModel : IBaseViewModel { }
```
A marker interface for the CheckChannels viewmodel. Inherits from `IBaseViewModel` (defined in `DTS.Common.Base`). No additional members are defined.
### ICheckChannelsMenuView
```csharp
namespace DTS.Common.Interface
public interface ICheckChannelsMenuView : IRibbonView { }
```
A marker interface for the CheckChannels ribbon menu view. Inherits from `IRibbonView` (defined in `DTS.Common.RibbonControl`). No additional members are defined.
### ICheckChannelsMenuViewModel
```csharp
namespace DTS.Common.Interface
public interface ICheckChannelsMenuViewModel : IRibbonViewModel { }
```
A marker interface for the CheckChannels ribbon menu viewmodel. Inherits from `IRibbonViewModel` (defined in `DTS.Common.RibbonControl`). No additional members are defined.
## 3. Invariants
- All four interfaces are empty marker interfaces; they define no members beyond those inherited from their base interfaces.
- Each view interface has a corresponding viewmodel interface following the naming convention `ICheckChannels[Menu]View` / `ICheckChannels[Menu]ViewModel`.
- The main CheckChannels components inherit from base view/viewmodel types (`IBaseView`, `IBaseViewModel`), while the menu components inherit from ribbon-specific types (`IRibbonView`, `IRibbonViewModel`).
- All interfaces reside in the `DTS.Common.Interface` namespace.
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` — provides `IBaseView` and `IBaseViewModel` base interfaces
- `DTS.Common.RibbonControl` — provides `IRibbonView` and `IRibbonViewModel` base interfaces
### What depends on this module:
- **Unclear from source alone.** Concrete implementations of these interfaces would exist elsewhere in the codebase, likely in view and viewmodel classes within a CheckChannels feature module. The consumers would typically be dependency injection containers and navigation/routing systems.
## 5. Gotchas
- **Empty marker interfaces**: These interfaces define no custom members. All behavior contracts come from the parent interfaces (`IBaseView`, `IBaseViewModel`, `IRibbonView`, `IRibbonViewModel`). Developers implementing these interfaces must consult those base definitions to understand required members.
- **Separate menu hierarchy**: The `ICheckChannelsMenuView` and `ICheckChannelsMenuViewModel` inherit from ribbon-specific base types rather than the general base types used by the main view/viewmodel pair. This suggests the menu components integrate with a specialized ribbon control system.
- **Purpose unclear from source**: The specific functionality of the "CheckChannels" feature cannot be determined from these interface definitions alone. The name suggests channel verification or monitoring, but the actual behavior is not documented here.

View File

@@ -0,0 +1,47 @@
---
source_files:
- Common/DTS.CommonCore/Interface/CheckTrigger/ICheckTriggerView.cs
- Common/DTS.CommonCore/Interface/CheckTrigger/ICheckTriggerViewModel.cs
generated_at: "2026-04-16T12:07:28.882495+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b59a55831fe5a086"
---
# Documentation: ICheckTriggerView and ICheckTriggerViewModel
## 1. Purpose
This module defines two marker interfaces, `ICheckTriggerView` and `ICheckTriggerViewModel`, which serve as contracts for the View and ViewModel components of a "CheckTrigger" feature within an MVVM (Model-View-ViewModel) architecture. These interfaces exist to establish type identity and hierarchy within the system, allowing components to be identified as belonging to the CheckTrigger subsystem while inheriting base behavior from core framework types.
## 2. Public Interface
### `ICheckTriggerView`
- **Namespace:** `DTS.Common.Interface`
- **Signature:** `public interface ICheckTriggerView : IBaseView { }`
- **Description:** An empty marker interface extending `IBaseView`. Declares no members of its own; its purpose is purely typological, allowing implementations to be identified as CheckTrigger-specific views.
### `ICheckTriggerViewModel`
- **Namespace:** `DTS.Common.Interface`
- **Signature:** `public interface ICheckTriggerViewModel : IBaseViewModel { }`
- **Description:** An empty marker interface extending `IBaseViewModel`. Declares no members of its own; its purpose is purely typological, allowing implementations to be identified as CheckTrigger-specific view models.
## 3. Invariants
- Any class implementing `ICheckTriggerView` must also fulfill the contract of `IBaseView` (the specifics of which are not visible in the provided source).
- Any class implementing `ICheckTriggerViewModel` must also fulfill the contract of `IBaseViewModel` (the specifics of which are not visible in the provided source).
- Both interfaces are sealed in the sense that they add no additional members beyond their base interfaces; implementers need only satisfy base interface requirements.
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` — provides `IBaseView` and `IBaseViewModel` base types
### What depends on this module:
- **Unknown from source alone.** No consumers of these interfaces are visible in the provided files.
## 5. Gotchas
- **Empty marker interfaces:** Both interfaces declare zero members. This is a common pattern for type discrimination, but developers should be aware that these interfaces provide no behavioral contracts beyond what their base interfaces define.
- **Base interface contracts unknown:** The actual requirements for implementing these interfaces depend entirely on `IBaseView` and `IBaseViewModel`, which are not included in the provided source. Developers will need to consult those base definitions to understand full implementation requirements.
- **Naming convention:** The "CheckTrigger" naming suggests a specific feature domain, but no documentation or comments in the source explain what "CheckTrigger" represents in the business logic.

View File

@@ -0,0 +1,100 @@
---
source_files:
- Common/DTS.CommonCore/Interface/Communication/ICommunicationReport.cs
- Common/DTS.CommonCore/Interface/Communication/IDASConnectedDevice.cs
- Common/DTS.CommonCore/Interface/Communication/ICommunication_DASInfo.cs
generated_at: "2026-04-16T12:19:03.859448+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "c40d100ec97fea56"
---
# Documentation: DTS.Common.Interface.Communication
## 1. Purpose
This module defines three interfaces for communication-related data structures within the DTS system. `ICommunicationReport` provides a standard contract for reporting communication operation results, including status, user state, and raw data. `IDASConnectedDevice` describes hardware devices connected to a Data Acquisition System (DAS), capturing physical and logical identification properties. `ICommunication_DASInfo` extends DAS communication capabilities to manage connected device discovery, serial/firmware tracking, first-use date tracking, and streaming support detection. These interfaces support auto-discovery and monitoring of DAS-connected hardware (e.g., S6 devices connected to S6DB).
---
## 2. Public Interface
### ICommunicationReport
**Properties:**
| Name | Type | Access | Description |
|------|------|--------|-------------|
| `UserState` | `object` | get/set | Arbitrary user state associated with the communication report. |
| `Result` | `CommunicationConstantsAndEnums.CommunicationResult` | get/set | The result status of the communication operation. |
| `Data` | `byte[]` | get/set | Raw byte data payload from the communication. |
---
### IDASConnectedDevice
**Properties (all read-only):**
| Name | Type | Description |
|------|------|-------------|
| `DeviceType` | `HardwareTypes` | The hardware type of the connected device. |
| `Port` | `int` | The port on the DAS where the device is connected (0-based index). |
| `SpotOnPort` | `int` | The position in the chain on the given port (0-based index). |
| `PhysicalAddress` | `PhysicalAddress` | The MAC address or physical address of the device. |
| `IPAddress` | `string` | The IP address of the device. |
| `SerialNumber` | `string` | The serial number of the device. |
| `Location` | `string` | The location descriptor of the device. |
| `Version` | `string` | The firmware/hardware version of the device. |
---
### ICommunication_DASInfo
**Properties:**
| Name | Type | Access | Description |
|------|------|--------|-------------|
| `ConnectedDevices` | `IDASConnectedDevice[]` | get only | Array of devices currently connected to the DAS. Currently only used by SLICE6DB. |
| `SerialNumbers` | `string[]` | get/set | Array of serial numbers. |
| `FirmwareVersions` | `string[]` | get/set | Array of firmware versions. |
| `FirstUseDate` | `DateTime?` | get/set | Date of first hardware use; `null` indicates hardware has not been used since calibration. Only valid when `IsFirstUseDateSupported` is `true`. |
| `IsFirstUseDateSupported` | `bool` | get/set | Indicates whether hardware supports first use date tracking. Requires firmware storage for user attributes and calibration by software supporting hardware first use. |
| `IsStreamingSupported` | `bool` | get/set | Indicates whether streaming is supported. TSR AIRs can enable/disable via `DISABLE_STREAMING_FEATURE` system attribute. |
**Methods:**
| Signature | Description |
|-----------|-------------|
| `void SetConnectedDevices(IDASConnectedDevice[] devices)` | Sets the `ConnectedDevices` array with devices connected to this DAS. |
| `string StackSerialNumber(int devid)` | Returns the stack serial number for the given device ID. |
---
## 3. Invariants
- **Port and SpotOnPort indexing**: Both `Port` and `SpotOnPort` on `IDASConnectedDevice` are 0-based indices.
- **FirstUseDate validity**: `FirstUseDate` is only meaningful when `IsFirstUseDateSupported` is `true`. A `null` value for `FirstUseDate` indicates the hardware has not been used since calibration.
- **ConnectedDevices mutability**: The `ConnectedDevices` property is read-only; modifications must go through `SetConnectedDevices(IDASConnectedDevice[])`.
- **Streaming support**: `IsStreamingSupported` reflects hardware capability; the actual feature can be controlled via the `DISABLE_STREAMING_FEATURE` system attribute on TSR AIRs.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Enums.Communication` — provides `CommunicationConstantsAndEnums.CommunicationResult`
- `DTS.Common.Enums.Hardware` — provides `HardwareTypes` enum
- `System.Net.NetworkInformation` — provides `PhysicalAddress` class
- `System` — provides `DateTime` type
### What depends on this module:
- Not determinable from the provided source files alone. These are interface definitions likely consumed by DAS communication implementations and device discovery services.
---
## 5. Gotchas
- **FirstUseDate null semantics**: A `null` `FirstUseDate` has specific meaning (hardware not used since calibration), not just "unknown" or "uninitialized". Consumers should check `IsFirstUseDateSupported` before relying on `FirstUseDate`.
- **ConnectedDevices limited usage**: The XML comment indicates `ConnectedDevices` is "currently only used by SLICE6DB" — other DAS types may not populate this array.
- **Streaming feature control**: `IsStreamingSupported` indicates hardware capability, but the actual streaming feature can be disabled via the `DISABLE_STREAMING_FEATURE` system attribute on TSR AIRs. The relationship between this property and the system attribute is not fully specified in the source.
- **StackSerialNumber parameter meaning**: The `devid` parameter in `StackSerialNumber(int devid)` lacks documentation; its interpretation (whether 0-based index, hardware ID, or other identifier) is unclear from source alone.

View File

@@ -0,0 +1,206 @@
---
source_files:
- Common/DTS.CommonCore/Interface/Components/IAssemblyView.cs
- Common/DTS.CommonCore/Interface/Components/IAssemblyListView.cs
- Common/DTS.CommonCore/Interface/Components/ITileView.cs
- Common/DTS.CommonCore/Interface/Components/IGroupView.cs
- Common/DTS.CommonCore/Interface/Components/ITileListView.cs
- Common/DTS.CommonCore/Interface/Components/IGroupListView.cs
- Common/DTS.CommonCore/Interface/Components/IAssemblyViewModel.cs
- Common/DTS.CommonCore/Interface/Components/IAssemblyListViewModel.cs
- Common/DTS.CommonCore/Interface/Components/ITileViewModel.cs
- Common/DTS.CommonCore/Interface/Components/IGroupViewModel.cs
- Common/DTS.CommonCore/Interface/Components/ITileListViewModel.cs
- Common/DTS.CommonCore/Interface/Components/IGroupListViewModel.cs
generated_at: "2026-04-16T12:16:00.246337+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "9dfaf004748c958d"
---
# Documentation: View/ViewModel Component Interfaces
## 1. Purpose
This module defines a set of abstraction interfaces for a Model-View-ViewModel (MVVM) architecture, specifically for displaying and managing grouped assembly information in a UI. It provides two parallel interface hierarchies: one in the `DTS.Common.Interface` namespace for assembly-based views, and another in the `DataPro.Common.Interface` namespace for tile/group-based views. These interfaces enable decoupling of UI components from their concrete implementations, supporting view composition patterns where assemblies can be displayed as individual items or grouped lists.
---
## 2. Public Interface
### DTS.Common.Interface Namespace
#### `IAssemblyView`
```csharp
public interface IAssemblyView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a single assembly view component. No members defined.
#### `IAssemblyListView`
```csharp
public interface IAssemblyListView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a list container for assembly views. No members defined.
#### `IAssemblyViewModel`
```csharp
public interface IAssemblyViewModel : IBaseViewModel
{
IAssemblyView View { get; set; }
string GroupName { get; set; }
List<AssemblyNameImage> AssemblyList { get; set; }
}
```
ViewModel interface for a single assembly group. Properties:
- `View` - The associated view instance
- `GroupName` - Name identifier for the group
- `AssemblyList` - Collection of `AssemblyNameImage` objects
#### `IAssemblyListViewModel`
```csharp
public interface IAssemblyListViewModel : IBaseViewModel
{
IMainViewModel Parent { get; set; }
IAssemblyListView View { get; set; }
List<IAssemblyView> GroupList { get; set; }
}
```
ViewModel interface for a collection of assembly groups. Properties:
- `Parent` - Reference to the parent `IMainViewModel`
- `View` - The associated list view instance
- `GroupList` - Collection of `IAssemblyView` instances
---
### DataPro.Common.Interface Namespace
#### `ITileView`
```csharp
public interface ITileView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a tile-based view component. No members defined.
#### `IGroupView`
```csharp
public interface IGroupView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a group-based view component. No members defined.
#### `ITileListView`
```csharp
public interface ITileListView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a list container for tile views. No members defined.
#### `IGroupListView`
```csharp
public interface IGroupListView : IBaseView { }
```
Marker interface extending `IBaseView`. Represents a list container for group views. No members defined.
#### `ITileViewModel`
```csharp
public interface ITileViewModel : IBaseViewModel
{
ITileView View { get; set; }
string GroupName { get; set; }
List<AssemblyNameImage> AssemblyList { get; set; }
}
```
ViewModel interface for a tile-based assembly group. Properties:
- `View` - The associated tile view instance
- `GroupName` - Name identifier for the group
- `AssemblyList` - Collection of `AssemblyNameImage` objects
#### `IGroupViewModel`
```csharp
public interface IGroupViewModel : IBaseViewModel
{
IGroupView View { get; set; }
string GroupName { get; set; }
List<AssemblyNameImage> AssemblyList { get; set; }
}
```
ViewModel interface for a group-based assembly display. Properties:
- `View` - The associated group view instance
- `GroupName` - Name identifier for the group
- `AssemblyList` - Collection of `AssemblyNameImage` objects
#### `ITileListViewModel`
```csharp
public interface ITileListViewModel : IBaseViewModel
{
IMainViewModel Parent { get; set; }
ITileListView View { get; set; }
List<ITileView> GroupList { get; set; }
}
```
ViewModel interface for a collection of tile groups. Properties:
- `Parent` - Reference to the parent `IMainViewModel`
- `View` - The associated tile list view instance
- `GroupList` - Collection of `ITileView` instances
#### `IGroupListViewModel`
```csharp
public interface IGroupListViewModel : IBaseViewModel
{
IMainViewModel Parent { get; set; }
IGroupListView View { get; set; }
List<IGroupView> GroupList { get; set; }
}
```
ViewModel interface for a collection of groups. Properties:
- `Parent` - Reference to the parent `IMainViewModel`
- `View` - The associated group list view instance
- `GroupList` - Collection of `IGroupView` instances
---
## 3. Invariants
- All View interfaces (`IAssemblyView`, `IAssemblyListView`, `ITileView`, `IGroupView`, `ITileListView`, `IGroupListView`) must inherit from `IBaseView`.
- All ViewModel interfaces must inherit from `IBaseViewModel`.
- The `View` property on a ViewModel must reference an instance of its corresponding View interface type (e.g., `IAssemblyViewModel.View` must be of type `IAssemblyView`).
- List ViewModels maintain a parent-child relationship: `IAssemblyListViewModel`, `ITileListViewModel`, and `IGroupListViewModel` must have a valid `Parent` reference to `IMainViewModel`.
- The `GroupList` property on list ViewModels must contain elements of the corresponding single-item View interface type.
---
## 4. Dependencies
### External Dependencies (referenced but not defined in source):
- **`DTS.Common.Base.IBaseView`** - Base interface for all views in the DTS namespace
- **`DTS.Common.Base.IBaseViewModel`** - Base interface for all ViewModels in the DTS namespace
- **`DataPro.Common.Base.IBaseView`** - Base interface for all views in the DataPro namespace
- **`DataPro.Common.Base.IBaseViewModel`** - Base interface for all ViewModels in the DataPro namespace
- **`AssemblyNameImage`** - Data structure representing assembly information (type definition not provided)
- **`IMainViewModel`** - Parent ViewModel interface (type definition not provided)
### Namespace Dependencies:
- `System.Collections.Generic` - For `List<T>` usage
- `System.Collections.ObjectModel` - Imported in DataPro ViewModel files but not actively used
- `System.Reflection` - Imported in DataPro ViewModel files but not actively used
---
## 5. Gotchas
### Namespace Inconsistency
The codebase contains two parallel interface hierarchies with inconsistent namespace naming:
- `DTS.Common.Interface` vs `DataPro.Common.Interface`
- `DTS.Common.Base` vs `DataPro.Common.Base`
This suggests either an ongoing refactoring, a legacy migration, or intentional separation between two subsystems. **The relationship between these two namespace families is unclear from source alone.**
### Unused Imports
The following files import namespaces that are never used in the interface definitions:
- `ITileViewModel.cs` - imports `System.Collections.ObjectModel` and `System.Reflection`
- `IGroupViewModel.cs` - imports `System.Collections.ObjectModel` and `System.Reflection`
- `ITileListViewModel.cs` - imports `System.Collections.ObjectModel`, `System.Reflection`, and `System`
- `IGroupListViewModel.cs` - imports `System.Collections.ObjectModel`, `System.Reflection`, and `System`
### Structural Duplication
`ITileViewModel` and `IGroupViewModel` have identical member signatures, differing only in their View property types (`ITileView` vs `IGroupView`). Similarly, `ITileListViewModel` and `IGroupListViewModel` are structurally identical. This may indicate an opportunity for generic abstraction or consolidation.
### Missing Type Definitions
The types `AssemblyNameImage` and `IMainViewModel` are referenced but not defined in the provided source files. Their structure and contracts cannot be documented from the available information.

View File

@@ -0,0 +1,105 @@
---
source_files:
- Common/DTS.CommonCore/Interface/Connection/IConnection.cs
generated_at: "2026-04-16T12:12:24.920785+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "a6aead5143a016b8"
---
# Documentation: IConnection Interface
## 1. Purpose
The `IConnection` interface defines a comprehensive abstraction for network socket connections within the DTS system. It provides a unified API for both client and server-side connection management, supporting connection lifecycle operations (create, connect, disconnect, dispose), bidirectional data transfer, and a "soft disconnect" mechanism for temporarily releasing connections with the expectation of reconnecting. The interface implements the Asynchronous Programming Model (APM) pattern for most operations, with one Task-based async method (`SendAsync`), and includes keep-alive monitoring capabilities.
## 2. Public Interface
### Interface Declaration
```csharp
public interface IConnection : IDisposable
```
### Properties
| Property | Signature | Description |
|----------|-----------|-------------|
| `IsSoftDisconnected` | `bool IsSoftDisconnected { get; }` | Returns `true` if the unit is soft disconnected (connected then voluntarily disconnected with expectation of reconnecting). |
| `Flags` | `System.Net.Sockets.SocketFlags Flags { get; set; }` | Gets or sets socket flags for send/receive operations. |
| `ConnectString` | `string ConnectString { get; }` | Returns the connection string associated with this connection. |
| `Connected` | `bool Connected { get; }` | Returns the current connection state. |
### Events
| Event | Signature | Description |
|-------|-----------|-------------|
| `OnDisconnected` | `event EventHandler OnDisconnected` | Raised when the connection is disconnected. |
### Methods - Connection Lifecycle
| Method | Signature | Description |
|--------|-----------|-------------|
| `Create` | `void Create(string connectString)` | Initializes the connection using the specified connection string. |
| `Create` | `void Create(string connectString, string hostIPAddress)` | Initializes the connection using the specified connection string and host IP address. |
| `SoftDisconnect` | `void SoftDisconnect()` | Performs a voluntary disconnect with the intention of reconnecting later. |
| `SoftConnect` | `void SoftConnect()` | Reconnects a soft disconnected unit. |
| `KeepAliveErrorReceived` | `void KeepAliveErrorReceived()` | Indicates that the device has not received a timely response to keep-alive. |
| `GetConnectionData` | `string GetConnectionData()` | Returns connection data as a string. |
### Methods - Server Operations
| Method | Signature | Description |
|--------|-----------|-------------|
| `Bind` | `void Bind(int port)` | Binds the connection to a specific port. |
| `Listen` | `void Listen(int backlog)` | Starts listening for incoming connections with the specified backlog. |
| `BeginAccept` | `IAsyncResult BeginAccept(AsyncCallback callback, object state)` | Begins an asynchronous operation to accept an incoming connection. |
| `EndAccept` | `IConnection EndAccept(IAsyncResult asyncResult)` | Completes the asynchronous accept operation and returns the accepted `IConnection`. |
### Methods - Client Connection Operations
| Method | Signature | Description |
|--------|-----------|-------------|
| `BeginConnect` | `IAsyncResult BeginConnect(AsyncCallback callback, object callbackObject)` | Begins an asynchronous connection attempt. |
| `EndConnect` | `void EndConnect(IAsyncResult ar)` | Completes the asynchronous connect operation. |
| `BeginDisconnect` | `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)` | Begins an asynchronous disconnect operation. |
| `EndDisconnect` | `void EndDisconnect(IAsyncResult asyncResult)` | Completes the asynchronous disconnect operation. |
### Methods - Data Transfer
| Method | Signature | Description |
|--------|-----------|-------------|
| `SendAsync` | `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Asynchronously sends data and returns the number of bytes sent. Uses TAP pattern. |
| `BeginSend` | `IAsyncResult BeginSend(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend, AsyncCallback callback, object callbackObject)` | Begins an asynchronous send operation. Uses APM pattern. |
| `EndSend` | `int EndSend(IAsyncResult ar)` | Completes the asynchronous send operation and returns the number of bytes sent. |
| `BeginReceive` | `IAsyncResult BeginReceive(byte[] receiveBuffer, int bufferStartOffset, int maxSizeToReceive, AsyncCallback callback, object callbackObject)` | Begins an asynchronous receive operation. |
| `EndReceive` | `int EndReceive(IAsyncResult ar)` | Completes the asynchronous receive operation and returns the number of bytes received. |
## 3. Invariants
- **Disposable Contract**: All implementations must properly implement `IDisposable`, ensuring resources (sockets, buffers, etc.) are released when disposed.
- **APM Pattern Pairing**: Every `Begin*` method must have a corresponding `End*` call to complete the operation and retrieve results. Calling `End*` without a preceding `Begin*`, or calling `End*` multiple times on the same `IAsyncResult`, is undefined behavior.
- **Soft Disconnect State Consistency**: `IsSoftDisconnected` should only return `true` after `SoftDisconnect()` has been called and before `SoftConnect()` is called. The soft disconnect state implies a prior successful connection.
- **Connection State Before Operations**: Data transfer methods (`SendAsync`, `BeginSend`, `BeginReceive`) require an active connection; behavior is undefined if called on a disconnected unit.
- **Create Before Use**: `Create()` must be called before connection operations (`BeginConnect`, `Bind`, etc.).
## 4. Dependencies
### External Dependencies (from imports)
- `System` - Core .NET types (`IAsyncResult`, `AsyncCallback`, `EventHandler`, `IDisposable`)
- `System.Threading.Tasks` - `Task<T>` for `SendAsync`
- `System.Net.Sockets.SocketFlags` - Socket configuration flags
### Dependents
- Unknown from this source file alone. Implementations of this interface and consumers would be defined elsewhere in the codebase.
## 5. Gotchas
1. **Mixed Async Patterns**: The interface uses both APM (`Begin*`/`End*` methods) and TAP (`SendAsync` returning `Task<int>`) patterns. This inconsistency may cause confusion when choosing which method to use. Note that `SendAsync` is the only TAP-style method; all other async operations use APM.
2. **Server and Client Methods in One Interface**: The interface combines server-side methods (`Bind`, `Listen`, `BeginAccept`, `EndAccept`) with client-side methods (`BeginConnect`, `EndConnect`). Implementations may need to handle scenarios where inappropriate methods are called (e.g., calling `Listen` on a client connection).
3. **Commented-Out Rate Methods**: The source contains commented-out methods `GetCurrentUploadRate()` and `GetCurrentDownloadRate()`, suggesting bandwidth monitoring was planned or removed. Do not assume these exist.
4. **Soft Disconnect vs. Regular Disconnect**: The interface provides `SoftDisconnect()`/`SoftConnect()` alongside `BeginDisconnect()`/`EndDisconnect()`. The relationship between these two disconnect mechanisms is not specified—whether `BeginDisconnect` affects `IsSoftDisconnected` state is unclear from the source alone.
5. **KeepAliveErrorReceived is a Method, Not an Event**: Despite the naming convention suggesting an event handler, `KeepAliveErrorReceived()` is a void method. Its intended usage (called by whom, when, and what it should do) is not specified in the source.

View File

@@ -0,0 +1,119 @@
---
source_files:
- Common/DTS.CommonCore/Interface/CustomChannels/ICustomChannelsView.cs
- Common/DTS.CommonCore/Interface/CustomChannels/ICustomChannelsExportView.cs
- Common/DTS.CommonCore/Interface/CustomChannels/ICustomChannelsImportView.cs
- Common/DTS.CommonCore/Interface/CustomChannels/ICustomChannelModel.cs
- Common/DTS.CommonCore/Interface/CustomChannels/ICustomChannelsViewModel.cs
generated_at: "2026-04-16T12:10:34.879323+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "d441dada7c96f903"
---
# Custom Channels Interface Module Documentation
## 1. Purpose
This module defines the contract interfaces for a Custom Channels feature, implementing a Model-View-ViewModel (MVVM) architecture. It provides abstractions for managing custom channel configurations, including the ability to import and export channel definitions. The interfaces decouple the presentation layer from business logic, enabling view models to orchestrate import/export operations while views remain passive implementations of `IBaseView` and `IBaseViewModel` contracts.
---
## 2. Public Interface
### `ICustomChannelsView`
**Namespace:** `DTS.Common.Interface`
**Inheritance:** `IBaseView`
A marker interface with no members. Identifies views responsible for displaying custom channels.
---
### `ICustomChannelsExportView`
**Namespace:** `DTS.Common.Interface.CustomChannels`
**Inheritance:** `IBaseView`
A marker interface with no members. Identifies views handling the export workflow for custom channels.
---
### `ICustomChannelsImportView`
**Namespace:** `DTS.Common.Interface.CustomChannels`
**Inheritance:** `IBaseView`
A marker interface with no members. Identifies views handling the import workflow for custom channels.
---
### `ICustomChannelModel`
**Namespace:** `DTS.Common.Interface.CustomChannels`
Represents a single custom channel item with selection state.
| Property | Type | Access | Description |
|----------|------|--------|-------------|
| `Name` | `string` | get | The identifier or display name of the custom channel. |
| `Included` | `bool` | get, set | Indicates whether this channel is selected for an operation (e.g., export). |
---
### `ICustomChannelsViewModel`
**Namespace:** `DTS.Common.Interface.CustomChannels`
**Inheritance:** `IBaseViewModel`
Orchestrates custom channel import/export operations.
**Properties:**
| Property | Type | Access | Description |
|----------|------|--------|-------------|
| `ImportView` | `ICustomChannelsImportView` | get, set | The view instance for import operations. |
| `ExportView` | `ICustomChannelsExportView` | get, set | The view instance for export operations. |
| `ExportFileName` | `string` | get, set | Target file path for export operations. |
| `ImportFileName` | `string` | get, set | Source file path for import operations. |
| `AllCustomChannels` | `ObservableCollection<ICustomChannelModel>` | get | Collection of all available custom channel models. |
**Methods:**
| Method | Signature | Description |
|--------|-----------|-------------|
| `Unset` | `void Unset()` | Clears or resets the view model state. |
| `OnSetActive` | `void OnSetActive(bool bImport)` | Called when the view becomes active; `bImport` indicates import mode (true) vs export mode (false). |
| `ReadImportFile` | `void ReadImportFile()` | Reads and parses the file specified by `ImportFileName`. |
| `SelectAll` | `void SelectAll()` | Sets `Included` to `true` for all items in `AllCustomChannels`. |
| `ClearSelection` | `void ClearSelection()` | Sets `Included` to `false` for all items in `AllCustomChannels`. |
| `Export` | `void Export()` | Executes the export operation using current selection and `ExportFileName`. |
| `Import` | `void Import()` | Executes the import operation using current selection and `ImportFileName`. |
---
## 3. Invariants
- `ICustomChannelModel.Name` is read-only; once set by the implementation, the name cannot be changed through this interface.
- `AllCustomChannels` is read-only at the interface level; consumers cannot replace the collection, only modify its contents or item properties.
- All view interfaces (`ICustomChannelsView`, `ICustomChannelsExportView`, `ICustomChannelsImportView`) must be assignable to `IBaseView`.
- `ICustomChannelsViewModel` must be assignable to `IBaseViewModel`.
- The `bImport` parameter in `OnSetActive` uses a boolean to distinguish between import (true) and export (false) modes.
---
## 4. Dependencies
**This module depends on:**
- `DTS.Common.Base` — Provides `IBaseView` and `IBaseViewModel` base contracts.
- `System.Collections.ObjectModel` — Provides `ObservableCollection<T>` used for `AllCustomChannels`.
**What depends on this module:**
- Cannot be determined from source alone. Concrete implementations of these interfaces, as well as consumers of `ICustomChannelsViewModel`, would exist elsewhere in the codebase.
---
## 5. Gotchas
1. **Namespace inconsistency:** `ICustomChannelsView` resides in `DTS.Common.Interface`, while all other interfaces in this feature set reside in `DTS.Common.Interface.CustomChannels`. This may cause confusion or require additional using directives.
2. **Marker interfaces:** `ICustomChannelsView`, `ICustomChannelsExportView`, and `ICustomChannelsImportView` define no members. Their utility appears to be type identification for view resolution or dependency injection—verify the actual usage pattern in the consuming codebase.
3. **Import/Export coupling:** The `ICustomChannelsViewModel` manages both import and export workflows. The `OnSetActive(bool bImport)` method toggles behavior based on a boolean flag, which may complicate testing or extension if the two workflows diverge.
4. **File I/O abstraction:** The interfaces expose file names as strings (`ImportFileName`, `ExportFileName`) with no validation hints. It is unclear whether implementations validate file existence, extensions, or permissions before `ReadImportFile()`, `Export()`, or `Import()` are called.

View File

@@ -0,0 +1,69 @@
---
source_files:
- Common/DTS.CommonCore/Interface/CustomerDetails/ICustomerDetailsView.cs
- Common/DTS.CommonCore/Interface/CustomerDetails/ICustomerDetailsViewModel.cs
generated_at: "2026-04-16T12:19:49.445469+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b07af412c78e07b1"
---
# Documentation: Customer Details Interfaces
## 1. Purpose
This module defines two marker interfaces—`ICustomerDetailsView` and `ICustomerDetailsViewModel`—that establish type identity for customer details components within a Model-View-ViewModel (MVVM) architecture. These interfaces exist to provide a contract for customer-specific views and view models, enabling type-safe binding, dependency injection, and navigation patterns while inheriting core behaviors from base interfaces in the `DTS.Common.Base` namespace.
---
## 2. Public Interface
### `ICustomerDetailsView`
- **Namespace:** `DTS.Common.Interface`
- **Inheritance:** `IBaseView` (from `DTS.Common.Base`)
- **Signature:**
```csharp
public interface ICustomerDetailsView : IBaseView { }
```
- **Behavior:** Empty marker interface. Any concrete view implementing this interface signals that it represents a customer details screen. All actual behavior and members are inherited from `IBaseView`.
### `ICustomerDetailsViewModel`
- **Namespace:** `DTS.Common.Interface`
- **Inheritance:** `IBaseViewModel` (from `DTS.Common.Base`)
- **Signature:**
```csharp
public interface ICustomerDetailsViewModel : IBaseViewModel { }
```
- **Behavior:** Empty marker interface. Any concrete view model implementing this interface signals that it provides the presentation logic for a customer details view. All actual behavior and members are inherited from `IBaseViewModel`.
---
## 3. Invariants
- **Type identity guarantee:** Any class implementing `ICustomerDetailsView` or `ICustomerDetailsViewModel` must also satisfy the contracts of `IBaseView` or `IBaseViewModel` respectively.
- **No additional members:** Neither interface defines its own properties, methods, or events; they rely entirely on their base interfaces for functionality.
- **Naming convention:** The interfaces follow a naming pattern suggesting a 1:1 correspondence between `ICustomerDetailsView` and `ICustomerDetailsViewModel`.
**Note:** Specific invariants regarding `IBaseView` and `IBaseViewModel` cannot be determined from the provided source files.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` — Provides `IBaseView` and `IBaseViewModel` base interfaces.
### What depends on this module:
- Cannot be determined from the provided source files alone. Likely consumers include:
- Concrete view implementations (e.g., WinForms, WPF, or web views displaying customer details)
- Concrete view model implementations for customer details
- Navigation or routing services that resolve views by interface type
- Dependency injection configurations
---
## 5. Gotchas
- **Empty marker interfaces:** Both interfaces define no members of their own. If `IBaseView` and `IBaseViewModel` also lack meaningful members, these interfaces serve purely as type markers. This design is intentional for type discrimination but may confuse developers expecting explicit contracts.
- **Base interface contracts unknown:** The actual capabilities and requirements of these interfaces are entirely determined by `IBaseView` and `IBaseViewModel`. Developers must consult those base definitions to understand what members must be implemented.
- **Potential tight coupling to base types:** Any changes to `IBaseView` or `IBaseViewModel` will ripple to all implementers of these customer details interfaces.

View File

@@ -0,0 +1,429 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DASFactory/IAutoArmed.cs
- Common/DTS.CommonCore/Interface/DASFactory/ITiltSensorCalAware.cs
- Common/DTS.CommonCore/Interface/DASFactory/IRangeBandwidthLimited.cs
- Common/DTS.CommonCore/Interface/DASFactory/IAutoArmStatus.cs
- Common/DTS.CommonCore/Interface/DASFactory/ITimeSynchronization.cs
- Common/DTS.CommonCore/Interface/DASFactory/IConnectedEthernetDevice.cs
- Common/DTS.CommonCore/Interface/DASFactory/IDASConfigurationArg.cs
- Common/DTS.CommonCore/Interface/DASFactory/IRealtime.cs
- Common/DTS.CommonCore/Interface/DASFactory/IUDPQATSEntry.cs
- Common/DTS.CommonCore/Interface/DASFactory/IDASFactory.cs
- Common/DTS.CommonCore/Interface/DASFactory/ICommunication.cs
- Common/DTS.CommonCore/Interface/DASFactory/IDiscoveredDevice.cs
- Common/DTS.CommonCore/Interface/DASFactory/IAnalogInputDASChannel.cs
- Common/DTS.CommonCore/Interface/DASFactory/IDASCommunication.cs
generated_at: "2026-04-16T12:19:30.502497+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "5d1420792c49604c"
---
# DASFactory Interfaces Documentation
## 1. Purpose
This module defines the core abstraction layer for the Data Acquisition System (DAS) Factory pattern. It provides interfaces for device discovery, hardware communication, channel configuration, real-time data streaming, and diagnostics across multiple DAS hardware types (SLICE, TDAS, TSR, etc.). The interfaces enable polymorphic treatment of diverse hardware while exposing type-specific capabilities through optional interface implementation. This module serves as the contract layer between high-level application services and low-level hardware drivers.
---
## 2. Public Interface
### IAutoArmed
```csharp
bool AutoArmed { get; set; }
```
Simple marker interface for auto-arming capability.
### ITiltSensorCalAware
```csharp
double[] TiltSensorCals { get; }
```
Exposes tilt sensor calibration values. Returns an array of calibration coefficients.
### IRangeBandwidthLimited
```csharp
bool RangeBandwidthLimited { get; }
```
Read-only flag indicating if the device has range/bandwidth limitations applied.
### IAutoArmStatus
```csharp
DFConstantsAndEnums.CommandStatus AutoArmStatus { get; set; }
```
Tracks the command status of auto-arm operations using `DFConstantsAndEnums.CommandStatus` enum.
### ITimeSynchronization
```csharp
bool SupportsTimeSynchronization { get; }
DateTime SystemBaseTime { get; }
```
Indicates time synchronization support and provides the system base time reference.
### IConnectedEthernetDevice
```csharp
string MACAddress { get; }
int Port { get; }
string SerialNumber { get; set; }
```
Represents an ethernet-connected device with network identification properties.
### IDASConfigurationArg
```csharp
IDASCommunication DAS { get; }
bool BlankConfigurationRead { get; }
bool ConfigurationFailedValidation { get; }
```
Argument interface for configuration events. Used per comment "17872 Use DASConfig XMLs on disk when performing an emergency download with DAS that have blank filestore(s)".
### IRealTime
```csharp
List<int> RealtimeDASChannels { get; set; }
List<double> TiltAxisData { get; set; }
string UDPStreamAddress { get; }
```
Real-time data streaming interface. `TiltAxisData` provides Slice6 Axis 1/2/3 (X/Y/Z) tilt in degrees. `UDPStreamAddress` provides the S6/S6A realtime UDP stream endpoint.
### IUDPQATSEntry
Extensive interface for UDP QATS (Quick Acquisition and Telemetry System) entries:
```csharp
string ResponseHostMac { get; }
string ResponseClientMacAddress { get; }
string SerialNumber { get; }
byte ArmState { get; }
byte ArmMode { get; }
byte Started { get; }
byte Triggered { get; }
byte FaultFlags { get; }
uint SampleRate { get; }
ulong TotalSamples { get; }
ulong CurrentSample { get; }
ushort EventNumber { get; }
ulong FaultSampleNumber { get; }
ushort LegacyFaultFlags { get; }
float InputVoltage { get; }
float BackupVoltage { get; }
float BatterySOC { get; }
ulong EstimateMaxSamples { get; }
short TiltSensorCh1 { get; }
short TiltSensorCh2 { get; }
short TiltSensorCh3 { get; }
float SysTempC { get; }
byte SyncClockEnable { get; }
byte ADCExtClockSyncEnable { get; }
byte SyncClockStatus { get; }
byte ADCExtClockSyncStatus { get; }
ulong EventTriggerSample { get; }
float[] ChannelOffsetMV { get; }
float[] ShuntDeviationPercent { get; }
DateTime Timestamp { get; }
```
### IDASFactory
Primary factory interface for DAS device management:
```csharp
bool PingAll();
string Language { get; set; }
void TakeOwnership();
bool AllowSDBCommandPort { get; set; }
double S6ConnectNewTimeout { get; set; }
string[] SliceDBHostNames { get; set; }
string[] GetConnectedDevices();
string[] TDASHostNames { get; set; }
string[] TDASSerialPortNames { get; set; }
string TDASSerialRackSerialNumber { get; set; }
List<IDASCommunication> GetDASList();
List<IDASCommunication> GetSortedDASList();
List<ICommunication> GetDevList();
void DetachAllDevices(bool detachUSB = false);
void Refresh(ActionCompleteDelegate action);
int MultiCastAutoDiscoveryDefaultTimeoutMS { get; set; }
SortableBindingList<IDiscoveredDevice> AutoDiscoverMulticast(bool discoverParents = true);
```
### ICommunication
Low-level communication interface extending `IComparable<ICommunication>` and `IComparable<string>`:
```csharp
IConnection Transport { get; set; }
void SetupReader();
int ReceiveBufferSize { get; set; }
string SerialNumber { get; set; }
string FirmwareVersion { get; set; }
byte ProtocolVersion { get; set; }
ICommunication_DASInfo DASInfo { get; set; }
Dictionary<DFConstantsAndEnums.ProtocolLimitedCommands, byte> MinimumProtocols { get; set; }
void InitMinProto();
bool IsCommandSupported(DFConstantsAndEnums.ProtocolLimitedCommands command);
byte GetMinProto(DFConstantsAndEnums.ProtocolLimitedCommands command);
event EventHandler OnDisconnected;
string ConnectString { get; }
bool Connected { get; }
void Connect(string ConnectString, CommunicationConstantsAndEnums.CommunicationCallback Callback, object CallbackObject, int CallbackTimeout, string ipAddress);
void Disconnect(bool reuseSocket, CommunicationConstantsAndEnums.CommunicationCallback Callback, object CallbackObject, int CallbackTimeout);
void Close(int Timeout);
void Flush(int Timeout);
bool ExecuteIsBusy { get; set; }
void Execute(byte[] byteData, CommunicationConstantsAndEnums.CommunicationCallback Callback, object CallbackObject, int CallbackTimeout);
void PseudoExecute(byte[] byteData, CommunicationConstantsAndEnums.CommunicationCallback Callback, object CallbackObject, int CallbackTimeout);
byte[] SyncExecute(byte[] byteData, int Timeout);
void Cancel();
void ForceCancel();
bool IsCanceled();
void ClearCancel();
ManualResetEvent CancelEvent { get; }
```
### IDiscoveredDevice
Interface for multicast-discovered devices:
```csharp
string Serial { get; set; }
MultiCastDeviceClasses DevClass { get; set; }
string Mac { get; set; }
IDiscoveredDevice Parent { get; set; }
bool IsParent(IDiscoveredDevice possibleChild);
int GetPort(IDiscoveredDevice device);
int GetSlot(IDiscoveredDevice child, Dictionary<string, IDiscoveredDevice> lookup);
int GetSlotOnPort(IDiscoveredDevice child, Dictionary<string, IDiscoveredDevice> lookup);
bool IsModule { get; set; }
int Port { get; set; }
int PositionOnDistributor { get; set; }
int PositionOnChain { get; set; }
bool Dhcp { get; set; }
string Ip { get; set; }
string Subnet { get; set; }
string Gateway { get; set; }
string Dns { get; set; }
bool Connected { get; set; }
string ConnectedIp { get; set; }
string ConnectedHost { get; set; }
ushort SystemId { get; set; }
string Location { get; set; }
string FirmwareVersion { get; set; } // Format: [Product Name]-[FW/BL]-[REL/DBG]-[Board #]-[FW Ver Name]
string BuildId { get; set; }
IConnectedEthernetDevice[] Connections { get; set; }
```
### IAnalogInputDASChannel
Comprehensive interface for analog input channel configuration (100+ members). Key properties include:
**Bridge Configuration:**
```csharp
SensorConstants.BridgeType TypeOfBridge { get; set; }
SensorConstants.BridgeType[] SupportedBridges { get; set; }
double BridgeResistanceOhms { get; set; }
```
**Sensor Properties:**
```csharp
double SensorCapacityEU { get; set; }
double SensorCapacity { get; set; }
string SensorPolarity { get; set; }
double DesiredRangeWithHeadroomEU { get; set; }
double SensitivityMilliVoltsPerEU { get; set; }
double SensitivityMilliVoltsPerEUNormalized { get; }
bool IsProportionalToExcitation { get; set; }
bool IsInverted { get; set; }
```
**Channel Identification:**
```csharp
string OriginalChannelName { get; set; }
string ChannelName2 { get; set; }
string ChannelId { get; set; }
string ChannelGroupName { get; set; }
string HardwareChannelName { get; set; }
```
**Excitation:**
```csharp
ExcitationVoltageOptions.ExcitationVoltageOption Excitation { get; set; }
ExcitationVoltageOptions.ExcitationVoltageOption[] SupportedExcitation { get; set; }
bool IsSupported(ExcitationVoltageOptions.ExcitationVoltageOption o);
```
**Digital Input:**
```csharp
DigitalInputModes[] SupportedDigitalInputModes { get; set; }
DigitalInputModes DigitalMode { get; set; }
string DIUnits { get; set; }
bool DigitalInputChannel { get; set; }
```
**Zero Configuration:**
```csharp
ZeroMethodType ZeroMethod { get; set; }
double ZeroAverageStartSeconds { get; set; }
double ZeroAverageStopSeconds { get; set; }
double InitialEU { get; set; }
string InitialOffset { get; set; }
```
**Diagnostics:**
```csharp
bool ShuntIsEnabled { get; set; }
int ShuntTargetADC { get; set; }
bool VoltageInsertionCheckEnabled { get; set; }
bool RemoveOffset { get; set; }
bool VerifyOffset { get; set; }
double OffsetToleranceLowMilliVolts { get; set; }
double OffsetToleranceHighMilliVolts { get; set; }
IDiagnosticResult Diagnostics { get; }
IDiagnosticResult DiagnosticInformation { get; }
```
**Level Triggering:**
```csharp
double? TriggerBelowThresholdEu { get; set; }
double? TriggerAboveThresholdEu { get; set; }
bool AlreadyLevelTriggered { get; set; }
double MeasuredEULevelTriggerCheck { get; set; }
```
**XML Serialization:**
```csharp
void WriteElementEnd(XmlWriter writer);
void WriteXml(XmlWriter writer);
void WriteXmlCRC32(XmlWriter writer);
string GetSupportedExcitationSerialized();
string GetSupportedDigitalInputModesSerialized();
string GetSupportedBridgesSerialized();
```
### IDASCommunication
Primary interface for DAS unit interaction. Extends multiple capability interfaces:
- `IConfiguration`, `IDiagnos`, `ITriggerCheck`, `IRealTime`, `IArmStatus`, `IDownload`, `IInformation`
- `IComparable<IDASCommunication>`, `IDisposable`, `IAutoArmStatus`, `IAutoArmed`, `IRangeBandwidthLimited`, `ITimeSynchronization`
**Key Properties:**
```csharp
ExcitationStatus ExcitationStatus { get; set; }
DateTime? FirstUseDate { get; set; }
bool IsFirstUseDateSupported { get; set; }
bool IsStreamingSupported { get; set; }
HardwareTypes GetHardwareType();
int RecordId { get; set; }
string SerialNumber { get; set; }
string FirmwareVersion { get; }
bool DiagnosticsHasBeenRun { get; set; }
bool ConfigureHasBeenRun { get; set; }
string MACAddress { get; set; }
string[] DownstreamMACAddresses { get; set; }
```
**Voltage Thresholds:**
```csharp
float InputLowVoltage { get; set; }
float InputMediumVoltage { get; set; }
float InputHighVoltage { get; set; }
float BatteryLowVoltage { get; set; }
float BatteryMediumVoltage { get; set; }
float BatteryHighVoltage { get; set; }
double MinimumValidInputVoltage { get; set; }
double MaximumValidInputVoltage { get; set; }
double MinimumValidBatteryVoltage { get; set; }
double MaximumValidBatteryVoltage { get; set; }
```
**Channel & Memory:**
```csharp
int NumberOfConfiguredChannels();
int NumberOfChannels();
long MaxMemory();
int MaxModules { get; set; }
```
**Sample Rates:**
```csharp
uint MinSampleRate();
uint MaxSampleRate(int numberOfConfiguredChannels);
uint MaxAAFilterRate();
```
**Capability Queries:**
```csharp
bool SupportsAutoArm();
bool SupportsLevelTrigger();
bool SupportsRealtime();
bool SupportsMultipleEvents();
bool SupportsTriggerInversion();
bool SupportsStartInversion();
bool SupportsHardwareInputCheck();
bool SupportsMultipleSampleRealtime();
bool SupportsIndividualChannelRealtimeStreaming { get; }
bool InvertTrigger { set; }
bool InvertStart { get; set; }
bool IgnoreShortedStart { get; set; }
bool IgnoreShortedTrigger { get; set; }
```
**Hardware Type Checks:**
```csharp
bool IsEthernetDistributor();
bool IsSlice6Distributor();
bool IsBattery();
bool IsTSRAIR();
bool IsSlice6Air();
bool ControlsDAQ();
bool IsStreamingSupported { get; set; }
```
**Operations:**
```csharp
void ReadFirstUseDate();
void SetIsStreamingSupported(bool supported = false);
bool ConnectionCheck();
double[] GetNominalRanges(SensorConstants.BridgeType bridge);
bool CheckAAF(float rate);
bool RequireDiagnosticRateMatchSampleRate();
ulong GetPhaseShiftSamples(uint ModuleIndex, double ActualSampleRate, uint HardwareAAF, ulong originalT0);
bool GetCanCheckArmStatus();
```
---
## 3. Invariants
1. **Channel Configuration**: A channel is considered "configured" if and only if `SerialNumber` field is populated (per `IsConfigured()` contract in `IAnalogInputDASChannel`).
2. **First Use Date**: `FirstUseDate` is only valid when `IsFirstUseDateSupported` is `true`. A `null` value indicates the hardware has not been used since calibration.
3. **Protocol Versioning**: Commands must be checked via `IsCommandSupported()` before execution on `ICommunication` implementations, as protocol support varies by firmware version.
4. **SetupReader Requirement**: `SetupReader()` must be called whenever a socket is connected (per comment in `ICommunication`).
5. **Diagnostics/Configuration State**: `DiagnosticsHasBeenRun` and `ConfigureHasBeenRun` flags indicate whether these operations have been executed and should be checked before relying on diagnostic results.
6. **Phase Shift Calculation**: `GetPhaseShiftSamples()` returns 0 for most DAS types as phase delay is only known for specific hardware.
7. **Position Hierarchy**: For devices on a SLICE6DB, `PositionOnDistributor` and `PositionOnChain` track device location when individual SLICE6 devices are not shown in UI.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Enums` - Core enumerations
- `DTS.Common.Enums.Communication` - Communication-specific enums
- `DTS.Common.Enums.DASFactory` - DAS factory enums including `DFConstantsAndEnums`, `MultiCastDeviceClasses`
- `DTS.Common.Enums.Hardware` - `HardwareTypes`, `ExcitationStatus`
- `DTS.Common.Enums.Sensors` - `SensorConstants.BridgeType`, `SensorConstants.CouplingModes`, `ExcitationVoltageOptions`, `DigitalInputModes`, `ZeroMethodType`
- `DTS.Common.Interface.Communication` - Communication interfaces
- `DTS.Common.Interface.Connection` - `IConnection` interface
- `DTS.Common.Interface.DASFactory.ARM` - ARM-related interfaces
- `DTS.Common.Interface.DASFactory.Config` - Configuration interfaces
- `DTS.Common.Interface.DASFactory.Diagnostics` - `IDiagnosticResult`, `IDiagnos`
- `DTS.Common.Interface.DASFactory.Download` - Download interfaces
- `DTS.Common.Interface.Sensors.SoftwareFilters` - `IFilterClass`
- `DTS.Common.Interface.StatusAndProgressBar` - `ActionCompleteDelegate`
- `DTS.Common.Utilities` - `SortableBindingList<T>`
- `System.Xml` - `XmlWriter` for serialization
### What depends on this module:
Cannot be determined from source alone, but `IDASCommunication` documentation states it is "the most used data structure in the API" with nearly all hardware services taking `List<IDASCommunication>` as a parameter.
---
## 5. Gotchas
1. **SoftwareFilterClass Refactoring** (IAnalog

View File

@@ -0,0 +1,38 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Common.CPU/IcpuEngine.cs
generated_at: "2026-04-16T12:17:51.395302+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "920a09a2c868b9d9"
---
# Documentation: ICPUEngine Interface
## 1. Purpose
This module defines the `ICPUEngine` interface within the `DTS.Common.Interface` namespace. It serves as a specific contract for CPU engine components, deriving from a base system interface `IBaseClass`. Currently, the interface acts as a marker or placeholder, as it defines no custom members of its own, implying that all necessary behavior is currently inherited or that the implementation is pending extension.
## 2. Public Interface
### `ICPUEngine`
**Signature:**
```csharp
public interface ICPUEngine : IBaseClass
```
**Description:**
This is the primary public type defined in this file. It is an empty interface that inherits from `IBaseClass`. It exposes no methods, properties, or events directly; its public interface consists entirely of the members inherited from `IBaseClass`.
## 3. Invariants
* Any class implementing `ICPUEngine` must also implement `IBaseClass` (defined in `DTS.Common.Base`).
* As the interface currently defines no members, it functions strictly as a type definition or marker within the type hierarchy.
## 4. Dependencies
* **Depends on:**
* `DTS.Common.Base` (specifically the `IBaseClass` interface).
* **Dependents:**
* Unknown from this source file alone. Concrete CPU engine implementations would implement this interface.
## 5. Gotchas
* **Empty Interface:** The `ICPUEngine` interface defines no members. Developers should not expect CPU-specific methods (such as execution cycles or instruction handling) to be available on variables typed as `ICPUEngine` unless they are defined on `IBaseClass`.
* **Naming/Location Discrepancy:** The file path suggests a directory named `DTS.Common.CPU` (`.../Interface/DTS.Common.CPU/IcpuEngine.cs`), but the namespace declared in the code is `DTS.Common.Interface`. This may cause confusion when locating the file versus the namespace usage.
* **File Casing:** The filename is `IcpuEngine.cs` (lowercase 'cpu'), while the interface name is `ICPUEngine` (uppercase 'CPU'). This inconsistency in casing could lead to confusion or issues on case-sensitive file systems.

View File

@@ -0,0 +1,269 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITabView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDiagView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITestsView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IStatsView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ICursorView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IViewerView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITabItemView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IPropertyView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IViewerShellView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IGraphPropertyView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDockPanelVerticalView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDockPanelHorizontalView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/GroupChannelReadCalcDelegate.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITabViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDiagViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IStatsViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ICursorViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITestsViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IViewerViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IPropertyViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IViewerModule.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IPSDReportModule .cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IGraphPropertyViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDockPanelVerticalViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IDockPanelHorizontalViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ITabItemViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IViewerShellViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IMainLiteView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IMainViewerView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ISelectedDataViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IMainLiteViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/IMainViewModel.cs
generated_at: "2026-04-16T12:14:43.492195+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "fed47436f7c090f0"
---
# DTS.Common.Interface Viewer Module Documentation
## 1. Purpose
This module defines the contract layer for the DTS Viewer application's presentation components. It establishes a Model-View-ViewModel (MVVM) architecture through a comprehensive set of interfaces for views, view models, and modules. The interfaces enable loose coupling between UI components and their controllers, supporting a modular, plugin-based architecture built on Microsoft Prism. This abstraction layer allows different concrete implementations of views and view models to be swapped without affecting dependent code.
---
## 2. Public Interface
### View Interfaces
All view interfaces inherit from `IBaseView` (defined in `DTS.Common.Base`) and are currently marker interfaces with no additional members:
| Interface | Description |
|-----------|-------------|
| `ITabView` | Marker interface for tab views |
| `IDiagView` | Marker interface for diagnostic views |
| `ITestsView` | Marker interface for test views |
| `IStatsView` | Marker interface for statistics views |
| `ICursorView` | Marker interface for cursor views |
| `IViewerView` | Marker interface for viewer views |
| `ITabItemView` | Marker interface for individual tab item views |
| `IPropertyView` | Marker interface for property views |
| `IViewerShellView` | Marker interface for the main shell view |
| `IGraphPropertyView` | Marker interface for graph property views |
| `IDockPanelVerticalView` | Marker interface for vertical dock panel views |
| `IDockPanelHorizontalView` | Marker interface for horizontal dock panel views |
#### `IMainLiteView`
```csharp
public interface IMainLiteView : IBaseView
{
StackPanel MainShell { get; set; }
ContentControl MainRegion { get; set; }
ContentControl NavigationRegion { get; set; }
ContentControl HorizontalTabRegion { get; set; }
ContentControl VerticalTabRegion { get; set; }
}
```
Exposes WPF region controls for the "Lite" version of the main view.
#### `IMainViewerView`
```csharp
public interface IMainViewerView : IBaseView
{
// All members commented out in source
}
```
Marker interface for the main viewer view. Region properties are commented out in the source.
---
### ViewModel Interfaces
All view model interfaces inherit from `IBaseViewModel` (defined in `DTS.Common.Base`).
#### Standard ViewModel Interfaces
Each provides a `View` property returning its corresponding view interface:
| Interface | View Property Type |
|-----------|-------------------|
| `ITabViewModel` | `ITabView View { get; }` |
| `IDiagViewModel` | `IDiagView View { get; }` |
| `IStatsViewModel` | `IStatsView View { get; }` |
| `ICursorViewModel` | `ICursorView View { get; }` |
| `ITestsViewModel` | `ITestsView View { get; }` |
| `IViewerViewModel` | `IViewerView View { get; }` |
| `IPropertyViewModel` | `IPropertyView View { get; }` |
| `IGraphPropertyViewModel` | `IGraphPropertyView View { get; }` |
| `IDockPanelVerticalViewModel` | `IDockPanelVerticalView View { get; }` |
| `IDockPanelHorizontalViewModel` | `IDockPanelHorizontalView View { get; }` |
#### `ITabItemViewModel`
```csharp
public interface ITabItemViewModel : IBaseViewModel
{
ITabItemView View { get; }
ITabViewModel Parent { get; }
}
```
Represents a tab item with a reference to its parent `ITabViewModel`.
#### `IViewerShellViewModel`
```csharp
public interface IViewerShellViewModel : IBaseViewModel
{
IViewerShellView View { get; }
List<FrameworkElement> GetRegions();
object ContextMainRegion { get; set; }
}
```
The shell view model providing region management and main region context.
#### `IMainLiteViewModel`
```csharp
public interface IMainLiteViewModel : IBaseViewModel
{
IMainView View { get; }
object ContextMainRegion { get; set; }
object ContextNavigationRegion { get; set; }
object ContextHorizontalTabRegion { get; set; }
object ContextVerticalTabRegion { get; set; }
List<FrameworkElement> GetRegions();
}
```
**Note:** Returns `IMainView` (not `IMainLiteView`), which is not defined in the provided source files.
#### `IMainViewerViewModel`
```csharp
public interface IMainViewerViewModel : IBaseViewModel
{
IBaseView View { get; }
object ContextMainRegion { get; set; }
object ContextNavigationRegion { get; set; }
object ContextHorizontalTabRegion { get; set; }
object ContextVerticalTabRegion { get; set; }
List<FrameworkElement> GetRegions();
}
```
Returns `IBaseView` directly rather than a specific view interface.
---
### Module Interfaces
#### `IViewerModule`
```csharp
public interface IViewerModule : IModule
{
void StartSession(bool standalone, string pluginFolder = "");
}
```
Defines a Prism module for the viewer with session initialization capability.
#### `IPSDReportModule`
```csharp
public interface IPSDReportModule : IModule
{
void StartSession(bool standalone, string pluginFolder = "");
}
```
Defines a Prism module for PSD reporting with identical session initialization signature.
---
### Other Types
#### `SetReadCalcProgressValueDelegate`
```csharp
public delegate void SetReadCalcProgressValueDelegate(string message = "", double value = -1D);
```
A delegate type for reporting progress during read/calculation operations. Default parameters allow calling with no arguments.
#### `ISelectedDataViewModel`
```csharp
public interface ISelectedDataViewModel
{
string SelectedDataFolder { get; set; }
string SelectedDataFile { get; set; }
void SelectAndIncludeDataFile(string file);
}
```
**Does NOT inherit from `IBaseViewModel`.** Manages data file selection with a method to both select and include a file as a test. The XML comment references bug "16158 Browse button on View Data tab not functional."
---
## 3. Invariants
- All view interfaces (except `ISelectedDataViewModel`) must inherit from `IBaseView`.
- All view model interfaces (except `ISelectedDataViewModel`) must inherit from `IBaseViewModel`.
- Each standard view model interface must expose a read-only `View` property returning its corresponding view interface type.
- `ITabItemViewModel.Parent` must return a valid `ITabViewModel` instance (parent-child relationship is expected).
- `StartSession` on module interfaces must be called to initialize the module with explicit `standalone` mode specification.
- Region context properties (`ContextMainRegion`, `ContextNavigationRegion`, etc.) are expected to be set by the framework or controlling code before views are rendered.
---
## 4. Dependencies
### External Dependencies
| Dependency | Usage |
|------------|-------|
| `DTS.Common.Base` | Provides `IBaseView` and `IBaseViewModel` base interfaces |
| `Microsoft.Practices.Prism.Modularity` | Provides `IModule` interface for module definitions |
| `System.Windows` | Provides `FrameworkElement` for region management |
| `System.Windows.Controls` | Provides `StackPanel`, `ContentControl` for view composition |
### Downstream Dependencies
**Unclear from source alone.** These interfaces are contract definitions; concrete implementations and consumers are not present in the provided files. The naming convention suggests implementations exist in a `DTS.Viewer` assembly or namespace.
---
## 5. Gotchas
1. **`IMainLiteViewModel.View` returns `IMainView`** — This interface references `IMainView`, which is not defined in any of the provided source files. This may be a typo for `IMainLiteView` or a separate interface.
2. **`IMainViewerView` has all members commented out** — The interface exists but all its region properties are commented out. This may indicate incomplete refactoring or an abandoned change.
3. **`ISelectedDataViewModel` does not follow the pattern** — Unlike all other view model interfaces, this one does not inherit from `IBaseViewModel` and has no `View` property. It appears to be a utility interface rather than a true MVVM view model.
4. **Inconsistent XML comments** — Some interfaces have XML documentation (e.g., `ITabViewModel`, `ITabItemViewModel`), while others do not. Some comments are copy-pasted incorrectly (e.g., `IViewerViewModel` says "Gets the Tests View" but returns `IViewerView`).
5. **`SetReadCalcProgressValueDelegate` naming mismatch** — The filename is `GroupChannelReadCalcDelegate.cs` but the delegate is named `SetReadCalcProgressValueDelegate`.
6. **`IPSDReportModule` filename has trailing space** — The filename is `IPSDReportModule .cs` (note the space before the extension).

View File

@@ -0,0 +1,83 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/CalculatedChannel/IAddCalculatedChannelView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/CalculatedChannel/IAddCalculatedChannelViewModel.cs
generated_at: "2026-04-16T12:23:49.838372+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "720d768a9bb759bc"
---
# Documentation: IAddCalculatedChannelView & IAddCalculatedChannelViewModel
## 1. Purpose
This module defines the view and viewmodel interfaces for the "Add Calculated Channel" feature within a larger MVVM (Model-View-ViewModel) architecture. `IAddCalculatedChannelView` serves as a marker interface for the view component, while `IAddCalculatedChannelViewModel` defines the contract for the viewmodel, exposing commands and properties for managing calculated channel creation, ISO export settings, DTS encoding defaults, and search context regions.
---
## 2. Public Interface
### IAddCalculatedChannelView
**Declaration:**
```csharp
public interface IAddCalculatedChannelView : IBaseView { }
```
A marker interface extending `IBaseView`. Contains no members.
---
### IAddCalculatedChannelViewModel
**Declaration:**
```csharp
public interface IAddCalculatedChannelViewModel : IBaseViewModel
```
**Properties:**
| Name | Type | Access | Description |
|------|------|--------|-------------|
| `View` | `IBaseView` | get/set | The Search View associated with this viewmodel. |
| `Parent` | `IBaseViewModel` | get/set | Reference to the parent viewmodel in the hierarchy. |
| `IncludeGroupNameInISOExport` | `bool` | get/set | Controls whether group names are included in ISO export output. |
| `DefaultDTSEncoding` | `int` | get/set | The default DTS encoding value for calculated channels. |
| `AddCalculatedChannelCommand` | `ICommand` | get | Command to add a calculated channel. |
| `ContextSearchRegion` | `object` | get/set | Context object for the search region. |
**Methods:**
| Name | Return Type | Description |
|------|-------------|-------------|
| `PublishChanges()` | `void` | Publishes or commits pending changes. Behavior specifics not documented in source. |
---
## 3. Invariants
- `IAddCalculatedChannelView` must always be assignable to `IBaseView`.
- `IAddCalculatedChannelViewModel` must always be assignable to `IBaseViewModel`.
- `AddCalculatedChannelCommand` is read-only (getter only); it cannot be replaced after initialization, only executed.
- The presence of `Parent` property implies a hierarchical viewmodel structure that must be maintained.
---
## 4. Dependencies
**This module depends on:**
- `DTS.Common.Base` — Provides `IBaseView` and `IBaseViewModel` base interfaces.
- `System.Windows.Input` — Provides `ICommand` interface for the `AddCalculatedChannelCommand` property.
**Consumers:**
- Unknown from source alone. These interfaces are intended to be implemented by concrete view and viewmodel classes elsewhere in the codebase.
---
## 5. Gotchas
- **Namespace mismatch:** Both files include `// ReSharper disable CheckNamespace`, indicating the declared namespace (`DTS.Common.Interface`) may not match the folder structure (`Common/DTS.CommonCore/Interface/DTS.Viewer/CalculatedChannel/`). This could cause confusion when locating files or during refactoring.
- **Marker interface:** `IAddCalculatedChannelView` has no members and serves only as a type marker. Any view-specific behavior must come from `IBaseView` or be cast to a more specific type.
- **`ContextSearchRegion` type:** The property is typed as `object`, suggesting loose typing. The actual expected type and usage pattern is unclear from source alone.
- **`PublishChanges()` semantics:** The method name suggests an event-publishing or change-commit pattern, but the exact behavior (what changes are published, to whom, and when this should be called) is not documented in the source.

View File

@@ -0,0 +1,172 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/ChartOptions/IChartOptionsView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ChartOptions/IChartOptionsViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/ChartOptions/IChartOptionsModel.cs
generated_at: "2026-04-16T12:25:32.635258+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "a0d576d041a71e53"
---
# Documentation: Chart Options Interfaces
## 1. Purpose
This module defines the contract for chart configuration and visualization options within the DTS system. It provides three interfaces (`IChartOptionsView`, `IChartOptionsViewModel`, `IChartOptionsModel`) that follow an MVVM (Model-View-ViewModel) pattern to manage chart display settings including axis scaling, cursors, unit types, filtering, and export functionality. These interfaces enable decoupled communication between UI components and business logic for chart rendering.
---
## 2. Public Interface
### IChartOptionsView
**Namespace:** `DTS.Common.Interface`
A marker interface extending `IBaseView` with no additional members.
```csharp
public interface IChartOptionsView : IBaseView { }
```
---
### IChartOptionsViewModel
**Namespace:** `DTS.Common.Interface`
Extends `IBaseViewModel` and coordinates between the view and model for chart options.
| Member | Type | Description |
|--------|------|-------------|
| `View` | `IBaseView` | Gets or sets the Search View. |
| `Parent` | `IBaseViewModel` | Gets or sets the parent view model. |
| `Model` | `IChartOptionsModel` | Gets or sets the associated chart options model. |
| `ContextSearchRegion` | `object` | Gets or sets a context search region object. |
**Methods:**
| Method | Signature | Description |
|--------|-----------|-------------|
| `PublishChanges` | `void PublishChanges()` | Publishes pending changes. |
| `ResetZoomMethod` | `void ResetZoomMethod()` | Resets the chart zoom. |
| `ResetTMethod` | `void ResetTMethod()` | Resets the time axis. |
| `SaveToPDFMethod` | `void SaveToPDFMethod()` | Saves the chart to PDF. |
| `ShowCusor` | `void ShowCusor(bool value)` | Shows or hides the cursor. |
| `ShowMinMaxCursor` | `void ShowMinMaxCursor(bool value)` | Shows or hides the min/max cursor. |
---
### IChartOptionsModel
**Namespace:** `DTS.Common.Interface`
Extends `IBaseModel` and holds all chart configuration state and commands.
**ADC/mV Display Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `SupportsADC` | `bool` | True if all channels support ADC. |
| `SupportsMV` | `bool` | True if all channels support mV. |
| `DisplayingVolts` | `bool` | Indicates if current mV option is for Volts or mV. |
| `MVOrV` | `string` | Returns "mV" or "V" depending on `DisplayingVolts` value. |
**Y-Axis Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `FullScaleValues` | `List<double>` | Available full scale values. |
| `SelectedFullScaleValue` | `double` | Currently selected full scale value. |
| `MinFixedY` | `double` | Minimum fixed Y value. |
| `MaxFixedY` | `double` | Maximum fixed Y value. |
| `LockedY` | `bool` | Indicates if Y-axis is locked. |
| `YRange` | `YRangeScaleEnum` | Y-axis range scale setting. |
| `UnitType` | `ChartUnitTypeEnum` | Chart unit type. |
| `UnitTypeDescription` | `string` | Description of the unit type (getter only). |
**Time Axis Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `MinFixedT` | `double` | Minimum fixed T value. |
| `MaxFixedT` | `double` | Maximum fixed T value. |
| `LockedT` | `bool` | Indicates if T-axis is locked. |
| `TimeUnitType` | `TimeUnitTypeEnum` | Time unit type setting. |
**Cursor Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `ShowCursor` | `bool` | Indicates if cursor is shown. |
| `CurrentCursorValues` | `string` | Current cursor values as string. |
| `IsCursorsAvailable` | `bool` | Indicates if cursors are available. |
**Filter Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `Filter` | `FilterOptionEnum` | Filter option setting. |
| `SelectedFilter` | `IFilterClass` | Selected filter class instance. |
**Other Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `Parent` | `IChartOptionsViewModel` | Parent view model reference. |
| `CanPublishChanges` | `bool` | Indicates if changes can be published. |
| `ReadData` | `bool` | Indicates if data should be read. |
| `IsDigitalChannel` | `bool` | Indicates if channel is digital. |
| `DecimateData` | `bool` | Indicates if data should be decimated. |
| `WidthPoints` | `long` | Width points value. |
**Commands:**
| Property | Type | Description |
|----------|------|-------------|
| `ResetZoomCommand` | `DelegateCommand` | Command to reset zoom. |
| `ResetTCommand` | `DelegateCommand` | Command to reset time axis. |
| `SaveToPDFCommand` | `DelegateCommand` | Command to save to PDF. |
---
## 3. Invariants
1. **Namespace Mismatch:** All three interfaces are declared in `DTS.Common.Interface` namespace, despite the file path suggesting `DTS.Viewer.ChartOptions`. The `// ReSharper disable CheckNamespace` directive indicates this is intentional.
2. **MVVM Hierarchy:**
- `IChartOptionsView` must implement `IBaseView`
- `IChartOptionsViewModel` must implement `IBaseViewModel`
- `IChartOptionsModel` must implement `IBaseModel`
3. **Parent-Child Relationships:**
- `IChartOptionsModel.Parent` must reference the `IChartOptionsViewModel` that owns it
- `IChartOptionsViewModel.Model` must reference the `IChartOptionsModel` it manages
4. **Unit Display Logic:** `MVOrV` property return value is determined by `DisplayingVolts` state.
5. **Command Availability:** The model exposes commands as `DelegateCommand` (Prism), implying they follow the `ICommand` pattern with execute/can-execute semantics.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` - Provides `IBaseView`, `IBaseViewModel`, `IBaseModel`
- `DTS.Common.Enums.Viewer` - Provides `YRangeScaleEnum`, `ChartUnitTypeEnum`, `TimeUnitTypeEnum`, `FilterOptionEnum`
- `DTS.Common.Interface.Sensors.SoftwareFilters` - Provides `IFilterClass`
- `Microsoft.Practices.Prism.Commands` - Provides `DelegateCommand`
- `System.Collections.Generic` - Provides `List<T>`
- `System.Windows.Input` - Provides `ICommand` (indirectly via `DelegateCommand`)
### What depends on this module:
- **Unclear from source alone** - No consumers are shown in these files. Likely implementations exist in a viewer/charting module.
---
## 5. Gotchas
1. **Typo in Method Name:** `ShowCusor(bool value)` is misspelled (should be `ShowCursor`). This typo is part of the public API and must be used as-is.
2. **Namespace/Path Inconsistency:** Files are located in `Common/DTS.CommonCore/Interface/DTS.Viewer/ChartOptions/` but declare namespace `DTS.Common.Interface`. The ReSharper suppression confirms this is deliberate but may cause confusion during navigation.
3. **Command vs Method Duplication:** `IChartOptionsModel` exposes `ResetZoomCommand`, `ResetTCommand`, `SaveToPDFCommand` while `IChartOptionsViewModel` exposes corresponding methods `ResetZoomMethod()`, `ResetTMethod()`, `SaveToPDFMethod()`. The relationship between these is not documented in the source.
4. **Mixed Naming Conventions:** Some methods use `Method` suffix (e.g., `ResetZoomMethod`) while properties use `Command` suffix (e.g., `ResetZoomCommand`). The rationale is unclear from source alone.

View File

@@ -0,0 +1,67 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/Filter/IFilterView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Filter/IFilterViewModel.cs
generated_at: "2026-04-16T12:24:10.338285+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "0d8966c24bd001af"
---
# Documentation: DTS.Common.Interface Filter Components
## 1. Purpose
This module defines the core interfaces for filter components within the DTS viewer system. It establishes a View-ViewModel contract for filter UI elements, following the MVVM (Model-View-ViewModel) pattern. The `IFilterView` and `IFilterViewModel` interfaces provide the abstraction layer that allows filter components to be integrated into the broader application architecture while maintaining separation between presentation and business logic.
---
## 2. Public Interface
### `IFilterView`
**Location:** `DTS.Common.Interface` namespace
**Inheritance:** `IBaseView`
A marker interface with no members. It extends `IBaseView` and serves to identify views that are specifically filter views within the type system.
---
### `IFilterViewModel`
**Location:** `DTS.Common.Interface` namespace
**Inheritance:** `IBaseViewModel`
| Property | Type | Accessor | Description |
|----------|------|----------|-------------|
| `View` | `IBaseView` | `get; set;` | Gets or sets the Search View associated with this filter view model. |
| `Parent` | `IBaseViewModel` | `get; set;` | Gets or sets the parent view model in the hierarchy. |
| `ContextSearchRegion` | `object` | `get; set;` | Gets or sets a context object for the search region. Purpose unclear from source alone. |
---
## 3. Invariants
- **Type Hierarchy:** `IFilterView` must always be assignable to `IBaseView`. `IFilterViewModel` must always be assignable to `IBaseViewModel`.
- **View Association:** The `View` property on `IFilterViewModel` is typed as `IBaseView` (not `IFilterView`), suggesting the view model may be associated with views broader than just filter views.
- **Parent-Child Relationship:** The `Parent` property establishes a hierarchical relationship between view models, though no validation or lifecycle management is defined at this interface level.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` — Provides `IBaseView` and `IBaseViewModel` base interfaces
### What depends on this module:
- **Cannot be determined from source alone.** No imports or usages are visible in the provided files.
---
## 5. Gotchas
1. **Namespace suppression:** The file `IFilterViewModel.cs` contains a `// ReSharper disable CheckNamespace` directive, suggesting the declared namespace (`DTS.Common.Interface`) may not match the project's default namespace structure. This could indicate a historical refactoring or organizational inconsistency.
2. **Weakly-typed context:** The `ContextSearchRegion` property is typed as `object`, providing no compile-time type safety. Consumers must know the expected runtime type through external documentation or convention.
3. **Missing XML documentation:** Only the `View` property has XML documentation (`<summary>` comment). The `Parent` and `ContextSearchRegion` properties lack documentation, leaving their intended usage and semantics unclear.
4. **Marker interface with no contract:** `IFilterView` defines no members beyond inheriting `IBaseView`. Its purpose appears to be purely for type identification, but the specific behaviors or capabilities it signals are not documented in source.

View File

@@ -0,0 +1,224 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphMainView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphChannelView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphPropertyView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/ITestDataView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphPropertyViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/ITestDataSeriesView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/ITestDataViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/ITestDataSeriesViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphChannelViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/IGraphMainViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Graphs/ITestDataSeries.cs
generated_at: "2026-04-16T12:24:37.475119+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "99208da86b0faad5"
---
# Documentation: DTS.Common.Interface Graph Module
## 1. Purpose
This module defines the interface contracts for a graph visualization subsystem following the Model-View-ViewModel (MVVM) architectural pattern. It provides abstractions for rendering test data series, managing graph channels, editing graph properties, and coordinating channel selection/locking across the application. The interfaces serve as boundaries between UI components and business logic, enabling test-driven development and loose coupling between the graph visualization components and their consumers.
---
## 2. Public Interface
### View Interfaces
#### `IGraphMainView`
- **Signature:** `public interface IGraphMainView : IBaseView`
- **Behavior:** Marker interface for the main graph view container. No members defined; extends `IBaseView`.
#### `IGraphChannelView`
- **Signature:** `public interface IGraphChannelView : IBaseView`
- **Behavior:** Marker interface for the graph channel selection/configuration view. No members defined; extends `IBaseView`.
#### `IGraphPropertyView`
- **Signature:** `public interface IGraphPropertyView : IBaseView`
- **Behavior:** Marker interface for the graph property editing view. No members defined; extends `IBaseView`.
#### `ITestDataView`
- **Signature:** `public interface ITestDataView : IBaseView`
- **Behavior:** Marker interface for the test data view. No members defined; extends `IBaseView`.
#### `ITestDataSeriesView`
- **Signature:** `public interface ITestDataSeriesView : IBaseView`
- **Members:**
- `bool SaveReportToPDF(string directory)` — Exports the report to PDF format to the specified directory.
- `bool SaveReportToCSV(string directory)` — Exports the report to CSV format to the specified directory.
- **Behavior:** Provides export capabilities for test data series reports.
#### `IGraphView`
- **Signature:** `public interface IGraphView : IBaseView`
- **Members:**
- `//void SetGraphs(ObservableCollection<ITestDataSeries> graphs);` (commented out)
- **Behavior:** Marker interface for the graph rendering view. Contains one commented-out method for setting graph collections.
---
### ViewModel Interfaces
#### `IGraphPropertyViewModel`
- **Signature:** `public interface IGraphPropertyViewModel : IBaseViewModel`
- **Members:**
- `IGraphPropertyView View { get; }` — Gets the associated property view.
- **Behavior:** ViewModel contract for managing graph property view state.
#### `IGraphViewModel`
- **Signature:** `public interface IGraphViewModel : IBaseViewModel`
- **Members:**
- `IGraphView View { get; }` — Gets the associated graph view.
- `ITestDataSeriesView DataSeriesView { get; set; }` — Gets or sets the data series view.
- **Behavior:** ViewModel contract for the main graph view coordination.
#### `ITestDataViewModel`
- **Signature:** `public interface ITestDataViewModel : IBaseViewModel`
- **Members:**
- `ITestDataView View { get; set; }` — Gets or sets the associated test data view.
- `ITestDataSeries Model { get; set; }` — Gets or sets the underlying test data series model.
- **Behavior:** ViewModel contract for test data display and editing.
#### `ITestDataSeriesViewModel`
- **Signature:** `public interface ITestDataSeriesViewModel : IBaseViewModel`
- **Members:**
- `ITestDataSeriesView View { get; set; }` — Gets or sets the associated view.
- `ITestDataSeries Model { get; set; }` — Gets or sets the underlying test data series model.
- `void MoveCursor(object sender, KeyEventArgs e)` — Handles cursor movement events.
- `string CurrentCursorValues { get; set; }` — Gets or sets the current cursor position values for display.
- **Behavior:** ViewModel for test data series with interactive cursor functionality.
#### `IGraphChannelViewModel`
- **Signature:** `public interface IGraphChannelViewModel : IBaseViewModel`
- **Members:**
- `IGraphChannelView View { get; }` — Gets the associated channel view.
- `ObservableCollection<ITestChannel> GraphChannelList { get; set; }` — Collection of all available graph channels.
- `ObservableCollection<ITestChannel> SelectedGraphChannelList { get; set; }` — Collection of currently selected graph channels.
- `TestChannel SelectedGraphChannel { get; set; }` — The currently single-selected graph channel.
- **Behavior:** ViewModel for managing graph channel selection and display.
#### `IGraphMainViewModel`
- **Signature:** `public interface IGraphMainViewModel : IBaseViewModel`
- **Members:**
- `IGraphMainView View { get; set; }` — Gets or sets the main graph view.
- `IBaseViewModel Parent { get; set; }` — Gets or sets the parent ViewModel reference.
- `List<ITestChannel> LockedChannelList { get; set; }` — List of locked channels.
- `List<ITestChannel> SelectedChannelList { get; set; }` — List of selected channels.
- `string LockedGroupName { get; set; }` — Name of the locked group.
- `void PublishSelectedChannels()` — Publishes the current channel selection.
- `void AddSelectedChannel(ITestChannel channel)` — Adds a single channel to the selection.
- `void AddSelectedGroupChannels(string groupName, List<ITestChannel> channels)` — Adds multiple channels from a group to the selection.
- `void AddLockedChannel(ITestChannel channel, bool isLocked)` — Adds or updates a channel's locked state.
- `void AddLockedGroupChannels(string testName, string groupName, List<ITestChannel> channels, bool isLocked)` — Adds or updates multiple channels' locked state as a group.
- `void GraphList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)` — Handler for graph list collection changes.
- **Behavior:** Primary ViewModel for graph coordination, managing channel selection and locking state.
---
### Model Interface
#### `ITestDataSeries`
- **Signature:** `public interface ITestDataSeries : IBaseModel`
- **Members (Identification):**
- `string TestGroup { get; set; }`
- `string TestSetupName { get; set; }`
- `string TestId { get; set; }`
- `string ChannelId { get; set; }`
- `string HardwareChannel { get; set; }`
- `string Bridge { get; set; }`
- `string GroupName { get; set; }`
- `string ChannelName { get; set; }`
- `string Description { get; }`
- **Members (Data):**
- `double[] Xvalue { get; set; }` — X-axis data points.
- `double[] Yvalue { get; set; }` — Y-axis data points.
- `Brush GraphColor { get; set; }` — Visual color for the graph line.
- **Members (Configuration):**
- `string SWAAF { get; set; }`
- `string HWAAF { get; set; }`
- `string SampleRate { get; set; }`
- `string ISOCode { get; set; }`
- `string ISOChannelName { get; set; }`
- `string UserCode { get; set; }`
- `string UserChannelName { get; set; }`
- `string EngineeringUnits { get; set; }`
- `string Excitation { get; set; }`
- `string Polarity { get; set; }`
- `string RecordingMode { get; set; }`
- **Members (Sensor):**
- `string SensorSN { get; }`
- `string SensorSNDisplay { get; }`
- **Members (Statistics - read-only):**
- `string MinY { get; }`
- `string MaxY { get; }`
- `string AvgY { get; }`
- `string StdDevY { get; }`
- `string T0EUValue { get; }`
- **Members (FFT Analysis):**
- `bool FFT { get; }` — Indicates if this series is an FFT of signal data.
- `double PeakFrequency { get; }` — Peak frequency by magnitude (only populated when `FFT` is true).
- `double PeakMagnitude { get; }` — Peak magnitude of frequencies (only populated when `FFT` is true).
- `double GRMS { get; set; }` — Root-mean-squared acceleration (calculated in PSD results graphs).
- **Members (HIC - Head Injury Criterion):**
- `bool HIC { get; }` — Indicates if HIC calculation applies.
- `string HICValue { get; }`
- `string T1Time { get; }`
- `string T2Time { get; }`
- **Behavior:** Data model representing a complete test data series with metadata, raw data, and computed statistics. Supports both time-domain and frequency-domain (FFT) data representations.
---
## 3. Invariants
1. **Inheritance Hierarchy:** All view interfaces (`IGraphMainView`, `IGraphChannelView`, `IGraphPropertyView`, `ITestDataView`, `ITestDataSeriesView`, `IGraphView`) must extend `IBaseView`.
2. **Inheritance Hierarchy:** All ViewModel interfaces (`IGraphPropertyViewModel`, `IGraphViewModel`, `ITestDataViewModel`, `ITestDataSeriesViewModel`, `IGraphChannelViewModel`, `IGraphMainViewModel`) must extend `IBaseViewModel`.
3. **Inheritance Hierarchy:** `ITestDataSeries` must extend `IBaseModel`.
4. **FFT Data Population:** `PeakFrequency` and `PeakMagnitude` are only valid when `FFT` is `true`. Consumers must check `FFT` before accessing these properties.
5. **GRMS Context:** `GRMS` is only calculated for PSD (Power Spectral Density) results graphs.
6. **Observable Collections:** `IGraphChannelViewModel` uses `ObservableCollection<ITestChannel>` for both `GraphChannelList` and `SelectedGraphChannelList`, implying UI binding expectations for collection change notifications.
7. **Read-Only Statistics:** Statistical properties (`MinY`, `MaxY`, `AvgY`, `StdDevY`, `T0EUValue`, `PeakFrequency`, `PeakMagnitude`) are read-only and presumably computed from `Xvalue` and `Yvalue` arrays.
---
## 4. Dependencies
### This Module Depends On:
| Dependency | Usage |
|------------|-------|
| `DTS.Common.Base` | `IBaseView`, `IBaseViewModel`, `IBaseModel` base interfaces |
| `DTS.Common.Classes.Viewer.TestMetadata` | `TestChannel`, `ITestChannel` types |
| `DTS.Common.Events` | Referenced in `ITestDataSeriesView.cs` (specific types not visible in source) |
| `System.Windows.Input` | `KeyEventArgs` in `ITestDataSeriesViewModel` |
| `System.Windows.Media` | `Brush` type in `ITestDataSeries` |
| `System.Collections.ObjectModel` | `ObservableCollection<T>` |
| `System.Collections.Specialized` | `NotifyCollectionChangedEventArgs` |
### What Depends On This Module:
**Cannot be determined from source alone.** This module defines only interfaces; consumers would be concrete implementations and other modules that reference these contracts.
---
## 5. Gotchas
1. **Namespace Inconsistency:** Four files (`ITestDataView.cs`, `ITestDataSeriesView.cs`, `IGraphView.cs`, `ITestDataSeriesViewModel.cs`, `IGraphMainViewModel.cs`, `ITestDataSeries.cs`) contain `// ReSharper disable CheckNamespace`, suggesting the declared namespace `DTS.Common.Interface` may not match the file path structure. This could cause confusion when locating types.
2. **Commented-Out Code:** `IGraphView` contains a commented-out method `SetGraphs(ObservableCollection<ITestDataSeries> graphs)`. The reason for its removal and whether it should be restored or permanently deleted is unclear from source.
3. **Malformed XML Comment:** In `ITestDataSeries.cs`, the XML comment for `PeakMagnitude` has a malformed closing tag (`</summary<` instead of `</summary>`), which may break documentation generation tools.
4. **Mixed Collection Types:** `IGraphChannelViewModel` uses `ObservableCollection<ITestChannel>` while `IGraphMainViewModel` uses `List<ITestChannel>`. This inconsistency in collection types across related ViewModels may indicate differing lifecycle or notification requirements, but could also be an oversight.
5. **Type Mismatch in `IGraphChannelViewModel`:** The `SelectedGraphChannel` property is typed as `TestChannel` (concrete class), while the collections use `ITestChannel` (interface). This breaks consistency with the interface-based design pattern used elsewhere.
6. **Setter Accessibility:** Several read-only properties in `ITestDataSeries` (e.g., `Description`, `SensorSN`, `MinY`, `MaxY`, etc.) have only getters, but it's unclear whether these are computed properties or set via constructor/mutable backing field. The implementation strategy is not specified.

View File

@@ -0,0 +1,74 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/Legend/ILegendView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/Legend/ILegendViewModel.cs
generated_at: "2026-04-16T12:22:08.946405+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "fa541836d2cec79b"
---
# Documentation: ILegendView / ILegendViewModel
## 1. Purpose
This module defines the core interfaces for a Legend component within a Viewer system, following the MVVM (Model-View-ViewModel) architectural pattern. `ILegendView` represents the view abstraction for legend visualization, while `ILegendViewModel` defines the contract for its corresponding ViewModel, establishing the relationship between the two layers. These interfaces enable decoupled communication between the legend's presentation logic and its UI rendering.
---
## 2. Public Interface
### `ILegendView`
**Namespace:** `DTS.Common.Interface`
**Inherits:** `IBaseView`
A marker interface representing a legend view component. No members are defined beyond those inherited from `IBaseView`.
```csharp
public interface ILegendView : IBaseView { }
```
---
### `ILegendViewModel`
**Namespace:** `DTS.Common.Interface`
**Inherits:** `IBaseViewModel`
Defines the contract for a legend ViewModel with access to its associated view.
| Member | Type | Access | Description |
|--------|------|--------|-------------|
| `View` | `ILegendView` | `get` | Returns the associated `ILegendView` instance for this ViewModel. |
```csharp
public interface ILegendViewModel : IBaseViewModel
{
ILegendView View { get; }
}
```
---
## 3. Invariants
- `ILegendViewModel.View` must return a non-null `ILegendView` instance when accessed (implied by the contract, though nullability annotations are not present in the source).
- Both interfaces must maintain their inheritance from `IBaseView` and `IBaseViewModel` respectively, ensuring consistency with the broader view/viewmodel hierarchy.
- The `View` property on `ILegendViewModel` is read-only (getter only), suggesting the view association is established at construction or through internal mechanisms, not via public setters.
---
## 4. Dependencies
### This module depends on:
- `DTS.Common.Base` — Provides `IBaseView` and `IBaseViewModel` base interfaces from which these interfaces inherit.
### What depends on this module:
- **Cannot be determined from source alone.** Consumers would include concrete implementations of `ILegendView` and `ILegendViewModel`, as well as any components that render or interact with legend functionality.
---
## 5. Gotchas
- **Marker Interface:** `ILegendView` defines no members of its own. All functionality comes from `IBaseView`. Developers should consult `IBaseView` to understand available members.
- **Tight Coupling via Property:** The `ILegendViewModel.View` property creates a direct reference from the ViewModel to the View, which is a deviation from pure MVVM where ViewModels are typically view-agnostic. The rationale for this design choice is not documented in the source.
- **Missing Nullability Annotations:** The source lacks C# 8.0+ nullable reference type annotations, making it unclear whether `View` is guaranteed to be non-null.

View File

@@ -0,0 +1,143 @@
---
source_files:
- Common/DTS.CommonCore/Interface/DTS.Viewer/MainView/IMainView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/MainView/IViewerMainView.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/MainView/IViewerMainViewGrid.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/MainView/IMainViewModel.cs
- Common/DTS.CommonCore/Interface/DTS.Viewer/MainView/IViewerMainViewModel.cs
generated_at: "2026-04-16T12:24:51.311433+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "95ec9f6198f586ac"
---
# Documentation: DTS.Common.Interface MainView Interfaces
## 1. Purpose
This module defines the core view and ViewModel interfaces for the main window of a DTS Viewer application. It establishes the contract for a modular, region-based UI layout using what appears to be a MVVM (Model-View-ViewModel) architecture. The interfaces support multiple UI regions (navigation, graphs, tests, legends, diagnostics, statistics, cursor, and property panels) and provide keyboard interaction handling, zoom control, and configuration management for a data visualization and analysis tool.
---
## 2. Public Interface
### View Interfaces
#### `IMainView`
```csharp
public interface IMainView : IBaseView { }
```
Marker interface for a main view component. Extends `IBaseView`. No members defined.
#### `IViewerMainView`
```csharp
public interface IViewerMainView : IBaseView { }
```
Marker interface for a viewer main view component. Extends `IBaseView`. No members defined.
#### `IViewerMainViewGrid`
```csharp
public interface IViewerMainViewGrid : IBaseView { }
```
Marker interface for a viewer main view grid component. Extends `IBaseView`. No members defined.
---
### ViewModel Interfaces
#### `IMainViewModel`
```csharp
public interface IMainViewModel : IBaseViewModel
```
| Member | Type | Access | Description |
|--------|------|--------|-------------|
| `View` | `IBaseView` | `get` | Gets the Main View instance |
| `ContextNavigationRegion` | `object` | `get; set` | Navigation region context |
| `ContextGraphRegion` | `object` | `get; set` | Graph region context |
| `ContextTestsRegion` | `object` | `get; set` | Tests region context |
| `ContextGraphsRegion` | `object` | `get; set` | Graphs region context |
| `ContextLegendRegion` | `object` | `get; set` | Legend region context |
| `ContextDiagRegion` | `object` | `get; set` | Diagnostics region context |
| `ContextStatsRegion` | `object` | `get; set` | Statistics region context |
| `ContextCursorRegion` | `object` | `get; set` | Cursor region context |
| `ContextPropertyRegion` | `object` | `get; set` | Property region context |
| `GetRegions()` | `List<FrameworkElement>` | method | Returns a list of all region FrameworkElements |
---
#### `IViewerMainViewModel`
```csharp
public interface IViewerMainViewModel : IBaseViewModel, ISelectedDataViewModel
```
| Member | Type | Access | Description |
|--------|------|--------|-------------|
| `View` | `IBaseView` | `get; set` | Gets or sets the Main View instance |
| `Standalone` | `bool` | `get; set` | Indicates if viewer is running in standalone mode |
| `ContextNavigationRegion` | `object` | `get; set` | Navigation region context |
| `ContextGraphRegion` | `object` | `get; set` | Graph region context |
| `ContextTestsRegion` | `object` | `get; set` | Tests region context |
| `ContextGraphsRegion` | `object` | `get; set` | Graphs region context |
| `ContextLegendRegion` | `object` | `get; set` | Legend region context |
| `ContextDiagRegion` | `object` | `get; set` | Diagnostics region context |
| `ContextStatsRegion` | `object` | `get; set` | Statistics region context |
| `ContextCursorRegion` | `object` | `get; set` | Cursor region context |
| `ContextPropertyRegion` | `object` | `get; set` | Property region context |
| `GetRegions()` | `List<FrameworkElement>` | method | Returns a list of all region FrameworkElements |
| `ConfigPath` | `string` | `get; set` | Path to configuration file |
| `DoesUserHaveEditPermission` | `bool` | `get; set` | User edit permission flag |
| `ZoomReset()` | `void` | method | Resets zoom to default state |
| `LeftKeyPress()` | `void` | method | Handles left arrow key press notification |
| `RightKeyPress()` | `void` | method | Handles right arrow key press notification |
| `ChannelCodeViewMode` | `Common.Enums.IsoViewMode` | `get; set` | Channel code view mode setting |
| `CalibrationBehaviorSetting` | `Common.Enums.Sensors.CalibrationBehaviors` | `get; set` | Calibration behavior configuration |
| `CalibrationBehaviorSettableInViewer` | `bool` | `get; set` | Whether calibration behavior can be set in viewer |
| `SettingsVisibility` | `Visibility` | `get` | Visibility state of settings UI |
---
## 3. Invariants
1. **Namespace Mismatch**: All interfaces are declared in namespace `DTS.Common.Interface` despite file paths suggesting `DTS.Viewer.MainView` sub-namespaces. The ReSharper disable comments indicate this is intentional.
2. **Region Context Types**: All `Context*Region` properties are typed as `object`, suggesting late binding or multiple possible region types. Implementations must handle assignment of appropriate region types.
3. **View Property Mutability**: `IMainViewModel.View` is read-only (`get`), while `IViewerMainViewModel.View` is read-write (`get; set`). Implementations must respect this difference.
4. **Inheritance Chain**:
- All view interfaces must implement `IBaseView`
- `IMainViewModel` must implement `IBaseViewModel`
- `IViewerMainViewModel` must implement both `IBaseViewModel` and `ISelectedDataViewModel`
5. **GetRegions() Contract**: Must return a non-null `List<FrameworkElement>` containing the UI regions.
---
## 4. Dependencies
### External Dependencies (Imports)
| Namespace | Usage |
|-----------|-------|
| `DTS.Common.Base` | `IBaseView`, `IBaseViewModel`, `ISelectedDataViewModel` base types |
| `System.Collections.Generic` | `List<T>` for `GetRegions()` return type |
| `System.Windows` | `FrameworkElement`, `Visibility` types |
| `Common.Enums` | `IsoViewMode` enum |
| `Common.Enums.Sensors` | `CalibrationBehaviors` enum |
### Downstream Dependencies
**Unclear from source alone** - These are interface definitions; concrete implementations and consumers are not present in the provided files.
---
## 5. Gotchas
1. **Namespace Inconsistency**: The file paths suggest namespaces like `DTS.Viewer.MainView`, but all interfaces are declared in `DTS.Common.Interface`. The `// ReSharper disable CheckNamespace` directives indicate this mismatch is known and suppressed. New developers should be aware that file location does not match declared namespace.
2. **View Property Asymmetry**: `IMainViewModel.View` is read-only while `IViewerMainViewModel.View` is read-write. This inconsistency could cause confusion when implementing or consuming these interfaces.
3. **Magic Object Types**: All region context properties use `object` type rather than specific region interfaces. The actual types expected/returned are unclear from the source alone.
4. **Duplicate Region Definitions**: Both `IMainViewModel` and `IViewerMainViewModel` define identical region properties. This suggests either parallel evolution or a design that could benefit from a shared base interface for region management.
5. **Partial Enum Paths**: The types `Common.Enums.IsoViewMode` and `Common.Enums.Sensors.CalibrationBehaviors` are referenced but their definitions are not provided, making their exact values and usage unclear from this source alone.

Some files were not shown because too many files have changed in this diff Show More