Class VhUtils
Provides assorted helpers: sizes and their text, sockets and free ports, tasks with a timeout, keys and hashes, files, and countries.
public static class VhUtils
- Inheritance
-
VhUtils
- Inherited Members
Fields
Gigabytes
The bytes in a gigabyte, 2^30.
public const long Gigabytes = 1073741824
Field Value
Megabytes
The bytes in a megabyte, 2^20.
public const long Megabytes = 1048576
Field Value
Petabytes
The bytes in a petabyte, 2^50.
public const long Petabytes = 1125899906842624
Field Value
Terabytes
The bytes in a terabyte, 2^40.
public const long Terabytes = 1099511627776
Field Value
Properties
DebuggerTimeout
Gets or sets the timeout WhenNoDebugger(TimeSpan) gives while a debugger is attached, or null to keep the timeouts as they are. The default is a day.
public static TimeSpan? DebuggerTimeout { get; set; }
Property Value
Methods
ConfigTcpClient(TcpClient, int?, int?, bool?, bool?, bool)
Configures a TCP client: Nagle's delay, buffer sizes above zero, address reuse and keep-alive, each when given. A failure to set keep-alive is logged as a warning, and keep-alive is skipped from then on, process-wide.
public static void ConfigTcpClient(TcpClient tcpClient, int? sendBufferSize = null, int? receiveBufferSize = null, bool? reuseAddress = null, bool? keepAlive = null, bool noDelay = true)
Parameters
tcpClientTcpClientThe TCP client.
sendBufferSizeint?The send buffer's size, or null to keep it.
receiveBufferSizeint?The receive buffer's size, or null to keep it.
reuseAddressbool?Whether the address may be reused, or null to keep it.
keepAlivebool?Whether to send keep-alives, or null to keep it.
noDelaybooltrue, the default, to send without Nagle's delay.
Exceptions
- SocketException
An option other than keep-alive cannot be set.
ConvertFromBase64AndFixPadding(string)
Decodes Base64, adding the padding that is missing.
public static byte[] ConvertFromBase64AndFixPadding(string base64)
Parameters
base64stringThe Base64 text.
Returns
- byte[]
The bytes.
Exceptions
- FormatException
The text is not Base64.
CreateCompletedTcs()
Creates a completed task source that runs continuations asynchronously.
public static TaskCompletionSource CreateCompletedTcs()
Returns
- TaskCompletionSource
The task source.
DirectoryCopy(string, string, bool)
Copies a folder's files to another folder, which is made when missing; an existing file is not overwritten.
public static void DirectoryCopy(string sourcePath, string destinationPath, bool recursive)
Parameters
sourcePathstringThe folder to copy.
destinationPathstringThe folder to copy into.
recursivebooltrue to copy the subfolders too.
Exceptions
- DirectoryNotFoundException
The source folder does not exist.
- IOException
A file exists already, or cannot be copied.
- UnauthorizedAccessException
The process may not read or write a file or folder.
DisposeAll<T>(IEnumerable<T>?)
Disposes every item; a throw stops the rest. Callers keep their own locks around the enumeration.
public static void DisposeAll<T>(IEnumerable<T>? items) where T : IDisposable
Parameters
itemsIEnumerable<T>The items, or null.
Type Parameters
TThe type of the items.
EncryptClientId(string, byte[])
Encrypts a client ID with a shared key, as the server checks it: AES-CBC with a zero IV, over the ID's GUID bytes, or its UTF-8 bytes when it is no GUID, filled up with zeros to a whole number of blocks.
public static byte[] EncryptClientId(string clientId, byte[] key)
Parameters
Returns
- byte[]
The encrypted bytes.
Remarks
The same ID and key always give the same bytes: the server makes them again to check that the client holds the key. They are a proof of that, not a secret kept.
Exceptions
- CryptographicException
The key is of no AES size.
FormatBits(long)
Formats a rate in bytes per second as bits per second, such as 8 Mbps, in units of 1024.
public static string FormatBits(long bytes)
Parameters
byteslongThe bytes per second.
Returns
- string
The text.
FormatBytes(long, bool, bool)
Formats a size in bytes for reading, such as 1.5 GB, in the current culture.
public static string FormatBytes(long size, bool use1024 = true, bool round = false)
Parameters
sizelongThe size in bytes; a negative one keeps its sign.
use1024boolroundbooltrue to round to a whole number of the unit.
Returns
- string
The text, or
0for zero.
FormatMegaBytes(long, bool, bool)
Formats a size in megabytes for reading, such as 2 GB, in the current culture.
public static string FormatMegaBytes(long sizeMb, bool use1024 = false, bool round = false)
Parameters
sizeMblongThe size in megabytes; a negative one keeps its sign.
use1024booltrue for units of 1024; false, the default, for units of 1000.
roundbooltrue to round to a whole number of the unit.
Returns
- string
The text, or
0for zero.
FromMB(long)
Converts megabytes to bytes, a megabyte being 1024 × 1024 bytes.
public static long FromMB(long megabytes)
Parameters
megabyteslongThe megabytes.
Returns
- long
The bytes.
GenerateKey()
Generates a random 128-bit AES key.
public static byte[] GenerateKey()
Returns
- byte[]
The key.
GenerateKey(int)
Generates a random AES key of a size.
public static byte[] GenerateKey(int keySizeInBit)
Parameters
keySizeInBitintThe key's size in bits: 128, 192 or 256.
Returns
- byte[]
The key.
Exceptions
- CryptographicException
The size is not an AES key's.
GetAssemblyMetadata(Assembly, string, string)
Reads an assembly's metadata value by key.
public static string GetAssemblyMetadata(Assembly assembly, string key, string defaultValue)
Parameters
assemblyAssemblyThe assembly.
keystringThe key.
defaultValuestringThe value when the key is missing or empty.
Returns
- string
The value.
GetBufferMd5(byte[])
Computes the MD5 hash of bytes, for change detection, not security.
public static string GetBufferMd5(byte[] value)
Parameters
valuebyte[]The bytes.
Returns
- string
The hash, in upper-case hex.
GetCurrencySymbol(string)
Gets a currency's symbol from its ISO code, from the first culture whose region uses it.
public static string GetCurrencySymbol(string currencyCode)
Parameters
currencyCodestringThe currency's ISO code, such as
USD.
Returns
- string
The symbol, or the code itself when no culture uses it.
GetFreeTcpEndPoint(IPAddress, int)
Finds a TCP port free on an address now: the given one when it is, else one the system picks. Another process may take it before the caller binds it.
public static IPEndPoint GetFreeTcpEndPoint(IPAddress ipAddress, int defaultPort = 0)
Parameters
Returns
- IPEndPoint
The endpoint.
Exceptions
- SocketException
No port can be bound on the address.
GetFreeUdpEndPoint(IPAddress, int)
Finds a UDP port free on an address now: the given one when it is, else one the system picks. Another process may take it before the caller binds it.
public static IPEndPoint GetFreeUdpEndPoint(IPAddress ipAddress, int defaultPort = 0)
Parameters
Returns
- IPEndPoint
The endpoint.
Exceptions
- SocketException
No port can be bound on the address.
- InvalidOperationException
The socket has no local endpoint.
GetHexStringSha256(string, int?)
Computes a stable ID of a text's content, for change detection, not security: its SHA-256 in lower-case hex, optionally cut.
public static string GetHexStringSha256(string value, int? length = null)
Parameters
Returns
- string
The hex text.
Exceptions
- ArgumentOutOfRangeException
lengthis negative or over 64.
GetRequiredInstance<T>(T?)
Returns an object that must have been set.
public static T GetRequiredInstance<T>(T? obj)
Parameters
objTThe object, or null.
Returns
- T
The object.
Type Parameters
TThe object's type.
Exceptions
- InvalidOperationException
The object is null.
GetStringMd5(string)
Computes the MD5 hash of a text's UTF-8 bytes, for change detection, not security.
public static string GetStringMd5(string value)
Parameters
valuestringThe text.
Returns
- string
The hash, in upper-case hex.
IsConnectionRefusedException(Exception)
Determines whether an exception, or its inner exception, is a refused connection.
public static bool IsConnectionRefusedException(Exception ex)
Parameters
exExceptionThe exception.
Returns
IsInfinite(TimeSpan)
Determines whether a time span means no limit: MaxValue or InfiniteTimeSpan.
public static bool IsInfinite(TimeSpan timeSpan)
Parameters
timeSpanTimeSpanThe time span.
Returns
IsNullOrEmpty<T>(IEnumerable<T>?)
Determines whether a sequence is null or has no item.
public static bool IsNullOrEmpty<T>(IEnumerable<T>? array)
Parameters
arrayIEnumerable<T>The sequence, or null.
Returns
Type Parameters
TThe type of the items.
IsNullOrEmpty<T>(T[]?)
Determines whether an array is null or empty.
public static bool IsNullOrEmpty<T>(T[]? array)
Parameters
arrayT[]The array, or null.
Returns
Type Parameters
TThe type of the items.
IsSocketClosedException(Exception)
Determines whether an exception is of the kinds a closed socket throws: ObjectDisposedException, IOException or SocketException, whatever its cause.
public static bool IsSocketClosedException(Exception ex)
Parameters
exExceptionThe exception.
Returns
IsTcpClientHealthy(TcpClient)
Determines whether a TCP client is connected and its socket reports no error.
public static bool IsTcpClientHealthy(TcpClient tcpClient)
Parameters
tcpClientTcpClientThe TCP client.
Returns
ParseArguments(string)
Splits a command line into arguments at white space, keeping a double-quoted part together.
public static IEnumerable<string> ParseArguments(string commandLine)
Parameters
commandLinestringThe command line.
Returns
- IEnumerable<string>
The arguments, without their quotes.
Remarks
A quoted part and what stands right beside it are one argument, and a pair of quotes alone is an empty one.
RemoveMilliseconds(DateTime)
Cuts a time to whole seconds, keeping its kind.
public static DateTime RemoveMilliseconds(DateTime dateTime)
Parameters
dateTimeDateTimeThe time.
Returns
- DateTime
The time without its fraction of a second.
RunTask(Task, CancellationToken)
Waits for a task until a token is canceled; the task itself is not canceled.
public static Task RunTask(Task task, CancellationToken cancellationToken)
Parameters
taskTaskThe task.
cancellationTokenCancellationTokenThe token to monitor for cancellation requests.
Returns
- Task
A task that completes with the task.
Exceptions
- OperationCanceledException
cancellationTokenwas canceled.- Exception
The task's own exception.
RunTask(Task, TimeSpan, CancellationToken)
Waits for a task at most a timeout; the task itself is not canceled.
public static Task RunTask(Task task, TimeSpan timeout, CancellationToken cancellationToken)
Parameters
taskTaskThe task.
timeoutTimeSpanHow long to wait; zero for no limit.
cancellationTokenCancellationTokenThe token to monitor for cancellation requests.
Returns
- Task
A task that completes with the task.
Exceptions
- TimeoutException
The timeout passed first.
- ArgumentOutOfRangeException
The timeout is negative, other than infinite, or too long.
- OperationCanceledException
cancellationTokenwas canceled.- Exception
The task's own exception.
RunTask<T>(Task<T>, CancellationToken)
Waits for a task until a token is canceled; the task itself is not canceled.
public static Task<T> RunTask<T>(Task<T> task, CancellationToken cancellationToken)
Parameters
taskTask<T>The task.
cancellationTokenCancellationTokenThe token to monitor for cancellation requests.
Returns
- Task<T>
A task whose result is the task's.
Type Parameters
TThe type of the result.
Exceptions
- OperationCanceledException
cancellationTokenwas canceled.- Exception
The task's own exception.
RunTask<T>(Task<T>, TimeSpan, CancellationToken)
Waits for a task at most a timeout; the task itself is not canceled.
public static Task<T> RunTask<T>(Task<T> task, TimeSpan timeout, CancellationToken cancellationToken)
Parameters
taskTask<T>The task.
timeoutTimeSpanHow long to wait; zero for no limit.
cancellationTokenCancellationTokenThe token to monitor for cancellation requests.
Returns
- Task<T>
A task whose result is the task's.
Type Parameters
TThe type of the result.
Exceptions
- TimeoutException
The timeout passed first.
- ArgumentOutOfRangeException
The timeout is negative, other than infinite, or too long.
- OperationCanceledException
cancellationTokenwas canceled.- Exception
The task's own exception.
SafeToArray<T>(object, IEnumerable<T>)
Copies a collection into an array under a lock.
public static T[] SafeToArray<T>(object lockObject, IEnumerable<T> collection)
Parameters
lockObjectobjectThe lock.
collectionIEnumerable<T>The collection.
Returns
- T[]
The array.
Type Parameters
TThe type of the items.
SequenceEquals<T>(IEnumerable<T>?, IEnumerable<T>?)
Determines whether two sequences have the same items in order, a null one counting as empty.
public static bool SequenceEquals<T>(IEnumerable<T>? first, IEnumerable<T>? second)
Parameters
firstIEnumerable<T>The first sequence, or null.
secondIEnumerable<T>The second sequence, or null.
Returns
Type Parameters
TThe type of the items.
Shuffle<T>(T[])
Shuffles an array in place (Fisher-Yates), with a non-cryptographic random.
public static void Shuffle<T>(T[] array)
Parameters
arrayT[]The array.
Type Parameters
TThe type of the items.
TryDeleteFile(string)
Deletes a file when it exists, and gives back a failure instead of throwing it.
public static Exception? TryDeleteFile(string filePath)
Parameters
filePathstringThe file's path.
Returns
TryGetCountryName(string?)
Gets a country's English name from its code.
public static string? TryGetCountryName(string? countryCode)
Parameters
Returns
TryParseUrl(string?, UriKind)
Parses a URL.
public static Uri? TryParseUrl(string? stringUrl, UriKind uriKind = UriKind.Absolute)
Parameters
stringUrlstringThe URL's text, or null.
uriKindUriKindThe kind of URL expected. The default is absolute.
Returns
Exceptions
- ArgumentException
uriKindis not a valid kind.