Table of Contents

Class VhUtils

Namespace
VpnHood.Net.Toolkit.Utils
Assembly
VpnHood.Net.Toolkit.dll

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

long

Megabytes

The bytes in a megabyte, 2^20.

public const long Megabytes = 1048576

Field Value

long

Petabytes

The bytes in a petabyte, 2^50.

public const long Petabytes = 1125899906842624

Field Value

long

Terabytes

The bytes in a terabyte, 2^40.

public const long Terabytes = 1099511627776

Field Value

long

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

TimeSpan?

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

tcpClient TcpClient

The TCP client.

sendBufferSize int?

The send buffer's size, or null to keep it.

receiveBufferSize int?

The receive buffer's size, or null to keep it.

reuseAddress bool?

Whether the address may be reused, or null to keep it.

keepAlive bool?

Whether to send keep-alives, or null to keep it.

noDelay bool

true, 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

base64 string

The 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

sourcePath string

The folder to copy.

destinationPath string

The folder to copy into.

recursive bool

true 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

items IEnumerable<T>

The items, or null.

Type Parameters

T

The 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

clientId string

The client ID.

key byte[]

The AES key, of 128, 192 or 256 bits.

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

bytes long

The 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

size long

The size in bytes; a negative one keeps its sign.

use1024 bool

true for units of 1024; false for units of 1000.

round bool

true to round to a whole number of the unit.

Returns

string

The text, or 0 for 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

sizeMb long

The size in megabytes; a negative one keeps its sign.

use1024 bool

true for units of 1024; false, the default, for units of 1000.

round bool

true to round to a whole number of the unit.

Returns

string

The text, or 0 for zero.

FromMB(long)

Converts megabytes to bytes, a megabyte being 1024 × 1024 bytes.

public static long FromMB(long megabytes)

Parameters

megabytes long

The 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

keySizeInBit int

The 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

assembly Assembly

The assembly.

key string

The key.

defaultValue string

The 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

value byte[]

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

currencyCode string

The 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

ipAddress IPAddress

The address.

defaultPort int

The port to try first, or 0 for any.

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

ipAddress IPAddress

The address.

defaultPort int

The port to try first, or 0 for any.

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

value string

The text.

length int?

The number of hex characters to keep, or null for all 64.

Returns

string

The hex text.

Exceptions

ArgumentOutOfRangeException

length is negative or over 64.

GetRequiredInstance<T>(T?)

Returns an object that must have been set.

public static T GetRequiredInstance<T>(T? obj)

Parameters

obj T

The object, or null.

Returns

T

The object.

Type Parameters

T

The 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

value string

The 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

ex Exception

The exception.

Returns

bool

true if it is; otherwise, false.

IsInfinite(TimeSpan)

Determines whether a time span means no limit: MaxValue or InfiniteTimeSpan.

public static bool IsInfinite(TimeSpan timeSpan)

Parameters

timeSpan TimeSpan

The time span.

Returns

bool

true if it does; otherwise, false.

IsNullOrEmpty<T>(IEnumerable<T>?)

Determines whether a sequence is null or has no item.

public static bool IsNullOrEmpty<T>(IEnumerable<T>? array)

Parameters

array IEnumerable<T>

The sequence, or null.

Returns

bool

true if it is null or empty; otherwise, false.

Type Parameters

T

The type of the items.

IsNullOrEmpty<T>(T[]?)

Determines whether an array is null or empty.

public static bool IsNullOrEmpty<T>(T[]? array)

Parameters

array T[]

The array, or null.

Returns

bool

true if it is null or empty; otherwise, false.

Type Parameters

T

The 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

ex Exception

The exception.

Returns

bool

true if it is; otherwise, false.

IsTcpClientHealthy(TcpClient)

Determines whether a TCP client is connected and its socket reports no error.

public static bool IsTcpClientHealthy(TcpClient tcpClient)

Parameters

tcpClient TcpClient

The TCP client.

Returns

bool

true if it is; otherwise, false, also when the check fails.

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

commandLine string

The 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

dateTime DateTime

The 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

task Task

The task.

cancellationToken CancellationToken

The token to monitor for cancellation requests.

Returns

Task

A task that completes with the task.

Exceptions

OperationCanceledException

cancellationToken was 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

task Task

The task.

timeout TimeSpan

How long to wait; zero for no limit.

cancellationToken CancellationToken

The 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

cancellationToken was 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

task Task<T>

The task.

cancellationToken CancellationToken

The token to monitor for cancellation requests.

Returns

Task<T>

A task whose result is the task's.

Type Parameters

T

The type of the result.

Exceptions

OperationCanceledException

cancellationToken was 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

task Task<T>

The task.

timeout TimeSpan

How long to wait; zero for no limit.

cancellationToken CancellationToken

The token to monitor for cancellation requests.

Returns

Task<T>

A task whose result is the task's.

Type Parameters

T

The type of the result.

Exceptions

TimeoutException

The timeout passed first.

ArgumentOutOfRangeException

The timeout is negative, other than infinite, or too long.

OperationCanceledException

cancellationToken was 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

lockObject object

The lock.

collection IEnumerable<T>

The collection.

Returns

T[]

The array.

Type Parameters

T

The 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

first IEnumerable<T>

The first sequence, or null.

second IEnumerable<T>

The second sequence, or null.

Returns

bool

true if they are the same; otherwise, false.

Type Parameters

T

The 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

array T[]

The array.

Type Parameters

T

The 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

filePath string

The file's path.

Returns

Exception

The failure, or null.

TryGetCountryName(string?)

Gets a country's English name from its code.

public static string? TryGetCountryName(string? countryCode)

Parameters

countryCode string

The country's two-letter code, or null.

Returns

string

The name, or null for an empty or unknown code.

TryParseUrl(string?, UriKind)

Parses a URL.

public static Uri? TryParseUrl(string? stringUrl, UriKind uriKind = UriKind.Absolute)

Parameters

stringUrl string

The URL's text, or null.

uriKind UriKind

The kind of URL expected. The default is absolute.

Returns

Uri

The URL, or null when the text is not one.

Exceptions

ArgumentException

uriKind is not a valid kind.