15 KiB
15 KiB
source_files, generated_at, model, schema_version, sha256
| source_files | generated_at | model | schema_version | sha256 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
2026-04-16T02:13:53.536236+00:00 | Qwen/Qwen3-Coder-Next-FP8 | 1 | 0a10ccd507cef203 |
DTS.Common.Utils Module Documentation
1. Purpose
This module provides a collection of utility classes and static helper methods for common operations across the DTS (Data Acquisition and Test System) codebase. It serves as a foundational layer supporting UI components (ImageButton, BusyWaitAnimation), data serialization (SerializableDictionary), low-level binary operations (ByteConvertor), network diagnostics (NetworkUtils), timing and profiling (StopWatchQueue), enumeration handling (EnumUtil), image rendering (PNGImageUtil), mouse coordinate translation (MouseUtilities), and test-specific utilities (TestUtils). The module consolidates cross-cutting concerns to avoid duplication and promote consistency across the system.
2. Public Interface
EnumUtil (static class)
GetValues<T>()
Returns anIEnumerable<T>of all enum values of typeTusingEnum.GetValues.GetValuesList<T>()
Returns anItemCollection(fromXceed.Wpf.Toolkit.PropertyGrid.Attributes) containing key-value pairs of enum values and their names.
ImageButton (class, inherits Button)
- Constructor
ImageButton()
Initializes aStackPanel-based button with anImageandTextBlockarranged vertically. Source(property,ImageSource)
Gets/sets the image displayed in the button.ImageText(property,string)
Gets/sets the text displayed below the image.
PNGImageUtil (static class)
SaveImage(FrameworkElement view, string fileName)
Renders the given WPFFrameworkElementto a PNG file atfileNameusingRenderTargetBitmapandPngBitmapEncoder.
MouseUtilities (class)
GetMousePosition(Visual relativeTo)
Returns the current mouse cursor position as aPoint, transformed to be relative to the specifiedVisual. Uses Win32 API (GetCursorPos,ScreenToClient) and WPF transform logic. Includes scaling correction based onCompositionTarget.TransformToDevice.
StopWatchQueue (class)
- Constructor
StopWatchQueue(string name)
Initializes a queue with a name and internalStopwatchandQueue<long>(capacity 5000). Start()
Starts the internalStopwatch.Stop()
Stops theStopwatch, enqueues the elapsed ticks, and resets theStopwatch.DumpData()
Writes timing statistics (count, max, min, average, standard deviation) and all recorded values (in milliseconds) to a timestamped CSV file named<name><filetime>.csv.- Finalizer
~StopWatchQueue()
CallsDumpData()on disposal (via finalization).
SerializableDictionary<TKey, TValue> (class, implements IXmlSerializable)
- Constructor
Inherits fromDictionary<TKey, TValue>and implementsIXmlSerializable. GetSchema()
Returnsnull.ReadXml(XmlReader reader)
Deserializes a dictionary from XML with<items><item><key>...</key><value>...</value></item>...</items>structure.WriteXml(XmlWriter writer)
Serializes the dictionary to the same XML structure.
TestModuleTimeStamp (class)
TriggerTimestampSec(int)
Seconds component of a timestamp.TriggerTimestampNanoSec(int)
Nanoseconds component of a timestamp.
TestUtils (static class)
MinUnixTime(IEnumerable<TestModuleTimeStamp> basemodules)
Returns aTuple<double, double>of(TriggerTimestampSec, TriggerTimestampNanoSec)for the earliest timestamp that satisfies:
moduleTime > utcAverage - utcStandardDeviation,
wheremoduleTime = sec + nano / NANOS_PER_SECOND.
If no modules or invalid input, returnsnull.
Note: Logic appears to select the earliest timestamp within one standard deviation below the mean.ParseROISuffix(string test)
Extracts ROI suffix from a colon-separated test string. Tries two strategies:- If ≥4 segments, returns last segment.
- If contains
EventNumber, returns suffix after last underscore in that segment (prefixed with_).
Returnsstring.Emptyif no match.
SecureQueue<T> (class, implements IDisposable)
NullPolicyenum
DenyNull,SkipNull,AllowNull— behavior whenEnqueuereceives null or zero-length array.- Constructor
SecureQueue(NullPolicy policy, string name)
Initializes queue with policy, name, and internal locking/event mechanisms. ResetEvent()
Resets the internalManualResetEvent.Enqueue(T[] newData)
Thread-safe enqueue with null-checking per policy. Logs viaAPILoggerifExtraCommunicationLoggingis enabled.WaitForData(int timeoutMillisec)
Blocks up totimeoutMillisecfor data; returnstrueif data arrived,falseon timeout.QueueWaitHandle(property)
Exposes the internalManualResetEventas aWaitHandle.Dequeue(bool resetEvent)
Thread-safe dequeue: concatenates all queued arrays into one large array. Resets internal event. Returns empty array if queue empty.Flush()
Clears the queue and resets the event.IsEmpty()
Returnstrueif queue count is zero.Dispose()
No-op (empty implementation).
ByteConvertor (class)
Convert(byte[] input, int offset, out T value)
Reads frominputatoffsetand deserializes toT(supportsbyte,ushort,short,uint,int,ulong,long,float,double,string).
Note: Integer types are read in big-endian (network) order (e.g.,ushortusesinput[offset+0] << 8 | input[offset+1]).
float/doubleuseBitConverter(host-endian).
stringreads until null terminator.ToByteArray(T value)
SerializesTto a byte array in big-endian (network) order (e.g.,ToByteArray(ushort)writes high byte first).
float/doubleuseBitConverter.GetBytes(host-endian).
stringwrites characters + null terminator.
NetworkUtils (static class)
IsNetworkInterfaceUp(IPAddress ip)
Returnstrueif the given IP is assigned to an active, non-loopback, IPv4-enabled, multicast-capable network interface. Skips 169.254.x.x (link-local) addresses.GetAvailableNetworkInterfaces(long minimumSpeed = 10000000)
Returns list ofNetworkInterfaces that are non-loopback, non-virtual, non-Bluetooth, non-modem, and meet minimum speed. Excludes Npcap interfaces.GetAvailableHosts(bool supportMulticastOnly = false)
ReturnsList<HostInfo>(custom type, not shown) with IP, network ID, MAC, and start/end addresses for each valid unicast IPv4 interface. Skips 169.254.x.x and Npcap interfaces.GetStartAndEndAddress(IPAddress ip, IPAddress mask, out string startAddress, out string endAddress)
Computes network start (AND of IP and mask) and broadcast end (OR of IP and inverted mask) addresses. Returns empty strings on error.TryParseConnectionString(string connectionString, out string ipAddress)
Attempts to extract an IP address from a connection string (supports URI or colon-separated format). Returnstrueif successful and IP is valid.
BusyWaitAnimation (class)
StylePresetsenum
MacOsx,Firefox,Ie7,Custom.- Properties
Color,BgColor,OuterCircleRadius,InnerCircleRadius,NumberSpoke,Active,SpokeThickness,RotationSpeed,StylePreset. - Constructor
BusyWaitAnimation()
Initializes timer, appearance, and drawing resources. SetCircleAppearance(int numberSpoke, int spokeThickness, int innerCircleRadius, int outerCircleRadius)
Updates appearance parameters and invalidates.GDIGraphics(property)
Exposes internalGraphicsobject.hDC(property)
Gets/sets the device context handle and initializesGraphics.SetDrawArea(Rectangle rect)
Sets drawing bounds and initializes backing bitmap and graphics.
3. Invariants
ByteConvertor.Convertfor integers: Always interprets multi-byte values in big-endian (network byte order), regardless of host architecture.ByteConvertor.ToByteArrayfor integers: Always outputs in big-endian (network byte order).PNGImageUtil.SaveImage: Requiresview.ActualWidthandview.ActualHeightto be positive and non-zero; otherwise,RenderTargetBitmapmay fail or produce invalid output.StopWatchQueue: Records elapsed ticks inStop(); values are converted to milliseconds usingStopwatch.FrequencyduringDumpData().SecureQueue<T>:Dequeue()concatenates all queued arrays into a single array — not a FIFO of arrays.Dequeue()always resets the internalManualResetEvent, even if the queue was empty.- Thread-safety is ensured via
lock(ByteQueueLock).
TestUtils.MinUnixTime:- Uses
Common.Constants.NANOS_PER_SECONDandCommon.Constants.TEN_MILLIS_IN_SEC(not defined in this module). - Selects the first module satisfying the condition in iteration order, not necessarily the globally earliest valid timestamp.
- Uses
TestUtils.ParseROISuffix:- Relies on
DTS.Common.Constants.EventNumber(not defined here). - Returns
_+ last segment only if the last segment does not contain the event number string.
- Relies on
NetworkUtils.IsNetworkInterfaceUp: Skips interfaces with no IPv4 properties or link-local (169.254.x.x) addresses.
4. Dependencies
Internal Dependencies (from source)
DTS.Common.Interface(viaTestUtils.cs)DTS.Common.Utilities.Logging(viaSecureQueue.cs,NetworkUtils.cs)DTS.DASLib.Utility(namespace forSerializableDictionaryinSerializableDictionary.cs)DTS.Common.Constants(referenced but not defined in this module — used inTestUtils.cs)Xceed.Wpf.Toolkit.PropertyGrid.Attributes(forItemCollectioninEnumUtil.cs)
External Dependencies (via using)
- System:
System.Collections.Generic,System.Diagnostics,System.IO,System.Linq,System.Text,System.Threading,System.Threading.Tasks,System.Windows,System.Windows.Media,System.Windows.Media.Imaging,System.Windows.Threading,System.Windows.Forms,System.Drawing,System.Drawing.Drawing2D,System.Runtime.InteropServices,System.Xml,System.Xml.Serialization,System.Net,System.Net.NetworkInformation,System.Net.Sockets - Windows Presentation Foundation (WPF):
System.Windows.Controls,System.Windows.Interop,System.Windows.Media.Imaging - Windows Forms:
System.Windows.Forms - GDI+:
System.Drawing,System.Drawing.Drawing2D - Win32 API:
user32.dll(forGetCursorPos,GetPhysicalCursorPos,ScreenToClient)
Inferred Consumers
- UI components (
ImageButton,BusyWaitAnimation) likely used in WPF/WinForms UI layers. ByteConvertor,SecureQueue,StopWatchQueueused in low-level data acquisition or networking modules.NetworkUtils,PNGImageUtil,TestUtilsused in test automation, diagnostics, or reporting modules.SerializableDictionaryused for XML persistence of dictionaries.
5. Gotchas
ByteConvertorinteger conversions: Despite the class summary claiming "network order",floatanddoubleuseBitConverter(host-endian), which may cause inconsistencies if expecting consistent endianness across all types.StopWatchQueue.DumpData(): Writes CSV with header"All values in milli seconds"— but values are computed asticks / Frequency * 1000, which is correct for milliseconds. EnsureStopwatch.Frequencyis consistent across platforms.SecureQueue.Dequeue(): Returns a flattened array of all queued arrays, not the first queued array. This is likely intentional for streaming but may be surprising.MouseUtilities.GetMousePosition(): Uses a non-standard scaling correction (factor = 2D - M22) and conditional Y-offset adjustment. This may be fragile under DPI scaling changes or high-DPI scenarios.TestUtils.MinUnixTime():- Uses
basemodules.First()as initialminUnixTime, then compares only ifmodule.TriggerTimestampSec <= minUnixTime.Item1 && module.TriggerTimestampNanoSec < minUnixTime.Item2. This logic may skip valid candidates if seconds are equal but nanoseconds are greater. - The standard deviation cap (
TEN_MILLIS_IN_SEC) is applied after computing deviation, but the comparison uses>, not>=. - No validation that
basemodulesis non-null before calling.Count()(though.Count()on null throws).
- Uses
TestUtils.ParseROISuffix():- Uses
test.Split(":".ToCharArray(), ...)— string split with char array is inefficient;Split(':')would be simpler. - Relies on
DTS.Common.Constants.EventNumber— if undefined or changed, behavior breaks silently.
- Uses
NetworkUtils.GetAvailableHosts(): Skips 169.254.x.x addresses but does not skip other link-local ranges (e.g., IPv6). Also filters Npcap interfaces by description — may miss other packet-capture tools.BusyWaitAnimation:- Uses
Graphics.FromHdc— requires validhDCto be set before drawing; otherwise,FromHdcmay throw. Invalidate()uses_backgroundImage, but_backgroundImageis only initialized inSetDrawArea()— callingInvalidate()beforeSetDrawArea()will causeNullReferenceException.- Timer interval is set via
TimeSpan.FromMilliseconds(value)wherevalueisTicks— this is incorrect;Ticksis not milliseconds. Should useTimeSpan.FromMilliseconds(value)withvaluein milliseconds, orTimeSpan.FromTicks(value)ifvalueis ticks. The propertyRotationSpeedreturns_timer.Interval.Ticks, but setting it expects milliseconds — this mismatch is a bug.
- Uses
SerializableDictionary:- Uses
XmlSerializerfor keys and values — requiresTKeyandTValueto be serializable byXmlSerializer. - Does not handle duplicate keys during deserialization (would throw
ArgumentExceptionfromDictionary.Add). ReadXmlassumes XML structure<items><item>...</item>...</items>— any deviation (e.g., whitespace, attributes) may cause parsing errors.
- Uses
EnumUtil.GetValuesList<T>(): UsesItemCollectionfrom Xceed toolkit — may not be available in all environments or may require specific toolkit version.