Show / Hide Table of Contents

Class MiscUtils

Provides a collection of frequently-used extension methods

Inheritance
System.Object
MiscUtils
Inherited Members
System.Object.Equals(System.Object)
System.Object.Equals(System.Object, System.Object)
System.Object.GetHashCode()
System.Object.GetType()
System.Object.MemberwiseClone()
System.Object.ReferenceEquals(System.Object, System.Object)
System.Object.ToString()
Namespace: NFX
Assembly: NFX.dll
Syntax
public static class MiscUtils

Fields

UNIX_EPOCH_START_DATE

Declaration
public static readonly DateTime UNIX_EPOCH_START_DATE
Field Value
Type Description
System.DateTime

WIN_UNIX_LINE_BRAKES

Declaration
public static readonly string[] WIN_UNIX_LINE_BRAKES
Field Value
Type Description
System.String[]

Methods

AllFileNames(String, Boolean)

Walks all file names in a directory

Declaration
public static IEnumerable<string> AllFileNames(this string fromFolder, bool recurse)
Parameters
Type Name Description
System.String fromFolder
System.Boolean recurse
Returns
Type Description
System.Collections.Generic.IEnumerable<System.String>

AllFileNamesThatMatch(String, String, Boolean)

Walks all file names that match the pattern in a directory

Declaration
public static IEnumerable<string> AllFileNamesThatMatch(this string fromFolder, string pattern, bool recurse)
Parameters
Type Name Description
System.String fromFolder
System.String pattern
System.Boolean recurse
Returns
Type Description
System.Collections.Generic.IEnumerable<System.String>

AppendFormatLine(StringBuilder, String, Object)

Appends the string followed by new line and returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument.

Declaration
public static StringBuilder AppendFormatLine(this StringBuilder builder, string str, object arg0)
Parameters
Type Name Description
System.Text.StringBuilder builder
System.String str
System.Object arg0
Returns
Type Description
System.Text.StringBuilder

AppendFormatLine(StringBuilder, String, Object, Object)

Appends the string followed by new line and returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument.

Declaration
public static StringBuilder AppendFormatLine(this StringBuilder builder, string str, object arg0, object arg1)
Parameters
Type Name Description
System.Text.StringBuilder builder
System.String str
System.Object arg0
System.Object arg1
Returns
Type Description
System.Text.StringBuilder

AppendFormatLine(StringBuilder, String, Object, Object, Object)

Appends the string followed by new line and returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument.

Declaration
public static StringBuilder AppendFormatLine(this StringBuilder builder, string str, object arg0, object arg1, object arg2)
Parameters
Type Name Description
System.Text.StringBuilder builder
System.String str
System.Object arg0
System.Object arg1
System.Object arg2
Returns
Type Description
System.Text.StringBuilder

AppendFormatLine(StringBuilder, String, Object[])

Appends the string followed by new line and returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument.

Declaration
public static StringBuilder AppendFormatLine(this StringBuilder builder, string str, params object[] args)
Parameters
Type Name Description
System.Text.StringBuilder builder
System.String str
System.Object[] args
Returns
Type Description
System.Text.StringBuilder

ApproximateTimeDistance(DateTime, DateTime)

Retruns an approximate time distance (timespan) between two dates

Declaration
public static string ApproximateTimeDistance(this DateTime fromDate, DateTime toDate)
Parameters
Type Name Description
System.DateTime fromDate
System.DateTime toDate
Returns
Type Description
System.String

Args(String, Object[])

Shortcut helper for string.Format(tpl, params object[] args)

Declaration
public static string Args(this string tpl, params object[] args)
Parameters
Type Name Description
System.String tpl
System.Object[] args
Returns
Type Description
System.String

ArgsTpl(String, Object)

Interprets template of the form: Some text {@value_name@:C} by replacing with property/field values. Note: this function does not recognize escapes for simplicity (as escapes can be replaced by regular strings instead)

Declaration
public static string ArgsTpl(this string tpl, object args)
Parameters
Type Name Description
System.String tpl
System.Object args
Returns
Type Description
System.String

ArgsTpl(String, Object, out Boolean)

Interprets template of the form: Some text {@value_name@:C} by replacing with property/field values. Note: this function does not recognize escapes for simplicity (as escapes can be replaced by regular strings instead). Matched is set to true if at least one property match was made

Declaration
public static string ArgsTpl(this string tpl, object args, out bool matched)
Parameters
Type Name Description
System.String tpl
System.Object args
System.Boolean matched
Returns
Type Description
System.String

Burmatographize(String, Boolean)

