Files
DP44/docs/ai/Common/DTS.Common/Utils.md

303 lines
17 KiB
Markdown
Raw Normal View History

2026-04-17 14:55:32 -04:00
---
source_files:
- Common/DTS.Common/Utils/XMLUtils.cs
- Common/DTS.Common/Utils/EnumUtils.cs
- Common/DTS.Common/Utils/ValueStopWatch.cs
- Common/DTS.Common/Utils/ImageButton.cs
- Common/DTS.Common/Utils/PNGImageUtil.cs
- Common/DTS.Common/Utils/MouseUtils.cs
- Common/DTS.Common/Utils/StopWatch.cs
- Common/DTS.Common/Utils/SerializableDictionary.cs
- Common/DTS.Common/Utils/TestUtils.cs
- Common/DTS.Common/Utils/IPUtils.cs
- Common/DTS.Common/Utils/SecureQueue.cs
- Common/DTS.Common/Utils/ByteConverter.cs
- Common/DTS.Common/Utils/NetworkUtils.cs
- Common/DTS.Common/Utils/BusyWaitAnimation.cs
generated_at: "2026-04-17T15:28:48.852804+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "bbe4ae29c7962c3d"
---
# DTS.Common.Utils Documentation
## 1. Purpose
The `DTS.Common.Utils` namespace provides a collection of utility classes supporting common operations across the DTS system, including timing/diagnostics (`ValueStopwatch`, `StopWatchQueue`), byte manipulation with network byte order conversion (`ByteConvertor`), thread-safe queue management (`SecureQueue<T>`), network interface inspection (`NetworkUtils`, `IPUtils`), WPF UI components (`ImageButton`, `BusyWaitAnimation`), XML serialization helpers (`SerializableDictionary`), and various data parsing utilities (`TestUtils`, `EnumUtil`, `PNGImageUtil`, `MouseUtilities`). This module serves as a foundational utility layer for the broader DTS application ecosystem.
---
## 2. Public Interface
### ByteConvertor
**File:** `ByteConverter.cs`
| Method | Signature | Description |
|--------|-----------|-------------|
| `Convert` | `static void Convert(byte[] input, int offset, out byte value)` | Extracts a single byte at the specified offset. |
| `Convert` | `static void Convert(byte[] input, int offset, out ushort value)` | Converts 2 bytes starting at offset to `ushort` in network byte order (big-endian). |
| `Convert` | `static void Convert(byte[] input, int offset, out short value)` | Converts 2 bytes starting at offset to `short` in network byte order. |
| `Convert` | `static void Convert(byte[] input, int offset, out uint value)` | Converts 4 bytes starting at offset to `uint` in network byte order. |
| `Convert` | `static void Convert(byte[] input, int offset, out int value)` | Converts 4 bytes starting at offset to `int` in network byte order. |
| `Convert` | `static void Convert(byte[] input, int offset, out ulong value)` | Converts 8 bytes starting at offset to `ulong` in network byte order. |
| `Convert` | `static void Convert(byte[] input, int offset, out long value)` | Converts 8 bytes starting at offset to `long` in network byte order. |
| `Convert` | `static void Convert(byte[] input, int offset, out float value)` | Converts bytes to `float` using `BitConverter.ToSingle`. |
| `Convert` | `static void Convert(byte[] input, int offset, out double value)` | Converts bytes to `double` using `BitConverter.ToDouble`. |
| `Convert` | `static void Convert(byte[] input, int offset, out string value)` | Extracts null-terminated ASCII string starting at offset. |
| `ToByteArray` | `static byte[] ToByteArray(string input)` | Converts string to null-terminated byte array. |
| `ToByteArray` | `static byte[] ToByteArray(byte input)` | Wraps single byte in array. |
| `ToByteArray` | `static byte[] ToByteArray(ushort input)` | Converts to 2-byte array in network byte order. |
| `ToByteArray` | `static byte[] ToByteArray(short input)` | Converts to 2-byte array in network byte order. |
| `ToByteArray` | `static byte[] ToByteArray(uint input)` | Converts to 4-byte array in network byte order. |
| `ToByteArray` | `static byte[] ToByteArray(int input)` | Converts to 4-byte array in network byte order. |
| `ToByteArray` | `static byte[] ToByteArray(ulong input)` | Converts to 8-byte array in network byte order. |
| `ToByteArray` | `static byte[] ToByteArray(float input)` | Converts using `BitConverter.GetBytes`. |
| `ToByteArray` | `static byte[] ToByteArray(double input)` | Converts using `BitConverter.GetBytes`. |
---
### EnumUtil
**File:** `EnumUtils.cs`
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetValues<T>` | `static IEnumerable<T> GetValues<T>()` | Returns all values of enum type `T`. |
| `GetValuesList<T>` | `static ItemCollection GetValuesList<T>()` | Returns an `ItemCollection` populated with enum values and names, for use with Xceed WPF Toolkit PropertyGrid. |
---
### ValueStopwatch
**File:** `ValueStopWatch.cs`
A readonly struct for high-performance timing.
| Member | Signature | Description |
|--------|-----------|-------------|
| `StartNew` | `static ValueStopwatch StartNew()` | Factory method that creates a new instance capturing the current timestamp. |
| `GetElapsedTime` | `TimeSpan GetElapsedTime()` | Returns elapsed time since construction. Uses `Stopwatch.Frequency` for timestamp conversion. |
---
### StopWatchQueue
**File:** `StopWatch.cs`
A diagnostic queue that records timing samples and dumps statistics to CSV.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `StopWatchQueue(string name)` | Initializes with a name used for output filename. |
| `Start` | `void Start()` | Starts the internal `Stopwatch`. |
| `Stop` | `void Stop()` | Records elapsed ticks to queue and resets the stopwatch. |
| `DumpData` | `void DumpData()` | Writes all recorded samples to CSV file with min/max/average/stddev statistics. |
| `Flush` | `void Flush()` | Clears the queue and resets the event. |
---
### SecureQueue\<T\>
**File:** `SecureQueue.cs`
A thread-safe queue with configurable null handling and wait capabilities.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `SecureQueue(NullPolicy policy, string name)` | Initializes with null handling policy and name for logging. |
| `Enqueue` | `void Enqueue(T[] newData)` | Adds a **cloned copy** of the array to the queue. Behavior with null/empty depends on `NullPolicy`. |
| `Dequeue` | `T[] Dequeue(bool resetEvent)` | Removes and returns all queued items concatenated into a single array. Returns empty array if queue is empty. |
| `WaitForData` | `bool WaitForData(int timeoutMillisec)` | Blocks until data arrives or timeout. Returns `true` if data available. |
| `Flush` | `void Flush()` | Clears all queued data. |
| `IsEmpty` | `bool IsEmpty()` | Returns `true` if queue has no items. |
| `ResetEvent` | `void ResetEvent()` | Resets the internal `ManualResetEvent`. |
| `QueueWaitHandle` | `WaitHandle QueueWaitHandle { get; }` | Exposes the wait handle for external synchronization. |
| `Dispose` | `void Dispose()` | Implements `IDisposable` (currently empty implementation). |
**Nested Enum:**
```csharp
public enum NullPolicy
{
DenyNull, // Throws ArgumentException on null/empty enqueue
SkipNull, // Silently ignores null/empty enqueue
AllowNull // Permits null/empty values
}
```
---
### ImageButton
**File:** `ImageButton.cs`
A WPF `Button` subclass displaying an image above text.
| Property | Type | Description |
|----------|------|-------------|
| `Source` | `ImageSource` | The image displayed in the button. |
| `ImageText` | `string` | The text displayed below the image. |
---
### PNGImageUtil
**File:** `PNGImageUtil.cs`
| Method | Signature | Description |
|--------|-----------|-------------|
| `SaveImage` | `static void SaveImage(FrameworkElement view, string fileName)` | Renders a `FrameworkElement` to a PNG file at 96 DPI. Uses `RenderTargetBitmap` and `PngBitmapEncoder`. |
---
### MouseUtilities
**File:** `MouseUtils.cs`
| Method | Signature | Description |
|--------|-----------|-------------|
| `GetMousePosition` | `static Point GetMousePosition(Visual relativeTo)` | Returns mouse cursor position relative to the specified `Visual`. Uses Win32 `GetCursorPos` and `ScreenToClient` P/Invoke calls. |
---
### NetworkUtils
**File:** `NetworkUtils.cs`
| Member | Signature | Description |
|--------|-----------|-------------|
| `IsNetworkInterfaceUp` | `static bool IsNetworkInterfaceUp(IPAddress ip)` | Checks if a network interface with the specified IP is operational. |
| `GetAvailableHosts` | `static List<HostInfo> GetAvailableHosts(bool supportMulticastOnly = false)` | Returns available network hosts with IP, MAC, and address range info. Filters out virtual adapters, loopback, and low-speed interfaces. |
| `TryParseConnectionString` | `static bool TryParseConnectionString(string connectionString, out string ipAddress)` | Attempts to extract an IP address from a connection string (URI or colon-separated format). |
| `AllowInternalNICIPs` | `static bool AllowInternalNICIPs { get; set; }` | Controls whether 169.254.x.x addresses (link-local) are included in results. Default: `false`. |
---
### IPAddressIntForm
**File:** `IPUtils.cs`
Represents an IPv4 address as four integer octets.
| Member | Signature | Description |
|--------|-----------|-------------|
| Constructor | `IPAddressIntForm(int b1, int b2, int b3, int b4)` | Creates instance from four octets. |
| `ToString` | `override string ToString()` | Returns dotted-decimal notation (e.g., "192.168.1.1"). |
| `TryParse` | `static bool TryParse(string input, out IPAddressIntForm output)` | Parses dotted-decimal string to `IPAddressIntForm`. |
| `GetAllIPs` | `static string[] GetAllIPs(IPAddressIntForm a, IPAddressIntForm b)` | Returns all IP addresses between two endpoints (inclusive). |
**Nested Class:**
- `IPComparer` : `IComparer<IPAddressIntForm>` - Compares IPs byte-by-byte.
**Related Class:**
- `IPRange` - Holds `RangeStart` and `RangeEnd` of type `IPAddressIntForm`.
---
### TestUtils
**File:** `TestUtils.cs`
| Method | Signature | Description |
|--------|-----------|-------------|
| `MinUnixTime` | `static Tuple<double, double> MinUnixTime(IEnumerable<TestModuleTimeStamp> basemodules)` | Returns the minimum Unix timestamp (seconds, nanoseconds) from a collection, using statistical filtering (average minus standard deviation, capped at 10ms). Returns `null` if input is null or empty. |
| `ParseROISuffix` | `static string ParseROISuffix(string test)` | Parses a test string to extract ROI suffix based on event number markers. |
**Related Class:**
- `TestModuleTimeStamp` - POCO with `TriggerTimestampSec` (int) and `TriggerTimestampNanoSec` (int) properties.
---
### BusyWaitAnimation
**File:** `BusyWaitAnimation.cs`
A spinning circle animation control for indicating busy states.
| Property | Type | Description |
|----------|------|-------------|
| `Color` | `Color` | Color of the spokes. |
| `BgColor` | `Color` | Background color. |
| `OuterCircleRadius` | `int` | Radius of outer circle. Default: 10. |
| `InnerCircleRadius` | `int` | Radius of inner circle. Default: 8. |
| `NumberSpoke` | `int` | Number of spokes. Default: 10. |
| `SpokeThickness` | `int` | Thickness of each spoke. Default: 4. |
| `RotationSpeed` | `long` | Timer interval in ticks (higher = slower). |
| `Active` | `bool` | Starts/stops the animation. |
| `StylePreset` | `StylePresets` | Preset styles: `MacOsx`, `Firefox`, `Ie7`, `Custom`. |
| `hDC` | `int` | GDI device context handle for rendering. |
| `GDIGraphics` | `Graphics` | Exposes the internal GDI+ Graphics object. |
| Method | Signature | Description |
|--------|-----------|-------------|
| `SetDrawArea` | `void SetDrawArea(Rectangle rect)` | Sets the drawing area and initializes internal bitmaps. |
| `SetCircleAppearance` | `void SetCircleAppearance(int numberSpoke, int spokeThickness, int innerCircleRadius, int outerCircleRadius)` | Configures all visual parameters at once. |
---
### SerializableDictionary\<TKey, TValue\>
**File:** `SerializableDictionary.cs` (Note: namespace is `DTS.DASLib.Utility`)
| Member | Signature | Description |
|--------|-----------|-------------|
| `GetSchema` | `XmlSchema GetSchema()` | Returns `null`. |
| `ReadXml` | `void ReadXml(XmlReader reader)` | Deserializes from XML format with `<items>`, `<item>`, `<key>`, `<value>` structure. |
| `WriteXml` | `void WriteXml(XmlWriter writer)` | Serializes to XML with same structure. |
**Related Class:**
- `XmlDictionary` - Wrapper with `Dictionary` property of type `SerializableDictionary<string, object>`.
---
### XMLUtils
**File:** `XMLUtils.cs`
Empty class with no members. Purpose unclear from source alone.
---
## 3. Invariants
- **ByteConvertor**: All multi-byte integer conversions use **network byte order (big-endian)**. The `Convert` methods assume the input byte array is in network order; `ToByteArray` methods produce network order output.
- **SecureQueue\<T\>**: The generic constraint `where T : new()` requires a parameterless constructor. The `Dequeue` method always returns a non-null array (empty array if queue is empty).
- **ValueStopwatch**: As a `readonly struct`, instances are immutable. The `_startTimestamp` is captured at construction and cannot be modified.
- **StopWatchQueue**: The destructor (`~StopWatchQueue`) automatically calls `DumpData()`, ensuring statistics are written even if not explicitly called.
- **IPAddressIntForm**: All four byte properties (`ByteOne` through `ByteFour`) are read-only and set only at construction.
- **SerializableDictionary**: The XML structure must follow the `<items>/<item>/<key>/<value>` hierarchy for proper deserialization.
---
## 4. Dependencies
### External Dependencies (from imports):
- **Xceed.Wpf.Toolkit** (`Xceed.Wpf.Toolkit.PropertyGrid.Attributes`) - Used by `EnumUtil.GetValuesList<T>()` for `ItemCollection`.
- **System.Windows.Forms** - Used by `SecureQueue<T>` (though only referenced, not actively used in visible code).
- **System.Drawing** - Used by `BusyWaitAnimation` for GDI+ rendering.
- **System.Windows.Threading** - Used by `BusyWaitAnimation` for `DispatcherTimer`.
### Internal Dependencies (inferred):
- **DTS.Common.Constants** - Referenced in `TestUtils` for `NANOS_PER_SECOND`, `TEN_MILLIS_IN_SEC`, and `EventNumber`.
- **DTS.Common.Interface** - Referenced in `TestUtils.cs` (though no interface usage visible in the provided code).
- **DTS.Common.Utilities.Logging** - `APILogger` used in `SecureQueue<T>` and `NetworkUtils`.
- **DTS.DASLib.Utility** - `SerializableDictionary` resides in this namespace (different from other files).
- **Enums.DASFactory.DFConstantsAndEnums** - `ExtraCommunicationLogging` flag checked in `SecureQueue<T>`.
### Consumers:
- Unknown from source alone. These utilities appear designed for consumption by higher-level DTS modules.
---
## 5. Gotchas
1. **ByteConvertor class name spelling**: The class is named `ByteConvertor` (with 'or') rather than the American spelling `ByteConverter`. This could cause confusion or misspellings when referencing.
2. **ByteConvertor float/double conversions**: The `Convert` methods for `float` and `double` use `BitConverter.ToSingle`/`BitConverter.ToDouble`, which respect system endianness, unlike the integer methods that explicitly use network byte order. This inconsistency could cause issues on little-endian systems when interoperating with network protocols.
3. **SecureQueue\<T\>.Dequeue creates new ManualResetEvent**: Each call to `Dequeue` instantiates a **new** `ManualResetEvent(false)`, replacing the existing one. This could orphan wait handles and break any external code holding a reference to the previous event.
4. **SecureQueue\<T\>.Dispose is empty**: The `Dispose` method does not release the `ManualResetEvent` or other resources, potentially causing resource leaks.
5. **StopWatchQueue file creation**: `DumpData` uses `FileMode.CreateNew`, which will throw an `IOException` if the file already exists. The filename includes only the timestamp without ensuring uniqueness.
6. **MouseUtilities DPI handling**: The `GetMousePosition` method contains a calculation `var factor = 2D - presentationSource.CompositionTarget.TransformToDevice.M22;` which appears to be a workaround for DPI scaling. The logic `if (factor > 0)` for offset adjustment may not handle all DPI scenarios correctly.
7. **NetworkUtils.GetAvailableHosts filters by hardcoded strings**: The method filters out adapters containing "virtual", "bluethooth" (misspelled), and "Npcap" in their names/descriptions. This could inadvertently filter legitimate adapters.
8. **BusyWaitAnimation requires GDI setup**: The class requires external code to set `hDC` and call `SetDrawArea` before rendering. Calling `Invalidate` or `OnPaint` before setup will result in null reference exceptions.
9. **SerializableDictionary namespace mismatch**: This class is in `DTS.DASLib.Utility` namespace while all other utilities are in `DTS.Common.Utils`. This could cause confusion when locating the class.
10. **XMLUtils is empty**: The `XMLUtils` class contains no members. Its purpose is unclear from the source.
11. **TestUtils.MinUnixTime returns null**: The method returns `null` (not a default tuple) when the input collection is null or empty. Callers must handle null returns.
12. **PNGImageUtil.SaveImage uses FileMode.CreateNew**: Will throw if file exists. Consider whether `FileMode.Create` would be more appropriate for overwriting.