Class Extensions
- Namespace
- FinanceSharp
- Assembly
- FinanceSharp.dll
Extensions function collections - group all static extensions functions here.
public static class Extensions
- Inheritance
-
Extensions
- Inherited Members
Methods
AddOrUpdate<TKey, TValue>(ConcurrentDictionary<TKey, Lazy<TValue>>, TKey, Func<TKey, TValue>, Func<TKey, TValue, TValue>)
Extension method to automatically add/update lazy values in concurrent dictionary.
public static TValue AddOrUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
Parameters
dictionaryConcurrentDictionary<TKey, Lazy<TValue>>Dictionary object we're operating on
keyTKeyKey we want to add or update.
addValueFactoryFunc<TKey, TValue>The function used to generate a value for an absent key
updateValueFactoryFunc<TKey, TValue, TValue>The function used to generate a new value for an existing key based on the key's existing value
Returns
- TValue
Type Parameters
TKeyKey type for dictionary
TValueValue type for dictonary
AddOrUpdate<K, V>(ConcurrentDictionary<K, V>, K, V)
Extension method to automatically set the update value to same as "add" value for TryAddUpdate. This makes the API similar for traditional and concurrent dictionaries.
public static void AddOrUpdate<K, V>(this ConcurrentDictionary<K, V> dictionary, K key, V value)
Parameters
dictionaryConcurrentDictionary<K, V>Dictionary object we're operating on
keyKKey we want to add or update.
valueVValue we want to set.
Type Parameters
KKey type for dictionary
VValue type for dictonary
Add<TKey, TElement, TCollection>(IDictionary<TKey, TCollection>, TKey, TElement)
Adds the specified element to the collection with the specified key. If an entry does not exist for th specified key then one will be created.
public static void Add<TKey, TElement, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TElement element) where TCollection : ICollection<TElement>, new()
Parameters
dictionaryIDictionary<TKey, TCollection>The source dictionary to be added to
keyTKeyThe key
elementTElementThe element to be added
Type Parameters
TKeyThe key type
TElementThe collection element type
TCollectionThe collection type
BatchBy<T>(IEnumerable<T>, int)
Performs on-line batching of the specified enumerator, emitting chunks of the requested batch size
public static IEnumerable<List<T>> BatchBy<T>(this IEnumerable<T> enumerable, int batchSize)
Parameters
enumerableIEnumerable<T>The enumerable to be batched
batchSizeintThe number of items per batch
Returns
- IEnumerable<List<T>>
An enumerable of lists
Type Parameters
TThe enumerable item type
Clear<T>(ConcurrentQueue<T>)
Extentsion method to clear all items from a thread safe queue
public static void Clear<T>(this ConcurrentQueue<T> queue)
Parameters
queueConcurrentQueue<T>queue object
Type Parameters
TQueue type
Remarks
Small risk of race condition if a producer is adding to the list.
ConvertTo(string, Type)
Converts the specified string value into the specified type
public static object ConvertTo(this string value, Type type)
Parameters
Returns
- object
The converted value
ConvertTo<T>(string)
Converts the specified string value into the specified type
public static T ConvertTo<T>(this string value)
Parameters
valuestringThe string value to be converted
Returns
- T
The converted value
Type Parameters
TThe output type
GetBetterTypeName(Type)
Gets a type's name with the generic parameters filled in the way they would look when
defined in code, such as converting Dictionary<1,2> to Dictionary<string,int>
public static string GetBetterTypeName(this Type type)
Parameters
typeTypeThe type who's name we seek
Returns
- string
A better type name
GetBytes(string)
Extension method to convert a string into a byte array
public static byte[] GetBytes(this string str)
Parameters
strstringString to convert to bytes.
Returns
- byte[]
Byte array
GetExtension(string)
Extension method to extract the extension part of this file name if it matches a safe list, or return a ".custom" extension for ones which do not match.
public static string GetExtension(this string str)
Parameters
strstringString we're looking for the extension for.
Returns
- string
Last 4 character string of string.
GetMD5Hash(Stream)
Gets the MD5 hash from a stream
public static byte[] GetMD5Hash(this Stream stream)
Parameters
streamStreamThe stream to compute a hash for
Returns
- byte[]
The MD5 hash
GetString(byte[], Encoding)
Extension method to convert a byte array into a string.
public static string GetString(this byte[] bytes, Encoding encoding = null)
Parameters
bytesbyte[]Byte array to convert.
encodingEncodingThe encoding to use for the conversion. Defaults to Encoding.ASCII
Returns
- string
String from bytes.
GetStringBetweenChars(string, char, char)
Get the first occurence of a string between two characters from another string
public static string GetStringBetweenChars(this string value, char left, char right)
Parameters
valuestringThe original string
leftcharLeft bound of the substring
rightcharRight bound of the substring
Returns
- string
Substring from original string bounded by the two characters
IsCommonBusinessDay(DateTime)
Business day here is defined as any day of the week that is not saturday or sunday
public static bool IsCommonBusinessDay(this DateTime date)
Parameters
dateDateTimeThe date to be examined
Returns
- bool
A bool indicating wether the datetime is a weekday or not
IsNaNOrZero(double)
Check if a number is NaN or equal to zero
public static bool IsNaNOrZero(this double value)
Parameters
valuedoubleThe double value to check
Returns
IsSubclassOfGeneric(Type, Type)
Checks the specified type to see if it is a subclass of the possibleSuperType. This method will
crawl up the inheritance heirarchy to check for equality using generic type definitions (if exists)
public static bool IsSubclassOfGeneric(this Type type, Type possibleSuperType)
Parameters
typeTypeThe type to be checked as a subclass of
possibleSuperTypepossibleSuperTypeTypeThe possible superclass of
type
Returns
- bool
True if
typeis a subclass of the generic type definitionpossibleSuperType
LazyToUpper(string)
Lazy string to upper implementation. Will first verify the string is not already upper and avoid the call to ToUpper() if possible.
public static string LazyToUpper(this string data)
Parameters
datastringThe string to upper
Returns
- string
The upper string
MatchesTypeName(Type, string)
Function used to match a type against a string type name. This function compares on the AssemblyQualfiedName, the FullName, and then just the Name of the type.
public static bool MatchesTypeName(this Type type, string typeName)
Parameters
Returns
- bool
True if the specified type matches the type name, false otherwise
Move<T>(List<T>, int, int)
Extension to move one element from list from A to position B.
public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
Parameters
listList<T>List we're operating on.
oldIndexintIndex of variable we want to move.
newIndexintNew location for the variable
Type Parameters
TType of list
ProcessUntilEmpty<T>(IProducerConsumerCollection<T>, Action<T>)
public static void ProcessUntilEmpty<T>(this IProducerConsumerCollection<T> collection, Action<T> handler)
Parameters
collectionIProducerConsumerCollection<T>handlerAction<T>
Type Parameters
T
RemoveFromEnd(string, string)
Returns a new string in which specified ending in the current instance is removed.
public static string RemoveFromEnd(this string s, string ending)
Parameters
Returns
Reset(Timer)
Add the reset method to the System.Timer class.
public static void Reset(this Timer timer)
Parameters
timerTimerSystem.timer object
Round(DateTime, TimeSpan)
Extension method to round a datetime to the nearest unit timespan.
public static DateTime Round(this DateTime datetime, TimeSpan roundingInterval)
Parameters
datetimeDateTimeDatetime object we're rounding.
roundingIntervalTimeSpanTimespan rounding period.
Returns
- DateTime
Rounded datetime
Round(TimeSpan, TimeSpan)
Extension method to round timespan to nearest timespan period.
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval)
Parameters
timeTimeSpanBase timespan we're looking to round.
roundingIntervalTimeSpanTimespan period we're rounding.
Returns
- TimeSpan
Rounded timespan period
Round(TimeSpan, TimeSpan, MidpointRounding)
Extension method to round a timeSpan to nearest timespan period.
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval, MidpointRounding roundingType)
Parameters
timeTimeSpanTimeSpan To Round
roundingIntervalTimeSpanRounding Unit
roundingTypeMidpointRoundingRounding method
Returns
- TimeSpan
Rounded timespan
RoundDown(long, TimeSpan)
Extension method to round a datetime down by a timespan interval.
public static long RoundDown(this long dateTime, TimeSpan interval)
Parameters
dateTimelongBase DateTime object we're rounding down.
intervalTimeSpanTimespan interval to round to.
Returns
- long
Rounded datetime
RoundToSignificantDigits(double, int)
Extension method to round a double value to a fixed number of significant figures instead of a fixed double places.
public static double RoundToSignificantDigits(this double d, int digits)
Parameters
Returns
- double
New double rounded to digits-significant figures
RoundUp(DateTime, TimeSpan)
Extension method to explicitly round up to the nearest timespan interval.
public static DateTime RoundUp(this DateTime time, TimeSpan d)
Parameters
Returns
- DateTime
Rounded datetime
SafeDecimalCast(double)
Casts the specified input value to a double while acknowledging the overflow conditions
public static double SafeDecimalCast(this double input)
Parameters
inputdoubleThe value to be cast
Returns
- double
The input value as a double, if the value is too large or to small to be represented as a double, then the closest double value will be returned
SingleOrAlgorithmTypeName(List<string>, string)
Return the first in the series of names, or find the one that matches the configured algirithmTypeName
public static string SingleOrAlgorithmTypeName(this List<string> names, string algorithmTypeName)
Parameters
namesList<string>The list of class names
algorithmTypeNamestringThe configured algorithm type name from the config
Returns
- string
The name of the class being run
SmartRounding(double)
Provides global smart rounding, numbers larger than 1000 will round to 4 double places, while numbers smaller will round to 7 significant digits
public static double SmartRounding(this double input)
Parameters
inputdouble
Returns
SynchronouslyAwaitTask(Task)
Safely blocks until the specified task has completed executing
public static void SynchronouslyAwaitTask(this Task task)
Parameters
taskTaskThe task to be awaited
SynchronouslyAwaitTaskResult<TResult>(Task<TResult>)
Safely blocks until the specified task has completed executing
public static TResult SynchronouslyAwaitTaskResult<TResult>(this Task<TResult> task)
Parameters
taskTask<TResult>The task to be awaited
Returns
- TResult
The result of the task
Type Parameters
TResultThe task's result type
ToCsv(string, int)
Breaks the specified string into csv components, all commas are considered separators
public static List<string> ToCsv(this string str, int size = 4)
Parameters
Returns
ToCsvData(string, int)
Breaks the specified string into csv components, works correctly with commas in data fields
public static List<string> ToCsvData(this string str, int size = 4)
Parameters
Returns
ToDouble(string)
Extension method for faster string to double conversion.
public static double ToDouble(this string str)
Parameters
strstringString to be converted to positive double value
Returns
- double
Decimal value of the string
Remarks
Leading and trailing whitespace chars are ignored
ToInt32(string)
Extension method for faster string to Int32 conversion.
public static int ToInt32(this string str)
Parameters
strstringString to be converted to positive Int32 value
Returns
- int
Int32 value of the string
Remarks
Method makes some assuptions - always numbers, no "signs" +,- etc.
ToInt64(string)
Extension method for faster string to Int64 conversion.
public static long ToInt64(this string str)
Parameters
strstringString to be converted to positive Int64 value
Returns
- long
Int32 value of the string
Remarks
Method makes some assuptions - always numbers, no "signs" +,- etc.
ToLower(Enum)
Converts the specified enum value to its corresponding lower-case string representation
public static string ToLower(this Enum @enum)
Parameters
enumEnumThe enumeration value
Returns
- string
A lower-case string representation of the specified enumeration value
ToMD5(string)
Extension method to convert a string to a MD5 hash.
public static string ToMD5(this string str)
Parameters
strstringString we want to MD5 encode.
Returns
- string
MD5 hash of a string
ToSHA256(string)
Encrypt the token:time data to make our API hash.
public static string ToSHA256(this string data)
Parameters
datastringData to be hashed by SHA256
Returns
- string
Hashed string.
ToStream(string)
Extension method to convert strings to stream to be read.
public static Stream ToStream(this string str)
Parameters
strstringString to convert to stream
Returns
- Stream
Stream instance
TruncateTo3DecimalPlaces(double)
Will truncate the provided double, without rounding, to 3 double places
public static double TruncateTo3DecimalPlaces(this double value)
Parameters
valuedoubleThe value to truncate
Returns
- double
New instance with just 3 double places
WaitOne(WaitHandle, int, CancellationToken)
Blocks the current thread until the current WaitHandle is set, using a 32-bit signed integer to measure the time interval, while observing a CancellationToken.
public static bool WaitOne(this WaitHandle waitHandle, int millisecondsTimeout, CancellationToken cancellationToken)
Parameters
waitHandleWaitHandleThe wait handle to wait on
millisecondsTimeoutintThe number of milliseconds to wait, or Infinite(-1) to wait indefinitely.
cancellationTokenCancellationTokenThe CancellationToken to observe.
Returns
- bool
true if the WaitHandle was set; otherwise, false.
Exceptions
- System.Threading.OperationCanceledException
cancellationTokenwas canceled.- ArgumentOutOfRangeException
millisecondsTimeoutis a negative number other than -1, which represents an infinite time-out.- InvalidOperationException
The maximum number of waiters has been exceeded.
- ObjectDisposedException
The object has already been disposed or the CancellationTokenSource that created
cancellationTokenhas been disposed.
WaitOne(WaitHandle, CancellationToken)
Blocks the current thread until the current WaitHandle receives a signal, while observing a CancellationToken.
public static bool WaitOne(this WaitHandle waitHandle, CancellationToken cancellationToken)
Parameters
waitHandleWaitHandleThe wait handle to wait on
cancellationTokenCancellationTokenThe CancellationToken to observe.
Returns
Exceptions
- InvalidOperationException
The maximum number of waiters has been exceeded.
- System.OperationCanceledExcepton
cancellationTokenwas canceled.- ObjectDisposedException
The object has already been disposed or the CancellationTokenSource that created
cancellationTokenhas been disposed.
WaitOne(WaitHandle, TimeSpan, CancellationToken)
Blocks the current thread until the current WaitHandle is set, using a TimeSpan to measure the time interval, while observing a CancellationToken.
public static bool WaitOne(this WaitHandle waitHandle, TimeSpan timeout, CancellationToken cancellationToken)
Parameters
waitHandleWaitHandleThe wait handle to wait on
timeoutTimeSpanA TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.
cancellationTokenCancellationTokenThe CancellationToken to observe.
Returns
- bool
true if the WaitHandle was set; otherwise, false.
Exceptions
- System.Threading.OperationCanceledException
cancellationTokenwas canceled.- ArgumentOutOfRangeException
timeoutis a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than MaxValue.- InvalidOperationException
The maximum number of waiters has been exceeded.
- ObjectDisposedException
The object has already been disposed or the CancellationTokenSource that created
cancellationTokenhas been disposed.
WithEmbeddedHtmlAnchors(string)
Convert a string into the same string with a URL! :)
public static string WithEmbeddedHtmlAnchors(this string source)
Parameters
sourcestringThe source string to be converted
Returns
- string
The same source string but with anchor tags around substrings matching a link regex