Swaps string letters that "obfuscates" string- usefull for generation of keys from strings that have to become non-obvious to user. This function does not offer any real protection (as it is easy to decipher the original value), just visual. The name comes from non-existing science "Burmatography" used in "Neznaika" kids books

Declaration
public static string Burmatographize(this string src, bool rtl = false)
Parameters
Type Name Description
System.String src
System.Boolean rtl
Returns
Type Description
System.String

CapitalizeFirstChar(String)

Capitalizes first character of string

Declaration
public static string CapitalizeFirstChar(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.String

Default(String, String)

Defaults string if it is null or whitespace

Declaration
public static string Default(this string str, string val = "")
Parameters
Type Name Description
System.String str
System.String val
Returns
Type Description
System.String

DisplayNameWithExpandedGenericArgs(Type)

Returns the the name of the type with expanded generic argument names. This helper is useful for printing class names to logs/messages. List'1[System.Object] -> List<Object>

Declaration
public static string DisplayNameWithExpandedGenericArgs(this Type type)
Parameters
Type Name Description
System.Type type
Returns
Type Description
System.String

EntryExeName(Boolean)

Returns the name of entry point executable file optionaly with its path

Declaration
public static string EntryExeName(bool withPath = true)
Parameters
Type Name Description
System.Boolean withPath
Returns
Type Description
System.String

EqualsIgnoreCase(String, String)

Helper function that performs case-insensitive comparison between strings using invariant comparison. Either lhs and rhs can be null. Use this in conjunction with GetHashCodeIgnoreCase

Declaration
public static bool EqualsIgnoreCase(this string lhs, string rhs)
Parameters
Type Name Description
System.String lhs
System.String rhs
Returns
Type Description
System.Boolean

EqualsOrdIgnoreCase(String, String)

Helper function that performs case-insensitive comparison between strings using ordinal comparison. Either lhs and rhs can be null. Use this in conjunction with GetHashCodeOrdIgnoreCase

Declaration
public static bool EqualsOrdIgnoreCase(this string lhs, string rhs)
Parameters
Type Name Description
System.String lhs
System.String rhs
Returns
Type Description
System.Boolean

EqualsOrdSenseCase(String, String)

Helper function that performs case-insensitive comparison between strings using ordinal comparison. Either lhs and rhs can be null. Use this in conjunction with GetHashCodeOrdSenseCase

Declaration
public static bool EqualsOrdSenseCase(this string lhs, string rhs)
Parameters
Type Name Description
System.String lhs
System.String rhs
Returns
Type Description
System.Boolean

EqualsSenseCase(String, String)

Helper function that performs comparison between strings using invariant comparison. Either lhs and rhs can be null. Use this in conjunction with GetHashCodeSenseCase

Declaration
public static bool EqualsSenseCase(this string lhs, string rhs)
Parameters
Type Name Description
System.String lhs
System.String rhs
Returns
Type Description
System.Boolean

EscapeJSLiteral(String)

Escapes JS literal, replacing / \ \r \n " ' < > & chars with their hex codes

Declaration
public static string EscapeJSLiteral(this string value)
Parameters
Type Name Description
System.String value
Returns
Type Description
System.String

EvaluateVars(String, IEnvironmentVariableResolver, IMacroRunner)

Evaluates variables in a context of optional variable resolver and macro runner

Declaration
public static string EvaluateVars(this string line, IEnvironmentVariableResolver envResolver = null, IMacroRunner macroRunner = null)
Parameters
Type Name Description
System.String line
IEnvironmentVariableResolver envResolver
IMacroRunner macroRunner
Returns
Type Description
System.String

EvaluateVarsInConfigScope(String, Configuration)

Evaluates variables in a context of optional configuration supplied as config object

Declaration
public static string EvaluateVarsInConfigScope(this string line, Configuration scopeConfig = null)
Parameters
Type Name Description
System.String line
Configuration scopeConfig
Returns
Type Description
System.String

EvaluateVarsInDictionaryScope(String, IDictionary<String, Object>, IEnvironmentVariableResolver, IMacroRunner)

Evaluates variables in a context of optional configuration supplied as dictionary which is converted to attributes

Declaration
public static string EvaluateVarsInDictionaryScope(this string line, IDictionary<string, object> dict = null, IEnvironmentVariableResolver envResolver = null, IMacroRunner macroRunner = null)
Parameters
Type Name Description
System.String line
System.Collections.Generic.IDictionary<System.String, System.Object> dict
IEnvironmentVariableResolver envResolver
IMacroRunner macroRunner
Returns
Type Description
System.String

EvaluateVarsInXMLConfigScope(String, String, IEnvironmentVariableResolver, IMacroRunner)

Evaluates variables in a context of optional configuration supplied in XML format

Declaration
public static string EvaluateVarsInXMLConfigScope(this string line, string xmlScope = null, IEnvironmentVariableResolver envResolver = null, IMacroRunner macroRunner = null)
Parameters
Type Name Description
System.String line
System.String xmlScope
IEnvironmentVariableResolver envResolver
IMacroRunner macroRunner
Returns
Type Description
System.String

FromMicrosecondsSinceUnixEpochStart(Int64)

Gets UTC DateTime from number of microseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromMicrosecondsSinceUnixEpochStart(this long when)
Parameters
Type Name Description
System.Int64 when
Returns
Type Description
System.DateTime

FromMicrosecondsSinceUnixEpochStart(UInt64)

Gets UTC DateTime from number of microseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromMicrosecondsSinceUnixEpochStart(this ulong when)
Parameters
Type Name Description
System.UInt64 when
Returns
Type Description
System.DateTime

FromMillisecondsSinceUnixEpochStart(Int64)

Gets UTC DateTime from number of milliseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromMillisecondsSinceUnixEpochStart(this long when)
Parameters
Type Name Description
System.Int64 when
Returns
Type Description
System.DateTime

FromMillisecondsSinceUnixEpochStart(UInt64)

Gets UTC DateTime from number of milliseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromMillisecondsSinceUnixEpochStart(this ulong when)
Parameters
Type Name Description
System.UInt64 when
Returns
Type Description
System.DateTime

FromSecondsSinceUnixEpochStart(Int64)

Gets UTC DateTime from number of seconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromSecondsSinceUnixEpochStart(this long when)
Parameters
Type Name Description
System.Int64 when
Returns
Type Description
System.DateTime

FromSecondsSinceUnixEpochStart(UInt64)

Gets UTC DateTime from number of seconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static DateTime FromSecondsSinceUnixEpochStart(this ulong when)
Parameters
Type Name Description
System.UInt64 when
Returns
Type Description
System.DateTime

FromUTF8Bytes(Byte[], Int32, Int32)

Decode string with standart UTF8 decoder

Declaration
public static string FromUTF8Bytes(this byte[] buf, int idx = -1, int cnt = -1)
Parameters
Type Name Description
System.Byte[] buf
System.Int32 idx
System.Int32 cnt
Returns
Type Description
System.String

FullNameWithExpandedGenericArgs(Type, Boolean)

Returns the full name of the type optionally prefixed with verbatim id specifier &apos;@'. The generic arguments ar expanded into their full names i.e. List'1[System.Object] -> System.Collections.Generic.List<System.Object>

Declaration
public static string FullNameWithExpandedGenericArgs(this Type type, bool verbatimPrefix = true)
Parameters
Type Name Description
System.Type type
System.Boolean verbatimPrefix
Returns
Type Description
System.String

FullNestedTypeName(Type, Boolean)

Returns full name of the nested type, for example: System.Namespace.Type+Sub -> Type.Sub

Declaration
public static string FullNestedTypeName(this Type type, bool verbatimPrefix = true)
Parameters
Type Name Description
System.Type type
System.Boolean verbatimPrefix
Returns
Type Description
System.String

GetHashCodeIgnoreCase(String)

Helper function that performs case-insensitive GetHashcode for string using invariant comparison. Use this in conjunction with EqualsIgnoreCase

Declaration
public static int GetHashCodeIgnoreCase(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Int32

GetHashCodeOrdIgnoreCase(String)

Helper function that performs case-insensitive GetHashcode for string using ordinal comparison. Use this in conjunction with EqualsOrdIgnoreCase

Declaration
public static int GetHashCodeOrdIgnoreCase(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Int32

GetHashCodeOrdSenseCase(String)

Helper function that performs case-insensitive GetHashcode for string using ordinal comparison. Use this in conjunction with EqualsOrdSenseCase

Declaration
public static int GetHashCodeOrdSenseCase(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Int32

GetHashCodeSenseCase(String)

Helper function that performs GetHashcode for string using invariant comparison. Use this in conjunction with EqualsSenseCase

Declaration
public static int GetHashCodeSenseCase(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Int32

IPStringToIPEndPoint(String)

Converts string of format "xx.xx.xx.xx:nnnn" into IPEndPoint. DNS names are NOT supported

Declaration
[Obsolete]
public static IPEndPoint IPStringToIPEndPoint(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Net.IPEndPoint

IsComponentDesignerHosted(Component)

Determines if component is being used within designer

Declaration
public static bool IsComponentDesignerHosted(Component cmp)
Parameters
Type Name Description
System.ComponentModel.Component cmp
Returns
Type Description
System.Boolean

IsNotNullOrEmpty(String)

Helper function that calls !string.IsNullOrEmpty()

Declaration
public static bool IsNotNullOrEmpty(this string s)
Parameters
Type Name Description
System.String s
Returns
Type Description
System.Boolean

IsNotNullOrWhiteSpace(String)

Helper function that calls !string.IsNullOrWhiteSpace()

Declaration
public static bool IsNotNullOrWhiteSpace(this string s)
Parameters
Type Name Description
System.String s
Returns
Type Description
System.Boolean

IsNullOrEmpty(String)

Helper function that calls string.IsNullOrEmpty()

Declaration
public static bool IsNullOrEmpty(this string s)
Parameters
Type Name Description
System.String s
Returns
Type Description
System.Boolean

IsNullOrWhiteSpace(String)

Helper function that calls string.IsNullOrWhiteSpace()

Declaration
public static bool IsNullOrWhiteSpace(this string s)
Parameters
Type Name Description
System.String s
Returns
Type Description
System.Boolean

IsTrue(Nullable<Boolean>, Boolean)

Tests bool? for being assigned with true

Declaration
public static bool IsTrue(this bool ? value, bool dflt = false)
Parameters
Type Name Description
System.Nullable<System.Boolean> value
System.Boolean dflt
Returns
Type Description
System.Boolean

IsValidXMLName(String)

Returns true when supplied name can be used for XML node naming (node names, attribute names)

Declaration
public static bool IsValidXMLName(this string name)
Parameters
Type Name Description
System.String name
Returns
Type Description
System.Boolean

NonNull<T>(T, Func<Exception>, String)

Checks the value for null and throws exception if it is. The method is useful for .ctor call chaining to preclude otherwise anonymous NullReferenceException

Declaration
public static T NonNull<T>(this T obj, Func<Exception> error = null, string text = null)where T : class
Parameters
Type Name Description
T obj
System.Func<System.Exception> error
System.String text
Returns
Type Description
T
Type Parameters
Name Description
T

RoundToNextWeekDay(DateTime, DayOfWeek, Boolean)

Round date to next specific week day

Declaration
public static DateTime RoundToNextWeekDay(this DateTime now, DayOfWeek dayOfWeek, bool keepTime = false)
Parameters
Type Name Description
System.DateTime now
System.DayOfWeek dayOfWeek
System.Boolean keepTime
Returns
Type Description
System.DateTime

RoundToWeekDay(DateTime, DayOfWeek, Boolean)

Round date to specific week day

Declaration
public static DateTime RoundToWeekDay(this DateTime now, DayOfWeek dayOfWeek, bool keepTime = false)
Parameters
Type Name Description
System.DateTime now
System.DayOfWeek dayOfWeek
System.Boolean keepTime
Returns
Type Description
System.DateTime

RunAndCompleteProcess(String, String)

Runs specified process and waits for termination returning standard process output. This is a blocking call

Declaration
public static string RunAndCompleteProcess(string name, string args)
Parameters
Type Name Description
System.String name
System.String args
Returns
Type Description
System.String

SplitLines(String)

Splits string into lines using Win or .nix line brakes

Declaration
public static string[] SplitLines(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.String[]

StripSimpleHtml(String)

Strip simple html from string

Declaration
public static string StripSimpleHtml(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.String

TakeFirstChars(String, Int32, String)

Takes first X chars from a string. If string is null returns null. If string does not have enough the function returns what the string has

Declaration
public static string TakeFirstChars(this string str, int count, string ellipsis = null)
Parameters
Type Name Description
System.String str
System.Int32 count
System.String ellipsis
Returns
Type Description
System.String

ToConfigAttributes(IDictionary<String, Object>)

Converts dictionary into configuration where every original node gets represented as an attribute of config's root

Declaration
public static Configuration ToConfigAttributes(this IDictionary<string, object> dict)
Parameters
Type Name Description
System.Collections.Generic.IDictionary<System.String, System.Object> dict
Returns
Type Description
Configuration

ToConfigSections(IDictionary<String, Object>)

Converts dictionary into configuration where every original node gets represented as a sub-section of config's root

Declaration
public static Configuration ToConfigSections(this IDictionary<string, object> dict)
Parameters
Type Name Description
System.Collections.Generic.IDictionary<System.String, System.Object> dict
Returns
Type Description
Configuration

ToDebugView(Expression, Int32)

Converts expression tree to simple textual form for debugging

Declaration
public static string ToDebugView(this Expression expr, int indent = 0)
Parameters
Type Name Description
System.Linq.Expressions.Expression expr
System.Int32 indent
Returns
Type Description
System.String

ToDescription(MemberInfo)

Returns MemberInfo described as short string

Declaration
public static string ToDescription(this MemberInfo mem)
Parameters
Type Name Description
System.Reflection.MemberInfo mem
Returns
Type Description
System.String

ToDumpString(Byte[], DumpFormat, Int32, Int32, Boolean, Encoding, Int32)

Convert a buffer to a printable string

Declaration
public static string ToDumpString(this byte[] buf, DumpFormat fmt, int offset = 0, int count = -1, bool eol = false, Encoding encoding = null, int maxLen = 0)
Parameters
Type Name Description
System.Byte[] buf

Buffer to convert

DumpFormat fmt

Dumping format

System.Int32 offset

Starting index

System.Int32 count

Number of bytes to process (-1 means all bytes in the buffer)

System.Boolean eol

If true, terminate with end-of-line

System.Text.Encoding encoding

Encoding to use for writing data in Binary format

System.Int32 maxLen

Max length of the returned string. Pass 0 for unlimited length

Returns
Type Description
System.String

ToGUID(String)

Generates GUID based on a string MD5 hash

Declaration
public static Guid ToGUID(this string input)
Parameters
Type Name Description
System.String input
Returns
Type Description
System.Guid

ToIPEndPoint(String, Int32)

Resolve IP address by Name

Declaration
public static IPEndPoint ToIPEndPoint(this string epoint, int dfltPort = 0)
Parameters
Type Name Description
System.String epoint

An ip address or DNS host name with optional port separated by ':'

System.Int32 dfltPort

Port number to use if not supplied in endpoint string

Returns
Type Description
System.Net.IPEndPoint

IPEndPoint instance or null supplied string could not be parsed

ToJSONDataMap(Exception, Boolean, Boolean)

If there is error, converts its details to JSOnDataMap

Declaration
public static JSONDataMap ToJSONDataMap(this Exception error, bool recurse = true, bool stackTrace = false)
Parameters
Type Name Description
System.Exception error
System.Boolean recurse
System.Boolean stackTrace
Returns
Type Description
JSONDataMap

ToMD5(Byte[])

Returns a MD5 hash of a byte array

Declaration
public static byte[] ToMD5(this byte[] input)
Parameters
Type Name Description
System.Byte[] input
Returns
Type Description
System.Byte[]

ToMD5(String)

Returns a MD5 hash of a UTF8 string represented as byte[]

Declaration
public static byte[] ToMD5(this string input)
Parameters
Type Name Description
System.String input
Returns
Type Description
System.Byte[]

ToMD5String(Byte[])

Returns a MD5 hash of a UTF8 string represented as hex string

Declaration
public static string ToMD5String(this byte[] input)
Parameters
Type Name Description
System.Byte[] input
Returns
Type Description
System.String

ToMD5String(String)

Returns a MD5 hash of a UTF8 string represented as hex string

Declaration
public static string ToMD5String(this string input)
Parameters
Type Name Description
System.String input
Returns
Type Description
System.String

ToMessageWithType(Exception)

Writes exception message with exception type

Declaration
public static string ToMessageWithType(this Exception error)
Parameters
Type Name Description
System.Exception error
Returns
Type Description
System.String

ToMicrosecondsSinceUnixEpochStart(DateTime)

Gets number of microseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static long ToMicrosecondsSinceUnixEpochStart(this DateTime when)
Parameters
Type Name Description
System.DateTime when
Returns
Type Description
System.Int64

ToMillisecondsSinceUnixEpochStart(DateTime)

Gets number of milliseconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static long ToMillisecondsSinceUnixEpochStart(this DateTime when)
Parameters
Type Name Description
System.DateTime when
Returns
Type Description
System.Int64

ToSecondsSinceUnixEpochStart(DateTime)

Gets number of seconds since Unix epoch start (1970/1/1 0:0:0)

Declaration
public static long ToSecondsSinceUnixEpochStart(this DateTime when)
Parameters
Type Name Description
System.DateTime when
Returns
Type Description
System.Int64

ToUTF8Bytes(String)

Encodes string with standart UTF8 encoder

Declaration
public static byte[] ToUTF8Bytes(this string str)
Parameters
Type Name Description
System.String str
Returns
Type Description
System.Byte[]

Truncate(DateTime, Int64)

Tuncate date to specific resolution

Declaration
public static DateTime Truncate(this DateTime now, long tickResolution)
Parameters
Type Name Description
System.DateTime now
System.Int64 tickResolution
Returns
Type Description
System.DateTime
Back to top Copyright © 2006-2018 Agnicore Inc
Generated by DocFX