Files
DP44/enriched-partialglm/Common/DTS.CommonCore/Utils.md
2026-04-17 14:55:32 -04:00

157 lines
10 KiB
Markdown

---
source_files:
- Common/DTS.CommonCore/Utils/XMLUtils.cs
- Common/DTS.CommonCore/Utils/EnumUtils.cs
- Common/DTS.CommonCore/Utils/ImageButton.cs
- Common/DTS.CommonCore/Utils/PNGImageUtil.cs
- Common/DTS.CommonCore/Utils/MouseUtils.cs
- Common/DTS.CommonCore/Utils/StopWatch.cs
- Common/DTS.CommonCore/Utils/SerializableDictionary.cs
- Common/DTS.CommonCore/Utils/TestUtils.cs
- Common/DTS.CommonCore/Utils/SecureQueue.cs
- Common/DTS.CommonCore/Utils/ByteConverter.cs
- Common/DTS.CommonCore/Utils/NetworkUtils.cs
- Common/DTS.CommonCore/Utils/BusyWaitAnimation.cs
generated_at: "2026-04-16T12:01:02.629774+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "0a10ccd507cef203"
---
# DTS.CommonCore.Utils Documentation
## 1. Purpose
This module provides a collection of utility classes and helper methods for the DTS system, including thread-safe data structures (`SecureQueue`), byte manipulation with network byte order conversion (`ByteConvertor`), WPF UI components (`ImageButton`, `BusyWaitAnimation`), network interface utilities (`NetworkUtils`), XML serialization helpers (`SerializableDictionary`), performance profiling (`StopWatchQueue`), and various other utility functions for enums, timestamps, mouse positioning, and image rendering.
---
## 2. Public Interface
### `EnumUtil` (static class)
- `IEnumerable<T> GetValues<T>()` — Returns all values of enum type `T` as an enumerable.
- `ItemCollection GetValuesList<T>()` — Returns an `ItemCollection` populated with enum values and their names, suitable for use with Xceed WPF Toolkit PropertyGrid.
### `ImageButton` (extends `Button`)
- `ImageSource Source` — Gets or sets the image source displayed on the button.
- `string ImageText` — Gets or sets the text displayed below the image.
### `PNGImageUtil` (static class)
- `void SaveImage(FrameworkElement view, string fileName)` — Renders a `FrameworkElement` to a PNG file at the specified path. Uses 96 DPI and `Pbgra32` pixel format.
### `MouseUtilities`
- `static Point GetMousePosition(Visual relativeTo)` — Returns the mouse cursor position relative to the specified `Visual`, using Win32 API calls (`GetCursorPos`, `ScreenToClient`).
### `StopWatchQueue`
- `StopWatchQueue(string name)` — Constructor accepting a name used for output file naming.
- `void Start()` — Starts the internal stopwatch.
- `void Stop()` — Stops the stopwatch, records elapsed ticks to an internal queue, and resets the stopwatch.
- `void DumpData()` — Writes all recorded timing data to a CSV file with statistics (max, min, average, standard deviation in milliseconds).
### `SerializableDictionary<TKey, TValue>` (extends `Dictionary<TKey, TValue>`, implements `IXmlSerializable`)
- `XmlSchema GetSchema()` — Returns `null`.
- `void ReadXml(XmlReader reader)` — Deserializes the dictionary from XML format with `<items>`, `<item>`, `<key>`, and `<value>` elements.
- `void WriteXml(XmlWriter writer)` — Serializes the dictionary to XML format.
### `XmlDictionary`
- `SerializableDictionary<string, object> Dictionary` — A pre-configured serializable dictionary for string-to-object mappings.
### `TestModuleTimeStamp`
- `int TriggerTimestampSec` — Seconds component of timestamp.
- `int TriggerTimestampNanoSec` — Nanoseconds component of timestamp.
### `TestUtils` (static class)
- `Tuple<double, double> MinUnixTime(IEnumerable<TestModuleTimeStamp> basemodules)` — Calculates the minimum Unix timestamp from a collection, using statistical filtering (average minus standard deviation, capped at 10ms). Returns `null` if input is null or empty.
- `string ParseROISuffix(string test)` — Parses a test string to extract an ROI suffix based on event number markers.
### `SecureQueue<T>` (implements `IDisposable`, constrained to `new()`)
- `enum NullPolicy``DenyNull`, `SkipNull`, `AllowNull`.
- `SecureQueue(NullPolicy policy, string name)` — Constructor.
- `void ResetEvent()` — Resets the internal `ManualResetEvent`.
- `void Enqueue(T[] newData)` — Thread-safe enqueue; behavior depends on `NullPolicy`. Clones data before storing.
- `bool WaitForData(int timeoutMillisec)` — Blocks until data arrives or timeout; returns `true` if data available.
- `WaitHandle QueueWaitHandle` — Exposes the internal wait handle.
- `T[] Dequeue(bool resetEvent)` — Thread-safe dequeue; concatenates all queued arrays into a single array if multiple entries exist.
- `void Flush()` — Clears the queue and resets the event.
- `bool IsEmpty()` — Returns `true` if queue is empty.
- `void Dispose()` — Implementation of `IDisposable` (currently empty).
### `ByteConvertor` (static class)
- `void Convert(byte[] input, int offset, out byte/ushort/short/uint/int/ulong/long/float/double/string value)` — Converts bytes at offset to the specified type. Multi-byte integers are interpreted in **big-endian (network) byte order**. Strings are null-terminated.
- `byte[] ToByteArray(byte/ushort/short/uint/int/ulong/float/double/string input)` — Converts the specified type to a byte array. Multi-byte integers are output in **big-endian (network) byte order**. Strings are null-terminated.
### `NetworkUtils` (static class)
- `bool IsNetworkInterfaceUp(IPAddress ip)` — Returns `true` if the network interface for the given IP is up and operational.
- `List<HostInfo> GetAvailableHosts(bool supportMulticastOnly = false)` — Returns a list of available network hosts with IP, MAC, and address range information. Filters out VPN, virtual adapters, loopback, and Npcap interfaces.
- `bool TryParseConnectionString(string connectionString, out string ipAddress)` — Attempts to extract an IP address from a connection string; returns `false` for USB connections.
### `BusyWaitAnimation`
- `Color Color` — Gets or sets the spoke color.
- `Color BgColor` — Gets or sets the background color.
- `int OuterCircleRadius` — Gets or sets the outer circle radius.
- `int InnerCircleRadius` — Gets or sets the inner circle radius.
- `int NumberSpoke` — Gets or sets the number of spokes.
- `bool Active` — Gets or sets whether the animation is running.
- `int SpokeThickness` — Gets or sets the spoke thickness.
- `long RotationSpeed` — Gets or sets the rotation speed (higher = slower).
- `StylePresets StylePreset` — Gets or sets a preset style (`MacOsx`, `Firefox`, `Ie7`, `Custom`).
- `Graphics GDIGraphics` — Gets the internal GDI+ graphics object.
- `int hDC` — Gets or sets the device context handle.
- `void SetDrawArea(Rectangle rect)` — Sets the drawing area and initializes internal bitmaps.
- `void SetCircleAppearance(int numberSpoke, int spokeThickness, int innerCircleRadius, int outerCircleRadius)` — Configures the circle appearance.
### `XMLUtils`
- Empty class — **No public members defined.**
---
## 3. Invariants
- **ByteConvertor**: All multi-byte integer conversions use big-endian (network) byte order. The `Convert` methods assume the input byte array is sufficiently sized for the requested type at the given offset.
- **SecureQueue**: The queue is thread-safe; all operations use locking on `ByteQueueLock`. When `NullPolicy.DenyNull` is set, enqueuing null or empty arrays throws `ArgumentException`.
- **SerializableDictionary**: XML structure must follow `<items><item><key>...</key><value>...</value></item>...</items>` format.
- **StopWatchQueue**: `Stop()` records elapsed ticks since the last `Start()` call and resets the stopwatch; calling `Stop()` without `Start()` will record whatever the stopwatch state is (including zero if never started).
- **PNGImageUtil.SaveImage**: Requires the `FrameworkElement` to have valid `ActualWidth` and `ActualHeight` (must be rendered/measured). Uses `FileMode.CreateNew` — will throw if file already exists.
- **TestUtils.MinUnixTime**: Returns `null` if input collection is null or empty. Standard deviation is capped at `Common.Constants.TEN_MILLIS_IN_SEC`.
- **BusyWaitAnimation**: Requires `SetDrawArea()` and `hDC` to be set before animation can render.
---
## 4. Dependencies
### External Dependencies (from imports)
- **Xceed.Wpf.Toolkit.PropertyGrid.Attributes** — `EnumUtil.GetValuesList<T>()` returns `ItemCollection`.
- **System.Windows.Forms** — Used in `SecureQueue` (though not directly referenced in visible code, imported).
- **System.Drawing** — Used in `BusyWaitAnimation` for GDI+ graphics.
- **System.Windows.Threading** — `BusyWaitAnimation` uses `DispatcherTimer`.
### Internal Dependencies
- `DTS.Common.Utilities.Logging.APILogger` — Used by `SecureQueue` for logging.
- `DTS.Common.Interface` — Imported in `TestUtils` (usage unclear from source alone).
- `DTS.Common.Constants` — Constants `NANOS_PER_SECOND`, `TEN_MILLIS_IN_SEC`, `EventNumber` referenced in `TestUtils`.
- `Enums.DASFactory.DFConstantsAndEnums.ExtraCommunicationLogging` — Used in `SecureQueue.Enqueue`.
### Namespace Inconsistency
- `SerializableDictionary` and `XmlDictionary` are in namespace `DTS.DASLib.Utility`, while all other utilities are in `DTS.Common.Utils`.
---
## 5. Gotchas
1. **ByteConvertor float/double conversions**: Unlike integer types, `Convert` methods for `float` and `double` use `BitConverter.ToSingle/ToDouble`, which respects system endianness — inconsistent with the big-endian behavior of integer conversions.
2. **PNGImageUtil.SaveImage file mode**: Uses `FileMode.CreateNew`, which will throw an exception if the file already exists. Caller must ensure the file does not exist or handle the exception.
3. **SecureQueue.Dequeue event handling**: The method creates a **new** `ManualResetEvent(false)` on every call, which may cause issues if multiple consumers are waiting on the original event handle.
4. **SecureQueue.Dispose**: The `Dispose()` method is empty and does not release the `ManualResetEvent` or other resources.
5. **MouseUtilities.GetMousePosition DPI handling**: The calculation `var factor = 2D - presentationSource.CompositionTarget.TransformToDevice.M22` is non-obvious and may produce incorrect results for certain DPI configurations.
6. **StopWatchQueue finalizer**: The destructor `~StopWatchQueue()` calls `DumpData()`, which writes a file to disk. This could cause unexpected file I/O during garbage collection.
7. **BusyWaitAnimation static field**: Contains `static int _xxx = 0;` that is incremented in the constructor but never used — appears to be debug/legacy code.
8. **XMLUtils**: The class is entirely empty — unclear if this is placeholder or deprecated code.
9. **SerializableDictionary.ReadXml**: Creates new `XmlSerializer` instances for each key and value type on every call, which could cause performance issues and memory leaks (XmlSerializer caching issues).