Files

160 lines
11 KiB
Markdown
Raw Permalink Normal View History

2026-04-17 14:55:32 -04:00
---
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-17T15:28:51.759678+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "e99fd2232db1cd36"
---
# DTS.Common.Utils Module Documentation
## 1. Purpose
This module provides a collection of utility classes and helper functions for the DTS application suite. It encompasses WPF UI components (`ImageButton`, `BusyWaitAnimation`), network utilities (`NetworkUtils`, `ByteConvertor`), thread-safe data structures (`SecureQueue`), serialization helpers (`SerializableDictionary`), timing diagnostics (`StopWatchQueue`), and various conversion/inspection utilities. The module serves as a shared foundation for cross-cutting concerns across the DTS codebase.
---
## 2. Public Interface
### EnumUtil (static class)
- `IEnumerable<T> GetValues<T>()` — Returns all values of enum type `T` as an enumerable collection.
- `ItemCollection GetValuesList<T>()` — Returns an `ItemCollection` populated with enum values and their names, suitable for Xceed WPF Toolkit PropertyGrid.
### ImageButton (extends `Button`)
- `ImageSource Source { get; set; }` — Gets or sets the image displayed on the button.
- `string ImageText { get; set; }` — Gets or sets the text displayed below the image.
### PNGImageUtil (static class)
- `void SaveImage(FrameworkElement view, string fileName)` — Renders the given `FrameworkElement` to a PNG file at the specified path.
### MouseUtilities (class)
- `Point GetMousePosition(Visual relativeTo)` — Returns the current mouse cursor position relative to the specified `Visual`, accounting for DPI scaling via Win32 interop.
### StopWatchQueue (class)
- `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 dictionary from XML format with `<items>`, `<item>`, `<key>`, and `<value>` elements.
- `void WriteXml(XmlWriter writer)` — Serializes dictionary to XML format.
### XmlDictionary (class)
- `SerializableDictionary<string, object> Dictionary { get; set; }` — Wrapper property holding a string-to-object dictionary.
### TestModuleTimeStamp (class)
- `int TriggerTimestampSec { get; set; }` — Seconds component of timestamp.
- `int TriggerTimestampNanoSec { get; set; }` — 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 ± standard deviation, capped at 10ms).
- `string ParseROISuffix(string test)` — Parses and returns the ROI suffix from a test identifier string.
### SecureQueue<T> (implements `IDisposable`, constraint: `T : new()`)
- `enum NullPolicy { DenyNull, SkipNull, AllowNull }` — Policy for handling null/empty array enqueues.
- `SecureQueue(NullPolicy policy, string name)` — Constructor.
- `void Enqueue(T[] newData)` — Thread-safe enqueue; clones input data; applies null policy.
- `T[] Dequeue(bool resetEvent)` — Thread-safe dequeue; concatenates all queued arrays into a single array; returns empty array if queue is empty.
- `bool WaitForData(int timeoutMillisec)` — Blocks until data arrives or timeout; returns `true` if data available.
- `WaitHandle QueueWaitHandle { get; }` — Exposes the internal `ManualResetEvent` as a `WaitHandle`.
- `void ResetEvent()` — Resets the internal wait handle.
- `void Flush()` — Clears the queue and resets the wait handle.
- `bool IsEmpty()` — Returns `true` if queue is empty.
- `void Dispose()` — Implementation of `IDisposable` (currently empty).
### ByteConvertor (class)
- `static 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 using network byte order (big-endian) for integral types.
- `static byte[] ToByteArray(byte/ushort/short/uint/int/ulong/float/double/string input)` — Converts the specified type to a byte array in network byte order.
### NetworkUtils (static class)
- `bool IsNetworkInterfaceUp(IPAddress ip)` — Returns `true` if the network interface for the given IP is operational.
- `List<HostInfo> GetAvailableHosts(bool supportMulticastOnly = false)` — Returns a list of available network hosts with IP, MAC, and address range information.
- `bool TryParseConnectionString(string connectionString, out string ipAddress)` — Attempts to extract an IP address from a connection string; returns `false` for USB connections.
### BusyWaitAnimation (class)
- `Color Color { get; set; }` — Spoke color.
- `Color BgColor { get; set; }` — Background color.
- `int OuterCircleRadius { get; set; }` — Outer radius of the spinning circle.
- `int InnerCircleRadius { get; set; }` — Inner radius of the spinning circle.
- `int NumberSpoke { get; set; }` — Number of spokes in the animation.
- `bool Active { get; set; }` — Starts/stops the animation.
- `int SpokeThickness { get; set; }` — Thickness of each spoke.
- `long RotationSpeed { get; set; }` — Animation interval in ticks (higher = slower).
- `StylePresets StylePreset { get; set; }` — Preset styles: `MacOsx`, `Firefox`, `Ie7`, `Custom`.
- `void SetCircleAppearance(int numberSpoke, int spokeThickness, int innerCircleRadius, int outerCircleRadius)` — Configures all visual parameters at once.
- `void SetDrawArea(Rectangle rect)` — Sets the drawing area and initializes internal graphics buffers.
- `int hDC { get; set; }` — GDI device context handle for external rendering.
- `Graphics GDIGraphics { get; }` — Exposes the internal `Graphics` object.
### XMLUtils (class)
- Empty class with no members. Purpose unclear from source alone.
---
## 3. Invariants
- **ByteConvertor**: All integral type conversions use **network byte order (big-endian)**. Multi-byte reads expect input arrays to have sufficient length starting at the given offset.
- **SecureQueue<T>**: The generic type `T` must have a parameterless constructor (`new()` constraint).
- **SecureQueue<T>**: `Dequeue` always returns a non-null array (returns `new T[0]` on empty queue or exception).
- **SerializableDictionary**: XML structure must follow `<items><item><key>...</key><value>...</value></item></items>` format.
- **StopWatchQueue**: `Stop()` must be called after `Start()` for meaningful data; each `Stop()` records one measurement.
- **PNGImageUtil.SaveImage**: The `FrameworkElement` must have been rendered (measured/arranged) so `ActualWidth` and `ActualHeight` are non-zero.
- **MouseUtilities.GetMousePosition**: The `relativeTo` visual must be connected to a presentation source (window handle must exist).
- **TestUtils.MinUnixTime**: Returns `null` if input collection is null or empty.
---
## 4. Dependencies
### External Dependencies (from imports)
- **Xceed.Wpf.Toolkit.PropertyGrid.Attributes** — Used by `EnumUtil.GetValuesList<T>()` for `ItemCollection`.
- **System.Windows.Controls**, **System.Windows.Media** — WPF UI components (`ImageButton`).
- **System.Windows.Media.Imaging** — PNG encoding (`PNGImageUtil`).
- **System.Runtime.InteropServices** — P/Invoke for Win32 APIs (`MouseUtilities`).
- **System.Xml.Serialization**, **System.Xml.Schema** — XML serialization (`SerializableDictionary`).
- **System.Net.NetworkInformation**, **System.Net.Sockets** — Network interface queries (`NetworkUtils`).
- **System.Drawing** — GDI+ graphics (`BusyWaitAnimation`).
- **System.Windows.Threading** — `DispatcherTimer` for animation (`BusyWaitAnimation`).
### Internal Dependencies (inferred)
- `DTS.Common.Constants` — Constants `NANOS_PER_SECOND`, `TEN_MILLIS_IN_SEC`, `EventNumber` (used in `TestUtils`).
- `DTS.Common.Utilities.Logging.APILogger` — Logging in `SecureQueue` and `NetworkUtils`.
- `DTS.Common.Interface` — Referenced in `TestUtils` (usage unclear from source alone).
- `DTS.DASLib.Utility` — Namespace for `XmlDictionary` and `SerializableDictionary` (note: different namespace than other files).
- `DTS.Common.Utilities.Logging.Enums``DASFactory.DFConstantsAndEnums.ExtraCommunicationLogging` flag in `SecureQueue`.
---
## 5. Gotchas
1. **Namespace Inconsistency**: `SerializableDictionary` and `XmlDictionary` are in namespace `DTS.DASLib.Utility`, while all other utilities are in `DTS.Common.Utils`. This may cause confusion when locating types.
2. **ByteConvertor Float/Double Handling**: The `Convert` methods for `float` and `double` use `BitConverter.ToSingle`/`BitConverter.ToDouble`, which respect system endianness—unlike integral types which explicitly use network byte order. This could cause platform-specific behavior.
3. **SecureQueue.Dequeue Creates New ManualResetEvent**: Each `Dequeue` call instantiates a new `ManualResetEvent(false)`, replacing the existing one. This could lead to race conditions if threads are waiting on the old event handle.
4. **SecureQueue.Dispose is Empty**: The `Dispose()` method does not release `ByteQueueEvent` or `ByteQueueLock`, potentially causing resource leaks.
5. **StopWatchQueue Finalizer Writes Files**: The destructor `~StopWatchQueue()` calls `DumpData()`, which writes a CSV file to disk. This could cause unexpected file I/O during garbage collection.
6. **MouseUtilities DPI Calculation**: The line `var factor = 2D - presentationSource.CompositionTarget.TransformToDevice.M22;` uses an unusual formula for DPI compensation. The logic is unclear and may not handle all DPI scenarios correctly.
7. **BusyWaitAnimation Requires GDI Setup**: The class requires external initialization via `SetDrawArea()` and setting `hDC` before `Invalidate()` will function. Calling `Invalidate()` before setup will do nothing (null check on `_graphics`).
8. **PNGImageUtil.SaveImage Uses FileMode.CreateNew**: Will throw `IOException` if the file already exists. Does not overwrite existing files.
9. **XMLUtils is Empty**: The `XMLUtils` class contains no members. Its purpose is unclear from source alone.