Class NeonHelper
Provides global common utilities and state.
Namespace: Neon.Common
Assembly: Neon.Common.dll
Syntax
public static class NeonHelper
Fields
CR
Ordinal value of an ASCII carriage return.
Declaration
public const int CR = 13
Field Value
| Type | Description |
|---|---|
| int |
CRLF
A string consisting of a CRLF sequence.
Declaration
public const string CRLF = "\r\n"
Field Value
| Type | Description |
|---|---|
| string |
DateFormat100NsTZ
Returns the date format string used for serialize dates with 100 nanosecond precision to strings like: 2018-06-05T14:30:13.000000Z
Declaration
public const string DateFormat100NsTZ = "yyyy-MM-ddTHH:mm:ss.fffffffZ"
Field Value
| Type | Description |
|---|---|
| string |
DateFormat100NsTZOffset
Returns the date format string used for serialize dates with 100 nanosecond precision to strings like: 2018-06-05T14:30:13.000000+00:00
Declaration
public const string DateFormat100NsTZOffset = "yyyy-MM-ddTHH:mm:ss.fffffff+00:00"
Field Value
| Type | Description |
|---|---|
| string |
DateFormatMicroTZ
Returns the date format string used for serialize dates with microsecond precision to strings like: 2018-06-05T14:30:13.000000Z
Declaration
public const string DateFormatMicroTZ = "yyyy-MM-ddTHH:mm:ss.ffffffZ"
Field Value
| Type | Description |
|---|---|
| string |
DateFormatMicroTZOffset
Returns the date format string used for serialize dates with microsecond precision to strings like: 2018-06-05T14:30:13.000000+00:00
Declaration
public const string DateFormatMicroTZOffset = "yyyy-MM-ddTHH:mm:ss.ffffff+00:00"
Field Value
| Type | Description |
|---|---|
| string |
DateFormatSecondTZ
Returns the date format string used for serialize dates with second precision to strings like: 2018-06-05T14:30:13Z
Declaration
public const string DateFormatSecondTZ = "yyyy-MM-ddTHH:mm:ssZ"
Field Value
| Type | Description |
|---|---|
| string |
DateFormatTZ
Returns the date format string used for serialize dates with millisecond precision to strings like: 2018-06-05T14:30:13.000Z
Declaration
public const string DateFormatTZ = "yyyy-MM-ddTHH:mm:ss.fffZ"
Field Value
| Type | Description |
|---|---|
| string |
DateFormatTZOffset
Returns the date format string used for serialize dates with millisecond precision to strings like: 2018-06-05T14:30:13.000+00:00
Declaration
public const string DateFormatTZOffset = "yyyy-MM-ddTHH:mm:ss.fff+00:00"
Field Value
| Type | Description |
|---|---|
| string |
ESC
Ordinal value of an ASCII escape character.
Declaration
public const int ESC = 27
Field Value
| Type | Description |
|---|---|
| int |
HT
Ordinal value of an ASCII horizontal TAB.
Declaration
public const int HT = 9
Field Value
| Type | Description |
|---|---|
| int |
JsonRelaxedSerializerSettings
The global relaxed JSON serializer settings. These settings do not require that all source JSON properties match those defined by the type being deserialized.
Declaration
public static Lazy<JsonSerializerSettings> JsonRelaxedSerializerSettings
Field Value
| Type | Description |
|---|---|
| Lazy<JsonSerializerSettings> |
JsonStrictSerializerSettings
The global strict JSON serializer settings. These settings do require that all source JSON properties match those defined by the type being deserialized.
Declaration
public static Lazy<JsonSerializerSettings> JsonStrictSerializerSettings
Field Value
| Type | Description |
|---|---|
| Lazy<JsonSerializerSettings> |
LF
Ordinal value of an ASCII linefeed.
Declaration
public const int LF = 10
Field Value
| Type | Description |
|---|---|
| int |
LineEnding
Returns the native text line ending for the current environment.
Declaration
public static readonly string LineEnding
Field Value
| Type | Description |
|---|---|
| string |
NeonKubeOtelCollectorUri
The URI for Kubernetes Services deployed to namespaces for forwarding OTEL Collector log and trace information to the local Tempo installation or elsewhere.
Declaration
public const string NeonKubeOtelCollectorUri = "http://grafana-agent-node.neon-monitor.svc.cluster.local:4317"
Field Value
| Type | Description |
|---|---|
| string |
NeonMetricsPrefix
Returns the prefix to be used for Neon related Prometheus names.
Declaration
public const string NeonMetricsPrefix = "neonsdk"
Field Value
| Type | Description |
|---|---|
| string |
NeonPublicBucketUri
The URI for the public AWS S3 bucket where we persist cluster VM images and other things.
Declaration
public const string NeonPublicBucketUri = "https://neon-public.s3.us-west-2.amazonaws.com"
Field Value
| Type | Description |
|---|---|
| string |
NeonSdkDevRegistry
Identifies the development NEONSDK container image registry.
Declaration
public const string NeonSdkDevRegistry = "ghcr.io/neonrelease-dev"
Field Value
| Type | Description |
|---|---|
| string |
NeonSdkProdRegistry
Identifies the production NEONSDK container image registry.
Declaration
public const string NeonSdkProdRegistry = "ghcr.io/neonrelease"
Field Value
| Type | Description |
|---|---|
| string |
TAB
Ordinal value of an ASCII TAB character.
Declaration
public const int TAB = 9
Field Value
| Type | Description |
|---|---|
| int |
TestModeFolderVar
The environment variable used for unit testing that indicates
that Neon.Service.NeonService should run in test mode and
locate user test files in the folder specified by this variable
(when set).
Declaration
public const string TestModeFolderVar = "NF_TESTMODE_FOLDER"
Field Value
| Type | Description |
|---|---|
| string |
UnixEpoch
Returns the Unix epoch time: 01-01-1970 (UTC).
Declaration
public static readonly DateTime UnixEpoch
Field Value
| Type | Description |
|---|---|
| DateTime |
Properties
CpuArchitecture
Returns the current CPU architecture.
Declaration
public static CpuArchitecture CpuArchitecture { get; }
Property Value
| Type | Description |
|---|---|
| CpuArchitecture |
DebugLogPath
The fully qualified path to the file where the simple LogDebug(string) method will write debug lines. This defaults to debug-log.txt within the current user's home folder.
You may change this to a different location.
Declaration
public static string DebugLogPath { get; set; }
Property Value
| Type | Description |
|---|---|
| string |
DefaultUserHomeFolder
Returns the default user home. This is not affected by calls to SetUserHomeFolder(string).
Declaration
public static string DefaultUserHomeFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
DockerCli
Returns the name of the Docker CLI execuable for the current platform. This will be the fully qualified path to docker.exe on Windows and just docker on Linux and OS/X.
Declaration
public static string DockerCli { get; }
Property Value
| Type | Description |
|---|---|
| string | The path to the Docker CLI or |
DockerComposeCli
Returns the name of the Docker Compose CLI execuable for the current platform. This will be docker-compose.exe on Windows and just docker-compose on Linux and OS/x.
Declaration
public static string DockerComposeCli { get; }
Property Value
| Type | Description |
|---|---|
| string |
FileWildcards
Returns the characters used as wildcards for the current file system.
Declaration
public static char[] FileWildcards { get; }
Property Value
| Type | Description |
|---|---|
| char[] |
Framework
Identifies the .NET runtime hosting the current process.
Declaration
public static NetFramework Framework { get; }
Property Value
| Type | Description |
|---|---|
| NetFramework |
FrameworkDescription
Returns the .NET runtime description.
Declaration
public static string FrameworkDescription { get; }
Property Value
| Type | Description |
|---|---|
| string |
FrameworkVersion
Returns the current .NET runtime version hosting the current process.
Declaration
public static SemanticVersion FrameworkVersion { get; }
Property Value
| Type | Description |
|---|---|
| SemanticVersion |
HasElevatedPermissions
Determines whether the current process is running with elevated permissions. This corresponds to running with administrator privileges for Windows or as the root user for Linux and OS/X.
Declaration
public static bool HasElevatedPermissions { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Exceptions
| Type | Condition |
|---|---|
| PlatformNotSupportedException | Thrown for unsupported platforms. |
Is32BitBuild
Returns true if the client was built as 32-bit.
Declaration
public static bool Is32BitBuild { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Is32BitOS
Returns true for 32-bit operating systems.
Declaration
public static bool Is32BitOS { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Is64BitBuild
Returns true if the application was built as 64-bit.
Declaration
public static bool Is64BitBuild { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Is64BitOS
Returns true for 64-bit operating systems.
Declaration
public static bool Is64BitOS { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsARM
Returns true if the current process is runniong on an ARM processor.
Declaration
public static bool IsARM { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsCI
Returns true if the current process is running within a CI environment
such as GitHub Actions. This checks for this environment variable: CI=true.
Declaration
public static bool IsCI { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsDevWorkstation
Indicates whether the current application is running on a developer workstation. This is determined by the presence of the DEV_WORKSTATION environment variable.
Declaration
public static bool IsDevWorkstation { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsKubernetes
Returns true if the current process is running as a container on Kubernetes.
Declaration
public static bool IsKubernetes { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsLinux
Returns true if the current process is running on a Linux variant
operating system.
Declaration
public static bool IsLinux { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsMaintainer
Indicates whether the current user is a NEONFORGE maintainer. This is determined by the presence of the NF_MAINTAINER environment variable.
Declaration
public static bool IsMaintainer { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsOSX
Returns true if the current process is running on Mac OSX.
Declaration
public static bool IsOSX { get; }
Property Value
| Type | Description |
|---|---|
| bool |
IsWindows
Returns true if the current process is running on a Windows variant
operating system.
Declaration
public static bool IsWindows { get; }
Property Value
| Type | Description |
|---|---|
| bool |
JsonConverters
Returns the list of JsonConverter instances that will be automatically recognized by the JSON deserializers. This is initialized with converters for some common types like DateTime, TimeSpan, and Version.
note
IMPORTANT: You may customize this list but for that to have any impact, you must make the modifications very early in your application startup sequence, before any JSON serialization operations have been performed. Any changes made after this will be ignored.
Declaration
public static List<JsonConverter> JsonConverters { get; }
Property Value
| Type | Description |
|---|---|
| List<JsonConverter> |
MemoryMib
Returns the system RAM in MiB.
note
For applications running in containers, this will return information about the RAM available to the container, not the host system RAM.
Declaration
public static long MemoryMib { get; }
Property Value
| Type | Description |
|---|---|
| long |
NeonSdkAzureCodeSigningFolder
Returns the path to the folder used by NEONSDK to cache download Azure code signing code, creating the directory if it doesn't exist. This folder is located at: ~/.neonsdk/codesigning-azure
Declaration
public static string NeonSdkAzureCodeSigningFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
NeonSdkBranchRegistry
Returns the appropriate public container NEONSDK registry to be used for the git branch the assembly was built from. This returns NeonSdkProdRegistry for release branches and NeonSdkDevRegistry for all other branches.
Declaration
public static string NeonSdkBranchRegistry { get; }
Property Value
| Type | Description |
|---|---|
| string |
NeonSdkFolder
Returns the path to the folder used by NEONSDK to persist and cache state, creating the directory if it doesn't exist. This folder is located at: ~/.neonsdk
Declaration
public static string NeonSdkFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
NeonSdkUsbCodeSigningFolder
Returns the path to the folder used by NEONSDK to cache download local USB token code signing code, creating the directory if it doesn't exist. This folder is located at: ~/.neonsdk/codesigning-usb
Declaration
public static string NeonSdkUsbCodeSigningFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
OSDescription
Returns the operation system description.
Declaration
public static string OSDescription { get; }
Property Value
| Type | Description |
|---|---|
| string |
OpenEditorHandler
Used for implementing unit tests against the OpenEditor(string) method. OpenEditor(string) will call this action when it's non-null passing the file path, rather than actually opening the file in an editor. The handler can then simulate editing the file.
Declaration
public static Action<string> OpenEditorHandler { get; set; }
Property Value
| Type | Description |
|---|---|
| Action<string> |
ServiceContainer
The root dependency injection service container used by Neon class libraries. and applications.
Declaration
public static ServiceContainer ServiceContainer { get; set; }
Property Value
| Type | Description |
|---|---|
| ServiceContainer |
Remarks
This instance implements both the IServiceCollection and IServiceProvider interfaces and supports adding, removing, and locating services over the lifetime of the application. This is more flexible than the default Microsoft injection pattern, where services are added to an IServiceCollection at startup and then a read-only snapshot is taken via a BuildServiceProvider() call that is used throughout the remaining application lifespan.
This is implemented by a ServiceCollection by default. It is possible to replace this very early during application initialization but the default implementation should suffice for most purposes.
UserHomeFolder
Returns the path to the current user's HOME folder.
Declaration
public static string UserHomeFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
UserNeonDevBuildFolder
Returns the path to the development/build folder for NEONFORGE developers. This folder is used to hold build related files and is named .neondev/build under the current user's home folder.
note
This property ensures that the folder exists.
Declaration
public static string UserNeonDevBuildFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
UserNeonDevFolder
Returns the path to the development folder for NEONFORGE developers. This folder is used to hold build and test related files and is named .neondev under the current user's home folder.
Related: UserNeonDevBuildFolder, UserNeonDevTestFolder
note
This property ensures that the folder exists.
Declaration
public static string UserNeonDevFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
UserNeonDevTestFolder
Returns the path to the development/build folder for NEONFORGE developers. This folder is used to hold unit test related files and is named .neondev/test under the current user's home folder.
note
This property ensures that the folder exists.
Declaration
public static string UserNeonDevTestFolder { get; }
Property Value
| Type | Description |
|---|---|
| string |
VerifiedDockerCli
Returns the path to the Docker CLI on the current machine or throws an exception when the CLI cannot be located.
Declaration
public static string VerifiedDockerCli { get; }
Property Value
| Type | Description |
|---|---|
| string |
Exceptions
| Type | Condition |
|---|---|
| FileNotFoundException | Thrown when the Docker CLI could not be located. |
WindowsEdition
Identifies the current Windows edition (home, pro, server,...).
Declaration
public static WindowsEdition WindowsEdition { get; }
Property Value
| Type | Description |
|---|---|
| WindowsEdition |
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown when not running on Windows. |
Methods
ArrayEquals(byte[], byte[])
Determines whether two byte arrays contain the same values in the same order.
Declaration
public static bool ArrayEquals(byte[] v1, byte[] v2)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | v1 | Byte array #1. |
| byte[] | v2 | Byte array #2. |
Returns
| Type | Description |
|---|---|
| bool |
|
Base64UrlDecode(string)
Decodes a base64url encoded string. This is a URL and filename safe base-64 based encoding scheme: RFC6448.
Declaration
public static byte[] Base64UrlDecode(string encoded)
Parameters
| Type | Name | Description |
|---|---|---|
| string | encoded | The encoded string. |
Returns
| Type | Description |
|---|---|
| byte[] | The decoded bytes. |
Base64UrlEncode(byte[], bool)
Encodes a byte array using Base64Url encoding as specifed here: RFC 4648
Declaration
public static string Base64UrlEncode(byte[] bytes, bool retainPadding = false)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The input byte array. |
| bool | retainPadding | Optionally onverts any '=' characters padding into escaped "%3D", otherwise any padding will be omitted from the output. |
Returns
| Type | Description |
|---|---|
| string | The Base64Url encoded string. |
CastTo<TResult>(object)
Attempts to cast an object into a specific type.
Declaration
public static TResult CastTo<TResult>(object value)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be cast. |
Returns
| Type | Description |
|---|---|
| TResult | The casted result. |
Type Parameters
| Name | Description |
|---|---|
| TResult | The desired result type. |
Exceptions
| Type | Condition |
|---|---|
| InvalidCastException | Thrown if the value could not be cast into the type. |
ClearDebugLog()
Clears the debug log file if it exists.
Declaration
public static void ClearDebugLog()
CopyFolder(string, string)
Recursively copies the files within one folder to another, creating target folders as required.
Declaration
public static void CopyFolder(string sourceFolder, string targetFolder)
Parameters
| Type | Name | Description |
|---|---|---|
| string | sourceFolder | The source folder. |
| string | targetFolder | The target folder. |
Remarks
note
This method does not currently copy empty folders.
CreateBase36Uuid(bool)
Generates a 13 digit base-36 UUID including only lowercase ASCII characters and digits. This is useful for generating unique shorter names for Kubernetes objects etc.
Declaration
public static string CreateBase36Uuid(bool secure = true)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | secure | Optionally specifies that a cryptographically secure algorithm is is used to generate the UUID, rather than the default pseudo random generator. Cryptogrphically secure algorithms consume system entropy. |
Returns
| Type | Description |
|---|---|
| string | The new base-36 string. |
CreateSecureRandom()
Creates a Random pseudo random number generated with a cryptographically random seed.
Declaration
public static Random CreateSecureRandom()
Returns
| Type | Description |
|---|---|
| Random | A Random. |
DecryptFile(string)
Decrypts a file or directory when supported by the underlying operating system and file system. Currently, this only works on non-HOME versions of Windows and NTFS file systems.
Declaration
public static bool DecryptFile(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file or directory path. |
Returns
| Type | Description |
|---|---|
| bool |
|
DeflateBytes(byte[])
Uses deflate to commpress a byte array.
Declaration
public static byte[] DeflateBytes(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The input byte array or |
Returns
| Type | Description |
|---|---|
| byte[] | The compressed bytes or |
DeflateString(string)
Uses deflate to commpress a string.
Declaration
public static byte[] DeflateString(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string or |
Returns
| Type | Description |
|---|---|
| byte[] | The compressed bytes or |
DeleteFile(string)
Deletes a file if it exists.
Declaration
public static void DeleteFile(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The target file. |
DeleteFolder(string)
Recursively deletes a file system folder, ignoring any errors.
Declaration
public static void DeleteFolder(string folder)
Parameters
| Type | Name | Description |
|---|---|---|
| string | folder | The folder path. |
DeleteFolderContents(string)
Recursively deletes the contents of a file folder, ignoring any errors.
Declaration
public static void DeleteFolderContents(string folder)
Parameters
| Type | Name | Description |
|---|---|---|
| string | folder | The folder path. |
DisableOptionalWindowsFeature(string)
Disables an optional Windows feature.
Declaration
public static void DisableOptionalWindowsFeature(string feature)
Parameters
| Type | Name | Description |
|---|---|---|
| string | feature |
Remarks
This method does nothing when the feature is already disabled.
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown if the feature does't exist or is enabled and waiting for a Windows restart. |
DoesNotThrow(Action)
Verfies that an action does not throw an exception.
Declaration
[Pure]
public static bool DoesNotThrow(Action action)
Parameters
| Type | Name | Description |
|---|---|---|
| Action | action | The action. |
Returns
| Type | Description |
|---|---|
| bool |
|
DoesNotThrow<TException>(Action)
Verfies that an action does not throw a TException.
Declaration
public static bool DoesNotThrow<TException>(Action action) where TException : Exception
Parameters
| Type | Name | Description |
|---|---|---|
| Action | action | The action. |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| TException | The exception type. |
EnableOptionalWindowsFeature(string)
Enables an optional Windows feature, returning an indication of whether a Windows restart is required to complete the installation.
Declaration
public static bool EnableOptionalWindowsFeature(string feature)
Parameters
| Type | Name | Description |
|---|---|---|
| string | feature |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
This method does nothing when the feature is already enabled or has been enabled but is waiting for a restart.
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown if the feature does't exist. |
EncryptFile(string)
Encrypts a file or directory when supported by the underlying operating system and file system. Currently, this only works on non-HOME versions of Windows and NTFS file systems.
Declaration
public static bool EncryptFile(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file or directory path. |
Returns
| Type | Description |
|---|---|
| bool |
|
EnsureElevatedPermissions()
Ensures that the current process has elevated permissions. See HasElevatedPermissions.
Declaration
public static void EnsureElevatedPermissions()
Exceptions
| Type | Condition |
|---|---|
| SecurityException | Thrown when the process does not have elevated permissions. |
| PlatformNotSupportedException | Thrown for unsupported platforms. |
EnumToString(Type, object)
Type-safe enum serializer that also honors any EnumMemberAttribute
decorating the enumeration values.
Declaration
public static string EnumToString(Type type, object input)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The enumeration type. |
| object | input | The input value. |
Returns
| Type | Description |
|---|---|
| string | The deserialized value. |
EnumToString<TEnum>(TEnum)
Type-safe enum serializer that also honors any EnumMemberAttribute
decorating the enumeration values.
Declaration
public static string EnumToString<TEnum>(TEnum input) where TEnum : struct, Enum
Parameters
| Type | Name | Description |
|---|---|---|
| TEnum | input | The input value. |
Returns
| Type | Description |
|---|---|
| string | The deserialized value. |
Type Parameters
| Name | Description |
|---|---|
| TEnum | The enumeration type. |
EscapeCsv(string)
Escapes a string passed so that is suitable for writing to a CSV file as a field.
Declaration
public static string EscapeCsv(string value)
Parameters
| Type | Name | Description |
|---|---|---|
| string | value | The field value. |
Returns
| Type | Description |
|---|---|
| string | The escaped string. |
Remarks
The method surrounds the value with double quotes if it contains a comma or CRLF as well as escaping any double quotes in the string with second double quote.
ExceptionError(Exception, bool, bool, int)
Returns a string representation of an exception suitable for logging.
Declaration
public static string ExceptionError(Exception e, bool stackTrace = false, bool excludeInner = false, int depth = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| Exception | e | The exception. |
| bool | stackTrace | Optionally include the stack track. |
| bool | excludeInner | Optionally exclude information about any inner exception. |
| int | depth | INTERNAL USE ONLY: Used to prevent infinite recursion when inner exceptions cycle. |
Returns
| Type | Description |
|---|---|
| string | The error string. |
Execute(string, object[], TimeSpan?, Process, string, bool, Dictionary<string, string>, TextReader, Action<Process>)
Starts a process with an array of arguments to run an executable file and then waits for the process to terminate.
Declaration
public static int Execute(string path, object[] args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TextReader input = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| object[] | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. |
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| int | The process exit code. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
Execute(string, string, TimeSpan?, Process, string, bool, Dictionary<string, string>, TextReader, Action<Process>)
Starts a process to run an executable file and then waits for the process to terminate.
Declaration
public static int Execute(string path, string args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TextReader input = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| string | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. |
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| int | The process exit code. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteAsync(string, object[], TimeSpan?, Process, string, bool, Dictionary<string, string>, TextReader, Action<Process>)
Asynchronously starts a process to run an executable file with an array of arguments and then and waits for the process to terminate.
Declaration
public static Task<int> ExecuteAsync(string path, object[] args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TextReader input = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| object[] | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process.Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. |
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| Task<int> | The process exit code. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteAsync(string, string, TimeSpan?, Process, string, bool, Dictionary<string, string>, TextReader, Action<Process>)
Asynchronously starts a process to run an executable file and then waits for the process to terminate.
Declaration
public static Task<int> ExecuteAsync(string path, string args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TextReader input = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| string | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
| Action<Process> | processCallback |
Returns
| Type | Description |
|---|---|
| Task<int> | The process exit code. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteCapture(string, object[], TimeSpan?, Process, string, bool, Dictionary<string, string>, Action<string>, Action<string>, TextReader, Encoding, Action<Process>)
Starts a process to run an executable file and then waits for the process to terminate while capturing any output written to the standard output and error streams.
Declaration
public static ExecuteResponse ExecuteCapture(string path, object[] args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, Action<string> outputAction = null, Action<string> errorAction = null, TextReader input = null, Encoding outputEncoding = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| object[] | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| Action<string> | outputAction | Optional action that will be called when the process outputs some text. |
| Action<string> | errorAction | Optional action that will be called when the process outputs some error text. |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as standard input. |
| Encoding | outputEncoding | Optionally specifies the expected standard output/error encoding. This defaults to
|
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| ExecuteResponse | The ExecuteResponse including the process exit code and capture standard output and error streams. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
You can optionally specify the outputAction and/or errorAction
callbacks to receive the process output text as it is received. outputAction will
be called with both the STDOUT and STDERR streams if errorAction is null
otherwise it will called only with STDOUT text.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteCapture(string, string, TimeSpan?, Process, string, bool, Dictionary<string, string>, Action<string>, Action<string>, TextReader, Encoding, Action<Process>)
Starts a process to run an executable file and then waits for the process to terminate while capturing any output written to the standard output and error streams.
Declaration
public static ExecuteResponse ExecuteCapture(string path, string args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, Action<string> outputAction = null, Action<string> errorAction = null, TextReader input = null, Encoding outputEncoding = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| string | args | Command line arguments (or |
| TimeSpan? | timeout | Optional maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| Action<string> | outputAction | Optional action that will be called when the process outputs some text. |
| Action<string> | errorAction | Optional action that will be called when the process outputs some error text. |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as standard input. |
| Encoding | outputEncoding | Optionally specifies the expected standard output/error encoding. This defaults to
|
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| ExecuteResponse | The ExecuteResponse including the process exit code and capture standard output and error streams. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
You can optionally specify the outputAction and/or errorAction
callbacks to receive the process output text as it is received. outputAction will
be called with both the STDOUT and STDERR streams if errorAction is null
otherwise it will called only with STDOUT text.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteCaptureAsync(string, object[], string, bool, Dictionary<string, string>, TimeSpan?, Process, TextReader, Encoding, Action<Process>)
Asynchronously starts a process to run an executable file and then waits for the process to terminate while capturing any output written to the standard output and error streams.
Declaration
public static Task<ExecuteResponse> ExecuteCaptureAsync(string path, object[] args, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TimeSpan? timeout = null, Process process = null, TextReader input = null, Encoding outputEncoding = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| object[] | args | Command line arguments (or |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TimeSpan? | timeout | Maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. |
| Encoding | outputEncoding | Optionally specifies the expected standard output/error encoding. This defaults to
|
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| Task<ExecuteResponse> | The ExecuteResponse including the process exit code and capture standard output and error streams. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteCaptureAsync(string, string, TimeSpan?, Process, string, bool, Dictionary<string, string>, TextReader, Encoding, Action<Process>)
Asynchronously starts a process to run an executable file and then waits for the process to terminate while capturing any output written to the standard output and error streams.
Declaration
public static Task<ExecuteResponse> ExecuteCaptureAsync(string path, string args, TimeSpan? timeout = null, Process process = null, string workingDirectory = null, bool clearEnvironment = false, Dictionary<string, string> environmentVariables = null, TextReader input = null, Encoding outputEncoding = null, Action<Process> processCallback = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| string | args | Command line arguments (or |
| TimeSpan? | timeout | Maximum time to wait for the process to complete or |
| Process | process | Optional existing Process instance used to launch the process. |
| string | workingDirectory | Optionally specifies the working directory for executing the program. |
| bool | clearEnvironment | Optionally clears all environment variables that would be passed to the program.
This happens before setting any environment variables passed as |
| Dictionary<string, string> | environmentVariables | Optionally specifies the environment variables to be passed into the process.
The new process inherits the current processes variables when this is |
| TextReader | input | Optionally specifies a TextReader with text to be sent to the process as input. |
| Encoding | outputEncoding | Optionally specifies the expected standard output/error encoding. This defaults to
|
| Action<Process> | processCallback | Optionally passed to obtain the details of the process created to execute the command. When a non-null value is passed, the callback will be called with the Process instances just after it is launched. |
Returns
| Type | Description |
|---|---|
| Task<ExecuteResponse> | The ExecuteResponse including the process exit code and capture standard output and error streams. |
Remarks
note
If timeout is exceeded and execution has not completed in time
then a TimeoutException will be thrown and the process will be killed
if it was created by this method. Process instances passed via the process
parameter will not be killed in this case.
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the process did not exit within the |
ExecuteShell(string)
Executes a command using the local shell, CMD.EXE for Windows and Bash for OSX and Linux.
Declaration
public static int ExecuteShell(string command)
Parameters
| Type | Name | Description |
|---|---|---|
| string | command | The command and arguments to be executed. |
Returns
| Type | Description |
|---|---|
| int | The process exit code. |
ExpandTabs(string, int)
Expands any embedded TAB (\t) characters in the string passed into spaces such that the tab stops will be formatted correctly.
Declaration
public static string ExpandTabs(string input, int tabStop = 4)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
| int | tabStop | Optionally expands TABs into spaces when greater than zero or converts a series of leading spaces into tabs if less than zero. This defaults to 4. |
Returns
| Type | Description |
|---|---|
| string | The expanded string. |
Remarks
note
If the string passed includes line ending characters (CR or LF) then the output will include line endings for every line, including the last one.
A positive tabStop does what you'd expect by converting
spaces in the string into TABs such that the tab stops align to the value
passed. This works a bit differently for negative values.
A negative tabStop indicates that leading spaces in each
line will be converted into TABs. A value of -1 indicates that each leading
two spaces will bve converted into a TAB, a value of -2 indicates that each
leading 2 spaces will be converted into a TAB, and so on.
Conversion to TABs will cease when the first non space is ecountered and any odd number of spaces remaining will be included in the output.
FileWildcardRegex(string)
Generates a case insensitive Regex equivalent to a standard file name wildcard pattern using [*] and [?] characters.
Declaration
public static Regex FileWildcardRegex(string pattern)
Parameters
| Type | Name | Description |
|---|---|---|
| string | pattern | The file name wildcard pattern. |
Returns
| Type | Description |
|---|---|
| Regex | The corresponding Regex. |
Fork(string, params object[])
Forks a child process that will run in parallel with the current process.
Declaration
public static Process Fork(string path, params object[] args)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | Name or path to the executable file. note
The |
| object[] | args | Command line arguments (or |
Returns
| Type | Description |
|---|---|
| Process | The Process information. |
FromBase64(string, Encoding)
Declaration
public static string FromBase64(string encodedValue, Encoding encoding = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | encodedValue | The base64 encoded input. |
| Encoding | encoding | Optionally specifies the encoding to use to convert the decoded bytes to the result. This defaults to UTF8. |
Returns
| Type | Description |
|---|---|
| string | The converted string. |
FromHex(string)
Parses the hex string passed and converts it a byte array.
Declaration
public static byte[] FromHex(string s)
Parameters
| Type | Name | Description |
|---|---|---|
| string | s | The string to convert from hex. |
Returns
| Type | Description |
|---|---|
| byte[] | The corresponding byte array. |
Remarks
note
The method ignores whitespace characters (SP,CR,LF, and TAB) in the string so that HEX strings copied directly from typical hex dump outputs can be passed directly with minimal editing.
Exceptions
| Type | Condition |
|---|---|
| FormatException | Thrown if the input is not valid. |
GetApplicationFolder()
Returns the fully qualified path to the folder where the current executable resides. This includes a terminating "".
Declaration
public static string GetApplicationFolder()
Returns
| Type | Description |
|---|---|
| string | Path to the folder holding the executable |
GetAssemblyFolder(Assembly)
Returns the fully qualified path to the folder holding the assembly passed (includes the terminating "").
Declaration
[Obsolete("Avoid this because it is not compatible with single-file executables.")]
public static string GetAssemblyFolder(Assembly assembly)
Parameters
| Type | Name | Description |
|---|---|---|
| Assembly | assembly | The assembly. |
Returns
| Type | Description |
|---|---|
| string | Path to the folder holding the assembly. |
GetAssemblyPath(Assembly)
Returns the fully qualified path to the assembly file.
Declaration
[Obsolete("Avoid this because it is not compatible with single-file executables.")]
public static string GetAssemblyPath(Assembly assembly)
Parameters
| Type | Name | Description |
|---|---|---|
| Assembly | assembly | The assembly. |
Returns
| Type | Description |
|---|---|
| string | The assembly's path. |
GetConstructor(Type, params Type[])
Uses reflection to locate a specific public or non-public constructor for a type.
Declaration
public static ConstructorInfo GetConstructor(Type type, params Type[] parameterTypes)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The target type. |
| Type[] | parameterTypes | The parameter types. |
Returns
| Type | Description |
|---|---|
| ConstructorInfo | The MethodInfo. |
Exceptions
| Type | Condition |
|---|---|
| MissingMethodException | Thrown if the method does not exist. |
GetCryptoRandomBytes(int)
Generates a byte array filled with a cryptographically strong sequence of random values.
Declaration
public static byte[] GetCryptoRandomBytes(int count)
Parameters
| Type | Name | Description |
|---|---|---|
| int | count | The number of random bytes to be generated. |
Returns
| Type | Description |
|---|---|
| byte[] | The random byte array. |
GetCryptoRandomPassword(int)
Generates a cryptographically random password.
Declaration
public static string GetCryptoRandomPassword(int length)
Parameters
| Type | Name | Description |
|---|---|---|
| int | length | The password length. |
Returns
| Type | Description |
|---|---|
| string | The generated password. |
GetEnhancedJsonConverters()
Returns instances of the types that implement IEnhancedJsonConverter from the Neon.Common assembly.
Declaration
public static List<IEnhancedJsonConverter> GetEnhancedJsonConverters()
Returns
| Type | Description |
|---|---|
| List<IEnhancedJsonConverter> | The list of converters. |
GetEntryAssemblyPath()
Returns the fully qualified path the entry assembly for the current process.
Declaration
[Obsolete("Avoid this because it is not compatible with single-file executables.")]
public static string GetEntryAssemblyPath()
Returns
| Type | Description |
|---|---|
| string | The entry assembly file path. |
GetEnumNames<TEnum>()
Returns the value names for an enumeration type. This is similar to GetNames(Type) but also honors value names customized via EnumMemberAttribute.
Declaration
public static string[] GetEnumNames<TEnum>() where TEnum : struct, Enum
Returns
| Type | Description |
|---|---|
| string[] | The array of value names. |
Type Parameters
| Name | Description |
|---|---|
| TEnum |
GetExecuteCommandLine(string, params object[])
Returns the actual command line that will be executed from the command and arguments passed.
Declaration
public static string GetExecuteCommandLine(string command, params object[] args)
Parameters
| Type | Name | Description |
|---|---|---|
| string | command | The command to be executed. |
| object[] | args | Optional command arguments. |
Returns
| Type | Description |
|---|---|
| string | The actual command line to be executed. |
GetMethod(Type, string, params Type[])
Uses reflection to locate a specific public, non-public, instance or static method on a type.
Declaration
public static MethodInfo GetMethod(Type type, string name, params Type[] parameterTypes)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The target type. |
| string | name | The method name. |
| Type[] | parameterTypes | The parameter types. |
Returns
| Type | Description |
|---|---|
| MethodInfo | The MethodInfo. |
Exceptions
| Type | Condition |
|---|---|
| MissingMethodException | Thrown if the method does not exist. |
GetProcessById(int)
Returns the Process associated with an ID
or null if no process with this ID exists.
Declaration
public static Process GetProcessById(int id)
Parameters
| Type | Name | Description |
|---|---|---|
| int | id | The target process ID. |
Returns
| Type | Description |
|---|---|
| Process | The Process or |
Remarks
This is slightly different from how GetProcessById(int)
works. That method throws an ArgumentException if there's
no process with the ID where as this one will return null.
GetTaskResultAsObjectAsync(Task)
Used to await a generic Task<TResult> and return its result as an object. This is handy for situations where the task result type is unknown at compile time.
Declaration
public static Task<object> GetTaskResultAsObjectAsync(Task task)
Parameters
| Type | Name | Description |
|---|---|---|
| Task | task | The Task<TResult>. |
Returns
| Type | Description |
|---|---|
| Task<object> | The task result. |
GetWindowsOptionalFeatureStatus(string)
Returns the installation status for the named feature.
Declaration
public static WindowsFeatureStatus GetWindowsOptionalFeatureStatus(string feature)
Parameters
| Type | Name | Description |
|---|---|---|
| string | feature | Specifies the English name for the feature. |
Returns
| Type | Description |
|---|---|
| WindowsFeatureStatus | The WindowsFeatureStatus for the feature. |
Remarks
You'll need to pass the feature name in English. You can list possible feature names by executing this in your command shell:
note
Unknown will be returned for unknown features.
GetWindowsOptionalFeatures()
Returns a dictionary mapping optional Windows feature names to a WindowsFeatureStatus indicating feature installation status.
note
This method requires elevated permissions.
Declaration
public static Dictionary<string, WindowsFeatureStatus> GetWindowsOptionalFeatures()
Returns
| Type | Description |
|---|---|
| Dictionary<string, WindowsFeatureStatus> | The feature dictionary. |
Remarks
note
The feature names are in English and the lookup is case-insensitive.
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown when not running on Windows. |
| ExecuteException | Thrown when the current process doesn't have elevated permissions. |
GunzipBytes(byte[])
Uses GZIP to decompress a byte array from compressed bytes.
Declaration
public static byte[] GunzipBytes(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The compressed bytes or |
Returns
| Type | Description |
|---|---|
| byte[] | The decompressed string or |
GunzipFile(string, string)
Use GZIP to uncompress one file into another.
Declaration
public static void GunzipFile(string sourcePath, string targetPath)
Parameters
| Type | Name | Description |
|---|---|---|
| string | sourcePath | Path to the (compressed) source file. |
| string | targetPath | Path to the (uncompressed) target file. |
GunzipString(byte[])
Uses GZIP to decompress a string from compressed bytes.
Declaration
public static string GunzipString(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The compressed bytes or |
Returns
| Type | Description |
|---|---|
| string | The decompressed string or |
GzipBytes(byte[])
Uses GZIP to commpress a byte array.
Declaration
public static byte[] GzipBytes(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The input byte array or |
Returns
| Type | Description |
|---|---|
| byte[] | The compressed bytes or |
GzipFile(string, string)
Use GZIP to compress one file into another.
Declaration
public static void GzipFile(string sourcePath, string targetPath)
Parameters
| Type | Name | Description |
|---|---|---|
| string | sourcePath | Path to the (uncompressed) source file. |
| string | targetPath | Path to the (compressed) target file. |
GzipString(string)
Uses GZIP to commpress a string.
Declaration
public static byte[] GzipString(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string or |
Returns
| Type | Description |
|---|---|
| byte[] | The compressed bytes or |
HexDump(byte[], int, HexDumpOption)
Returns a byte array as a formatted hex dump.
Declaration
public static string HexDump(byte[] data, int bytesPerLine, HexDumpOption options)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | data | The buffer to be dumped. |
| int | bytesPerLine | The number of bytes to dump per output line. |
| HexDumpOption | options | The formatting options. |
Returns
| Type | Description |
|---|---|
| string | The hex dump string. |
HexDump(byte[], int, int, int, HexDumpOption)
Returns a byte array as a formatted hex dump.
Declaration
public static string HexDump(byte[] data, int start, int count, int bytesPerLine, HexDumpOption options)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | data | The buffer to be dumped. |
| int | start | The first byte to be dumped. |
| int | count | The number of bytes to be dumped. |
| int | bytesPerLine | The number of bytes to dump per output line. |
| HexDumpOption | options | The formatting options. |
Returns
| Type | Description |
|---|---|
| string | The hex dump string. |
HexValue(char)
Returns the decimal value of the hex digit passed.
Declaration
public static int HexValue(char ch)
Parameters
| Type | Name | Description |
|---|---|---|
| char | ch | The hex digit. |
Returns
| Type | Description |
|---|---|
| int | The corresponding decimal value. |
Remarks
Throws a FormatException if the character is not a hex digit.
InflateBytes(byte[])
Uses deflate to decompress a byte array from compressed bytes.
Declaration
public static byte[] InflateBytes(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The compressed bytes or |
Returns
| Type | Description |
|---|---|
| byte[] | The decompressed string or |
InflateString(byte[])
Uses deflate to decompress a string from compressed bytes.
Declaration
public static string InflateString(byte[] bytes)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | bytes | The compressed bytes or |
Returns
| Type | Description |
|---|---|
| string | The decompressed string or |
IsGzipped(Stream)
Examines a Stream to determine whether it has been compressed via GZIP. This assumes that the current position points to the GZIP header if there is one. The stream position will be restored before returning.
Declaration
public static bool IsGzipped(Stream stream)
Parameters
| Type | Name | Description |
|---|---|---|
| Stream | stream | The stream. |
Returns
| Type | Description |
|---|---|
| bool |
|
IsGzipped(string)
Examines a file to determine whether it has been compressed via GZIP.
Declaration
public static bool IsGzipped(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file path. |
Returns
| Type | Description |
|---|---|
| bool |
|
IsHex(char)
Returns true if the character passed is a hex digit.
Declaration
public static bool IsHex(char ch)
Parameters
| Type | Name | Description |
|---|---|---|
| char | ch | The character to test. |
Returns
| Type | Description |
|---|---|
| bool |
|
IsOdd(int)
Determines whether an integer is odd.
Declaration
public static bool IsOdd(int value)
Parameters
| Type | Name | Description |
|---|---|---|
| int | value | The value. |
Returns
| Type | Description |
|---|---|
| bool |
|
IsWithin(DateTime, DateTime, TimeSpan)
Determines whether a value is within expected - maxDelta
and value + maxDelta inclusive. This is useful for unit tests
where there might be an minor allowable variance due to clock skew, etc.
Declaration
public static bool IsWithin(DateTime expected, DateTime value, TimeSpan maxDelta)
Parameters
| Type | Name | Description |
|---|---|---|
| DateTime | expected | The expected value. |
| DateTime | value | The value being tested. |
| TimeSpan | maxDelta | The allowed variance. |
Returns
| Type | Description |
|---|---|
| bool |
|
IsWithin(DateTimeOffset, DateTimeOffset, TimeSpan)
Determines whether a value is within expected - maxDelta
and value + maxDelta inclusive. This is useful for unit tests
where there might be an minor allowable variance due to clock skew, etc.
Declaration
public static bool IsWithin(DateTimeOffset expected, DateTimeOffset value, TimeSpan maxDelta)
Parameters
| Type | Name | Description |
|---|---|---|
| DateTimeOffset | expected | The expected value. |
| DateTimeOffset | value | The value being tested. |
| TimeSpan | maxDelta | The allowed variance. |
Returns
| Type | Description |
|---|---|
| bool |
|
JTokenEquals(JToken, JToken)
Compares the two Newtonsoft JSON.NET JToken instances along with their decendants for equality. This is an alternative to JToken.EqualityComparer which seems to have some problems, as outlined in the remarks.
Declaration
public static bool JTokenEquals(JToken token1, JToken token2)
Parameters
| Type | Name | Description |
|---|---|---|
| JToken | token1 | The first token. |
| JToken | token2 | The second token. |
Returns
| Type | Description |
|---|---|
| bool |
|
JsonClone<T>(T)
Creates a deep clone of an object by first serializing to JSON and then deserializing it.
Declaration
public static T JsonClone<T>(T value) where T : class
Parameters
| Type | Name | Description |
|---|---|---|
| T | value | The object being clonned or |
Returns
| Type | Description |
|---|---|
| T | The clone. |
Type Parameters
| Name | Description |
|---|---|
| T | The object type. |
JsonDeserialize(Type, byte[], bool)
Non-generic method that deserializes UTF-8 encoded JSON bytes, optionally requiring strict mapping of input properties to the target type.
Declaration
public static object JsonDeserialize(Type type, byte[] jsonBytes, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The target type. |
| byte[] | jsonBytes | The UTF-8 encoded JSON bytes. |
| bool | strict | Optionally require that all input properties map to |
Returns
| Type | Description |
|---|---|
| object | The parsed |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonDeserialize(Type, string, bool)
Non-generic method that deserializes JSON text, optionally requiring strict mapping of input properties to the target type.
Declaration
public static object JsonDeserialize(Type type, string json, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The target type. |
| string | json | The JSON text. |
| bool | strict | Optionally require that all input properties map to |
Returns
| Type | Description |
|---|---|
| object | The parsed |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonDeserialize<T>(byte[], bool)
Deserializes UITF-8 encoded JSON bytes, optionally requiring strict mapping of input properties to the target type.
Declaration
public static T JsonDeserialize<T>(byte[] jsonBytes, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | jsonBytes | The UTF-8 encoded JSON bytes. |
| bool | strict | Optionally require that all input properties map to |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonDeserialize<T>(string, JsonSerializerSettings)
Deserializes JSON text using custom settings.
Declaration
public static T JsonDeserialize<T>(string json, JsonSerializerSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| string | json | The JSON text. |
| JsonSerializerSettings | settings | The optional settings or |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonDeserialize<T>(string, bool)
Deserializes JSON text, optionally requiring strict mapping of input properties to the target type.
Declaration
public static T JsonDeserialize<T>(string json, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| string | json | The JSON text. |
| bool | strict | Optionally require that all input properties map to |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonEquals(object, object)
Compares two object instances for equality by serializing them JSON and comparing the output.
Declaration
public static bool JsonEquals(object v1, object v2)
Parameters
| Type | Name | Description |
|---|---|---|
| object | v1 | Value 1 |
| object | v2 | Value 2 |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
This is a convienent and safe way of comparing two objects without having to comparing a potentially complex tree of members and then maintaining that as code changes over time at the cost of having to perform the serializations.
JsonOrYamlDeserialize<T>(string, bool)
Deserializes JSON or YAML text using, optionally requiring strict mapping of input properties to the target type.
Declaration
public static T JsonOrYamlDeserialize<T>(string input, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input text (JSON or YAML). |
| bool | strict | Optionally require that all input properties map to |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
Remarks
note
This method works by looking for leading '{' or '[' as the first non-whitespace character in the string to detect whether the input is JSON. The method assumes YAML otherwise.
JsonSerialize(object, Formatting)
Serializes an object to JSON text.
Declaration
public static string JsonSerialize(object value, Formatting format = null)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be serialized. |
| Formatting | format | Output formatting option (defaults to Formatting.None). |
Returns
| Type | Description |
|---|---|
| string | The JSON text. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonSerialize(object, JsonSerializerSettings, Formatting)
Serializes an object to JSON text using custom settings.
Declaration
public static string JsonSerialize(object value, JsonSerializerSettings settings, Formatting format = null)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be serialized. |
| JsonSerializerSettings | settings | The optional settings or |
| Formatting | format | Output formatting option (defaults to Formatting.None). |
Returns
| Type | Description |
|---|---|
| string | The JSON text. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonSerializeToBytes(object, Formatting)
Serializes an object to UTF-8 encoded JSON bytes.
Declaration
public static byte[] JsonSerializeToBytes(object value, Formatting format = null)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be serialized. |
| Formatting | format | Output formatting option (defaults to Formatting.None). |
Returns
| Type | Description |
|---|---|
| byte[] | The UTF-8 encoded JSON bytes. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonSerializeToBytes(object, JsonSerializerSettings, Formatting)
Serializes an object to UTF-8 encoded JSON bytes using custom settings.
Declaration
public static byte[] JsonSerializeToBytes(object value, JsonSerializerSettings settings, Formatting format = null)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be serialized. |
| JsonSerializerSettings | settings | The optional settings or |
| Formatting | format | Output formatting option (defaults to Formatting.None). |
Returns
| Type | Description |
|---|---|
| byte[] | The ITF-8 encoded JSON bytes. |
Remarks
This method uses the default JsonRelaxedSerializerSettings when specific settings are not passed. You may pass JsonStrictSerializerSettings or entirely custom settings.
JsonToYaml(string)
Converts a JSON text to YAML.
Declaration
public static string JsonToYaml(string jsonText)
Parameters
| Type | Name | Description |
|---|---|---|
| string | jsonText | The JSON text. |
Returns
| Type | Description |
|---|---|
| string | The equivalent YAML text. |
Remarks
note
Property names are always converted to lowercase when converting to YAML.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
LogDebug(Exception)
Appends exception information to the file at DebugLogPath. This is intended for low-level debugging when normal logging via TelemetryHub isn't suitable.
Declaration
public static void LogDebug(Exception e)
Parameters
| Type | Name | Description |
|---|---|---|
| Exception | e | The exception. |
LogDebug(string)
Appends a line of text to the file at DebugLogPath. This is intended for low-level debugging when normal logging via TelemetryHub isn't suitable (i.e. when debugging logging code or application initialization code running before normal logging is configured.
Declaration
public static void LogDebug(string line = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | line | Optionally specifies the line of text. |
Max(params TimeSpan[])
Determines the maximum TimeSpan value.
Declaration
public static TimeSpan Max(params TimeSpan[] values)
Parameters
| Type | Name | Description |
|---|---|---|
| TimeSpan[] | values | The values to compare. |
Returns
| Type | Description |
|---|---|
| TimeSpan | The minimum of the values passed or Zero when nothing is passed. |
Min(params TimeSpan[])
Determines the minimum TimeSpan value.
Declaration
public static TimeSpan Min(params TimeSpan[] values)
Parameters
| Type | Name | Description |
|---|---|---|
| TimeSpan[] | values | The values to compare. |
Returns
| Type | Description |
|---|---|
| TimeSpan | The minimum of the values passed or Zero when nothing is passed. |
NoAwait(Task)
Do nothing method that is used when you explicitly don't want to
await a task and you don't want to see warning CS4014.
Declaration
public static void NoAwait(Task task)
Parameters
| Type | Name | Description |
|---|---|---|
| Task | task | The task. |
NormalizeExecArgs(params object[])
Normalizes an array of argument objects into a form that can be passed to an invoked process by adding a quotes and escape characters as necessary.
Declaration
public static string NormalizeExecArgs(params object[] args)
Parameters
| Type | Name | Description |
|---|---|---|
| object[] | args | The arguments. |
Returns
| Type | Description |
|---|---|
| string | The formatted argument string. |
Remarks
note
null and empty arguments are ignored.
NullableEquals<T>(T?, T?)
Determines whether two nullable values are equal.
Declaration
public static bool NullableEquals<T>(T? v1, T? v2) where T : struct
Parameters
| Type | Name | Description |
|---|---|---|
| T? | v1 | Value #1. |
| T? | v2 | Value #2. |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| T | The base value type. |
OpenBrowser(string)
Launches the default browser to display the specified URI.
Declaration
public static void OpenBrowser(string uri)
Parameters
| Type | Name | Description |
|---|---|---|
| string | uri | The target URI. |
OpenEditor(string)
Launches the platform text editor to create or edit a file.
Declaration
public static void OpenEditor(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file path. |
Remarks
This method will launch the editor specified in the EDITOR environment variable otherwise it will launch NotePad on Windows and Vim on Linux and OS/X. EDITOR should be set to the command line used to launch the editor with special $FILE parameter. This will be replaced with the path to the file being edited.
note
We'll simply append the file path if $FILE isn't found in the EDITOR environment variable.
This method will block until the editor is closed.
note
For unit testing, you may set OpenEditorHandler to an action that will simulate editing the file. This action will be called instead of actually opening an editor when set.
OpenStandardInput()
Opens the current process standard inout stream.
Declaration
public static Stream OpenStandardInput()
Returns
| Type | Description |
|---|---|
| Stream | The open Stream. |
Remarks
note
This method integrates with ProgramRunner such that program executions simulated by calls to ExecuteWithInput(ProgramEntrypoint, string, params string[]) or ExecuteWithInput(ProgramEntrypoint, byte[], params string[]) can read the simulated input.
Should generally call this instead of calling OpenStandardInput() directly.
PackageReferenceToNeonCommonIsRequired()
This method may be called to ensure that the Neon.Common assembly is required at compile in a project that doesn't reference Neon.Common. The method does nothing.
note
A call to this is currently included by Neon.ModelGen to ensure that the enclosing project references Neon.Common.
Declaration
public static void PackageReferenceToNeonCommonIsRequired()
ParseBool(string)
Parses common boolean literals.
Declaration
public static bool ParseBool(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string being parsed. |
Returns
| Type | Description |
|---|---|
| bool | The parsed output. |
Remarks
This method recognizes the following case insensitive literals:
false |
0 off no disabled false |
true |
1 on yes enabled true |
Exceptions
| Type | Condition |
|---|---|
| FormatException | Thrown if the value is not valid. |
ParseCsv(string)
Parses a CSV encoded string into its component fields.
Declaration
public static string[] ParseCsv(string value)
Parameters
| Type | Name | Description |
|---|---|---|
| string | value | The encoded CSV string. |
Returns
| Type | Description |
|---|---|
| string[] | The decoded fields. |
Exceptions
| Type | Condition |
|---|---|
| FormatException | Thrown if the CSV file format is not valid. |
ParseEnum<TEnum>(string, TEnum?)
Type-safe enum parser that also honors any EnumMemberAttribute
decorating the enumeration values. This is case insensitive.
Declaration
public static TEnum ParseEnum<TEnum>(string input, TEnum? defaultValue = null) where TEnum : struct, Enum
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
| TEnum? | defaultValue | Optionally specifies the value to be returned if the input cannot be parsed instead of throwing an exception. |
Returns
| Type | Description |
|---|---|
| TEnum | The parsed value. |
Type Parameters
| Name | Description |
|---|---|
| TEnum | The enumeration type. |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
ParseNullableBool(string)
Parses a nullable bool.
Declaration
public static bool? ParseNullableBool(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string being parsed. |
Returns
| Type | Description |
|---|---|
| bool? |
|
Exceptions
| Type | Condition |
|---|---|
| FormatException | Thrown for invalid input strings. |
PartitionCount(int, int)
Computes the int number of partitions that would be required to divide a set of items where the number of items in each partition is limited.
Declaration
public static int PartitionCount(int itemCount, int partitionSize)
Parameters
| Type | Name | Description |
|---|---|---|
| int | itemCount | The number of items to be partitioned. |
| int | partitionSize | The maximim number of items in any partition. |
Returns
| Type | Description |
|---|---|
| int | The number of partitions required. |
PartitionCount(long, long)
Computes the long number of partitions that would be required to divide a set of items where the number of items in each partition is limited.
Declaration
public static long PartitionCount(long itemCount, long partitionSize)
Parameters
| Type | Name | Description |
|---|---|---|
| long | itemCount | The number of items to be partitioned. |
| long | partitionSize | The maximim number of items in any partition. |
Returns
| Type | Description |
|---|---|
| long | The number of partitions required. |
PartitionCount(uint, uint)
Computes the uint number of partitions that would be required to divide a set of items where the number of items in each partition is limited.
Declaration
public static uint PartitionCount(uint itemCount, uint partitionSize)
Parameters
| Type | Name | Description |
|---|---|---|
| uint | itemCount | The number of items to be partitioned. |
| uint | partitionSize | The maximim number of items in any partition. |
Returns
| Type | Description |
|---|---|
| uint | The number of partitions required. |
PartitionCount(ulong, ulong)
Computes the ulong number of partitions that would be required to divide a set of items where the number of items in each partition is limited.
Declaration
public static ulong PartitionCount(ulong itemCount, ulong partitionSize)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | itemCount | The number of items to be partitioned. |
| ulong | partitionSize | The maximim number of items in any partition. |
Returns
| Type | Description |
|---|---|
| ulong | The number of partitions required. |
PseudoRandomBytes(int)
Returns the specified number of pseudo random bytes.
Declaration
public static byte[] PseudoRandomBytes(int count)
Parameters
| Type | Name | Description |
|---|---|---|
| int | count | The requested number of bytes. |
Returns
| Type | Description |
|---|---|
| byte[] | The random bytes. |
PseudoRandomDouble()
Returns a double pseudo random number between 0.0 and +1.0
Declaration
public static double PseudoRandomDouble()
Returns
| Type | Description |
|---|---|
| double | The random number. |
PseudoRandomDouble(double)
Returns a double pseudo random number between 0.0 and the specified limit.
Declaration
public static double PseudoRandomDouble(double limit)
Parameters
| Type | Name | Description |
|---|---|---|
| double | limit | The limit. |
Returns
| Type | Description |
|---|---|
| double | The random number. |
PseudoRandomIndex(int)
Returns a random index into a sequence whose length is specified.
Declaration
public static int PseudoRandomIndex(int length)
Parameters
| Type | Name | Description |
|---|---|---|
| int | length | The sequence length. |
Returns
| Type | Description |
|---|---|
| int | The random index. |
Exceptions
| Type | Condition |
|---|---|
| IndexOutOfRangeException | Thrown if length is <= 0. |
PseudoRandomInt()
Returns an integer pseudo random number.
Declaration
public static int PseudoRandomInt()
Returns
| Type | Description |
|---|---|
| int | The random integer. |
PseudoRandomInt(int)
Returns a pseudo random number in the range of 0..limit-1.
Declaration
public static int PseudoRandomInt(int limit)
Parameters
| Type | Name | Description |
|---|---|---|
| int | limit | The value returned will not exceed one less than this value. |
Returns
| Type | Description |
|---|---|
| int | The random number. |
PseudoRandomTimespan(TimeSpan)
Returns a random TimeSpan between zero and a specified maximum.
Declaration
public static TimeSpan PseudoRandomTimespan(TimeSpan maxInterval)
Parameters
| Type | Name | Description |
|---|---|---|
| TimeSpan | maxInterval | The maximum interval. |
Returns
| Type | Description |
|---|---|
| TimeSpan | The random timespan. |
Remarks
This method is useful for situations where its desirable to have some variation in a delay before performing an activity like retrying an operation or performing a background task.
PseudoRandomTimespan(TimeSpan, double)
Returns a TimeSpan between the specified base interval plus a random period of the specified fraction of the value.
Declaration
public static TimeSpan PseudoRandomTimespan(TimeSpan baseInterval, double fraction)
Parameters
| Type | Name | Description |
|---|---|---|
| TimeSpan | baseInterval | The base interval. |
| double | fraction | The fractional multiplier for the random component. |
Returns
| Type | Description |
|---|---|
| TimeSpan | The random timespan. |
Remarks
The value returned is at least as large as baseInterval with an
added random fractional interval if fraction is positive or the value
returned may be less than baseInterval for a negative fraction.
This is computed via:
baseInterval + Helper.RandTimespan(TimeSpan.FromSeconds(baseInterval.TotalSeconds * fraction));
This method is useful for situations where its desirable to have some variation in a delay before performing an activity like retrying an operation or performing a background task.
PseudoRandomTimespan(TimeSpan, TimeSpan)
Returns a random TimeSpan value between the min/max values specified.
Declaration
public static TimeSpan PseudoRandomTimespan(TimeSpan minInterval, TimeSpan maxInterval)
Parameters
| Type | Name | Description |
|---|---|---|
| TimeSpan | minInterval | The minimum interval. |
| TimeSpan | maxInterval | The maximum interval. |
Returns
| Type | Description |
|---|---|
| TimeSpan | The randomized time span. |
ReadConsolePassword(string)
Reads a password from the Console terminated by Enter without echoing the typed characters.
Declaration
public static string ReadConsolePassword(string prompt = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | prompt | Optional prompt. |
Returns
| Type | Description |
|---|---|
| string | The password entered. |
ReadStandardInputBytes()
Reads the standard input file to the end and returns the result as bytes.
Declaration
public static byte[] ReadStandardInputBytes()
Returns
| Type | Description |
|---|---|
| byte[] | The standard input. |
ReadStandardInputText()
Reads the standard input file to the end and returns the result as a string.
Declaration
public static string ReadStandardInputText()
Returns
| Type | Description |
|---|---|
| string | The standard input. |
RegisterMisspelledUtf8Provider()
Ensures that a special UTF-8 text encoding provider misnamed as utf8 (without the dash) is registered. This is required sometimes because certain REST APIs may return incorrect charset values.
Declaration
public static void RegisterMisspelledUtf8Provider()
SequenceEqual<T>(IEnumerable<T>, IEnumerable<T>)
Compares two null or non-null enumerable sequences for equality.
Declaration
public static bool SequenceEqual<T>(IEnumerable<T> sequence1, IEnumerable<T> sequence2)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | sequence1 | The first list or |
| IEnumerable<T> | sequence2 | The second list or |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| T | The enumerable item type. |
Remarks
note
This method is capable of comparing null arguments and also
uses Equals(object, object) to compare individual
elements.
SequenceEqual<T>(IList<T>, IList<T>)
Compares two null or non-null lists for equality.
Declaration
public static bool SequenceEqual<T>(IList<T> list1, IList<T> list2)
Parameters
| Type | Name | Description |
|---|---|---|
| IList<T> | list1 | The first list or |
| IList<T> | list2 | The second list or |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| T | The enumerable item type. |
Remarks
note
This method is capable of comparing null arguments and also
uses Equals(object, object) to compare
individual elements.
SetUserHomeFolder(string)
Sets the appropriate variables for the operating system to change the current user's home folder to the specified path.
Declaration
public static void SetUserHomeFolder(string folder)
Parameters
| Type | Name | Description |
|---|---|---|
| string | folder | Specifies the new home folder. |
StartProcess(Assembly, string)
Starts a process for an Assembly by calling the assembly's main() entry point method.
Declaration
public static Process StartProcess(Assembly assembly, string args)
Parameters
| Type | Name | Description |
|---|---|---|
| Assembly | assembly | The assembly to be started. |
| string | args | The command line arguments (or |
Returns
| Type | Description |
|---|---|
| Process | The process started. |
Remarks
note
This method works only for executable assemblies with an appropriate main entry point that reside on the local file system.
StartThread(Action, int)
Starts a new Thread to perform an action.
Declaration
public static Thread StartThread(Action action, int maxStackSize = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| Action | action | The action to be performed. |
| int | maxStackSize |
Optionally specifies the maximum stack size, in bytes, to be used by the thread, or
0 to use the default maximum stack size specified in the header for the executable.
Important for partially trusted code, This defaults to 0 which generally means the stack size will be limited to 1 MiB for 32-bit applications or 4 MiB for 64-bit applications. |
Returns
| Type | Description |
|---|---|
| Thread | The Thread. |
StartThread(Action<object>, object, int)
Starts a new Thread to perform a parameterized action with an object parameter.
Declaration
public static Thread StartThread(Action<object> action, object parameter, int maxStackSize = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| Action<object> | action | The action to be performed. |
| object | parameter | The parameter to be passed to the thread action. |
| int | maxStackSize |
Optionally specifies the maximum stack size, in bytes, to be used by the thread, or
0 to use the default maximum stack size specified in the header for the executable.
Important for partially trusted code, This defaults to 0 which generally means the stack size will be limited to 1 MiB for 32-bit applications or 4 MiB for 64-bit applications. |
Returns
| Type | Description |
|---|---|
| Thread | The Thread. |
StartTypedThread<TParam>(Action<TParam>, TParam, int)
Starts a new Thread to perform a parameterized action with a typed parameter.
Declaration
public static Thread StartTypedThread<TParam>(Action<TParam> action, TParam parameter, int maxStackSize = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| Action<TParam> | action | The action to be performed. |
| TParam | parameter | The parameter to be passed to the thread action. |
| int | maxStackSize |
Optionally specifies the maximum stack size, in bytes, to be used by the thread, or
0 to use the default maximum stack size specified in the header for the executable.
Important for partially trusted code, This defaults to 0 which generally means the stack size will be limited to 1 MiB for 32-bit applications or 4 MiB for 64-bit applications. |
Returns
| Type | Description |
|---|---|
| Thread | The Thread. |
Type Parameters
| Name | Description |
|---|---|
| TParam | Identifies the type of the thread action parameter. |
StripAnsibleWarnings(string)
HACK: This method attempts to trim warnings generated by Ansible because it writes these warnings to STDOUT instead of STDERR. This is super fragile.
Declaration
public static string StripAnsibleWarnings(string text)
Parameters
| Type | Name | Description |
|---|---|---|
| string | text | The text to be adjusted. |
Returns
| Type | Description |
|---|---|
| string | The adjusted text. |
StripFileScheme(string)
Removes a file:// scheme from the path URI if this is scheme is present. The result will be a valid file system path.
Declaration
public static string StripFileScheme(string path)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The path/URI to be converted. |
Returns
| Type | Description |
|---|---|
| string | The file system path. |
Remarks
note
This method behaves slightly differently when running on Windows and when running on Unix/Linux. On Windows, file URIs are absolute file paths of the form:
FILE:///C:/myfolder/myfile
To convert this into a valid file system path this method strips the file:// scheme and the following forward slash. On Unix/Linux, file URIs will have the form:
FILE:///myfolder/myfile
In this case, the forward shlash following the file:// scheme is part of the file system path and will not be removed.
ToBase64(string, Encoding)
Converts the string passed into base64 string.
Declaration
public static string ToBase64(string value, Encoding encoding = null)
Parameters
| Type | Name | Description |
|---|---|---|
| string | value | The plaintext string to be encoded (cannot be |
| Encoding | encoding | Optionally specifies the encoding to use to convert the input to bytes before base64 encoding it. This defaults to UTF8. |
Returns
| Type | Description |
|---|---|
| string | The converted base-64 string. |
ToBoolString(bool)
Renders a bool value as either true or false
(lowercase).
Declaration
public static string ToBoolString(bool value)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | value | The value. |
Returns
| Type | Description |
|---|---|
| string | true or false, |
ToHex(byte, bool)
Converts a single byte into its hexidecimal equivalent.
Declaration
public static string ToHex(byte value, bool uppercase = false)
Parameters
| Type | Name | Description |
|---|---|---|
| byte | value | The input byte. |
| bool | uppercase | Optionally return the hex value as uppercase. |
Returns
| Type | Description |
|---|---|
| string | The hex string. |
ToHex(byte[], bool)
Converts the byte buffer passed into a hex encoded string.
Declaration
public static string ToHex(byte[] buf, bool uppercase = false)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | buf | The buffer |
| bool | uppercase | Optionally renders the hex digits in uppercase. |
Returns
| Type | Description |
|---|---|
| string | The hex encoded string. |
ToLinuxLineEndings(string)
Converts Windows line endings (CR-LF) to Linux/Unix line endings (LF).
Declaration
public static string ToLinuxLineEndings(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string or |
Returns
| Type | Description |
|---|---|
| string | The input string with converted line endings. |
TryParseBool(string, out bool)
Attempts to parse a boolean from common literals.
Declaration
public static bool TryParseBool(string input, out bool value)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string being parsed. |
| bool | value | Returns as the parsed value on success. |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
This method recognizes the following case insensitive literals:
false |
0 off no disabled false |
true |
1 on yes enabled true |
TryParseEnum(Type, string, out object)
enum parser that also honors any EnumMemberAttribute
decorating the enumeration values. This is case insensitive.
Declaration
public static bool TryParseEnum(Type type, string input, out object output)
Parameters
| Type | Name | Description |
|---|---|---|
| Type | type | The enumeration type. |
| string | input | The input string. |
| object | output | Returns as the parsed value. |
Returns
| Type | Description |
|---|---|
| bool |
|
TryParseEnum<TEnum>(string, out TEnum)
enum parser that also honors any EnumMemberAttribute
decorating the enumeration values. This is case insensitive.
Declaration
public static bool TryParseEnum<TEnum>(string input, out TEnum output)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
| TEnum | output | Returns as the parsed value. |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| TEnum | Specifies the enumeration type. |
TryParseHex(string, out byte[])
Attempts to parse a hex string into a byte array.
Declaration
public static bool TryParseHex(string s, out byte[] output)
Parameters
| Type | Name | Description |
|---|---|---|
| string | s | The string to convert from hex. |
| byte[] | output | Returns as the parsed byte array on success. |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
note
The method ignores whitespace characters (SP,CR,LF, and TAB) in the string so that HEX strings copied directly from typical hex dump outputs can be passed directly with minimal editing.
TryParseHex(string, out int)
Attempts to parse a hex encoded string into an integer.
Declaration
public static bool TryParseHex(string input, out int value)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
| int | value | The parsed integer. |
Returns
| Type | Description |
|---|---|
| bool |
|
TryParseNullableBool(string, out bool?)
Attempts to parse a nullable bool. null, empty or input == "null"
will return null. Otherwise we'll expect either "true" or "false" or
one of the other literals supported by ParseBool(string).
Declaration
public static bool TryParseNullableBool(string input, out bool? value)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string being parsed. |
| bool? | value | Returns as the parsed value. |
Returns
| Type | Description |
|---|---|
| bool |
|
TryParse<TEnum>(string, out TEnum)
Type-safe enum parser that also honors any EnumMemberAttribute
decorating the enumeration values. This is case insensitive.
Declaration
public static bool TryParse<TEnum>(string input, out TEnum output) where TEnum : struct, Enum
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
| TEnum | output | Returns as the parsed value. |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| TEnum | The enumeration type. |
UnixEpochMillisecondsToDateTimeUtc(long)
Converts the number of milliseconds from the Unix Epoch (1/1/1970 12:00:00am) into a UTC cref="DateTime"/> (UTC).
Declaration
public static DateTime UnixEpochMillisecondsToDateTimeUtc(long milliseconds)
Parameters
| Type | Name | Description |
|---|---|---|
| long | milliseconds |
Returns
| Type | Description |
|---|---|
| DateTime | The converted DateTime. |
UnixEpochNanosecondsToDateTimeUtc(long)
Converts the number of nanoseconds from the Unix Epoch (1/1/1970 12:00:00am) into a UTC cref="DateTime"/> (UTC).
Declaration
public static DateTime UnixEpochNanosecondsToDateTimeUtc(long nanoseconds)
Parameters
| Type | Name | Description |
|---|---|---|
| long | nanoseconds |
Returns
| Type | Description |
|---|---|
| DateTime | The converted DateTime. |
UrlTokenDecode(string)
Decodes a string encoded by UrlTokenEncode(byte[]) back into a byte array.
Declaration
public static byte[] UrlTokenDecode(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The input string. |
Returns
| Type | Description |
|---|---|
| byte[] | The decoded bytes. |
Exceptions
| Type | Condition |
|---|---|
| NullReferenceException | Thrown if |
UrlTokenEncode(byte[])
Encodes a byte array into a form suitable for using as a URI path segment or query parameter.
Declaration
public static string UrlTokenEncode(byte[] input)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | input | The byte array. |
Returns
| Type | Description |
|---|---|
| string | The encoded string. |
Exceptions
| Type | Condition |
|---|---|
| NullReferenceException | Thrown if |
WaitAll(IEnumerable<Thread>)
Waits for all of the threads passed to complete. This method does nothing
when threads is null or empty. Also and null
threads passed will be ignored.
Declaration
public static void WaitAll(IEnumerable<Thread> threads)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<Thread> | threads | The threads being waited on. |
WaitAllAsync(IEnumerable<Task>)
Asynchronously waits for all of the Tasks passed to complete.
Declaration
public static Task WaitAllAsync(IEnumerable<Task> tasks)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<Task> | tasks | The tasks to wait on. |
Returns
| Type | Description |
|---|---|
| Task | The tracking Task. |
WaitAllAsync(IEnumerable<Task>, TimeSpan?, string, CancellationToken)
Asynchronously waits for all of the Tasks passed to complete.
Declaration
public static Task WaitAllAsync(IEnumerable<Task> tasks, TimeSpan? timeout = null, string timeoutMessage = null, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<Task> | tasks | Specifies the tasks being waited on. |
| TimeSpan? | timeout | Optionally specifies a timeout. |
| string | timeoutMessage | Optionally specifies a message to be included in any TimeoutException thrown to help the what failed. |
| CancellationToken | cancellationToken | Optionally a cancellation token. |
Returns
| Type | Description |
|---|---|
| Task | The tracking Task. |
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the |
WaitAllAsync(params Task[])
Asynchronously waits for all of the Tasks passed to complete.
Declaration
public static Task WaitAllAsync(params Task[] tasks)
Parameters
| Type | Name | Description |
|---|---|---|
| Task[] | tasks | The tasks to wait on. |
Returns
| Type | Description |
|---|---|
| Task | The tracking Task. |
WaitFor(Func<bool>, TimeSpan, TimeSpan?, string, CancellationToken)
Waits for a boolean function to return true.
Declaration
public static void WaitFor(Func<bool> predicate, TimeSpan timeout, TimeSpan? pollInterval = null, string timeoutMessage = null, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| Func<bool> | predicate | The boolean predicate. |
| TimeSpan | timeout | Optionally specifies the maximum time to wait. |
| TimeSpan? | pollInterval | Optionally specifies time to wait between each predicate call or |
| string | timeoutMessage | Optionally overrides the TimeoutException message. |
| CancellationToken | cancellationToken | Optionally specifies a cancellation token. |
Remarks
This method periodically calls predicate until it
returns true or
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the never returned |
WaitForAsync(Func<Task<bool>>, TimeSpan, TimeSpan?, string, CancellationToken)
Asynchronously waits for a boolean function to return true.
Declaration
public static Task WaitForAsync(Func<Task<bool>> predicate, TimeSpan timeout, TimeSpan? pollInterval = null, string timeoutMessage = null, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| Func<Task<bool>> | predicate | The boolean predicate. |
| TimeSpan | timeout | Optionally specifies the maximum time to wait. |
| TimeSpan? | pollInterval | Optionally specifies time to wait between each predicate call or |
| string | timeoutMessage | Optionally overrides the TimeoutException message. |
| CancellationToken | cancellationToken | Optionally specifies a CancellationToken. |
Returns
| Type | Description |
|---|---|
| Task | The tracking Task. |
Remarks
This method periodically calls predicate until it
returns true or
Exceptions
| Type | Condition |
|---|---|
| TimeoutException | Thrown if the never returned |
YamlDeserializeViaJson<T>(string, bool)
Deserializes YAML to an object via JSON.NET. This allows the use of Newtonsoft.Json.JsonConverters to deserialize complex types. Strict requires mapping of input properties in the target type.
Declaration
public static T YamlDeserializeViaJson<T>(string yaml, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| string | yaml | The YAML text. |
| bool | strict | Optionally require that all input properties map to route properties. |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
YamlDeserialize<T>(string, bool)
Deserializes YAML text to an object, optionally requiring strict mapping of input properties to the target type.
note
Property names are expected to be lowercase.
Declaration
public static T YamlDeserialize<T>(string yaml, bool strict = false)
Parameters
| Type | Name | Description |
|---|---|---|
| string | yaml | The YAML text. |
| bool | strict | Optionally require that all input properties map to route properties. |
Returns
| Type | Description |
|---|---|
| T | The parsed |
Type Parameters
| Name | Description |
|---|---|
| T | The desired output type. |
YamlSerialize(object)
Serializes an object to YAML.
note
Property names are always converted to lowercase when serializing to YAML.
Declaration
public static string YamlSerialize(object value)
Parameters
| Type | Name | Description |
|---|---|---|
| object | value | The value to be serialized. |
Returns
| Type | Description |
|---|---|
| string | The YAML text. |