Table of Contents

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

dictionary ConcurrentDictionary<TKey, Lazy<TValue>>

Dictionary object we're operating on

key TKey

Key we want to add or update.

addValueFactory Func<TKey, TValue>

The function used to generate a value for an absent key

updateValueFactory Func<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

TKey

Key type for dictionary

TValue

Value 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

dictionary ConcurrentDictionary<K, V>

Dictionary object we're operating on

key K

Key we want to add or update.

value V

Value we want to set.

Type Parameters

K

Key type for dictionary

V

Value 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

dictionary IDictionary<TKey, TCollection>

The source dictionary to be added to

key TKey

The key

element TElement

The element to be added

Type Parameters

TKey

The key type

TElement

The collection element type

TCollection

The 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

enumerable IEnumerable<T>

The enumerable to be batched

batchSize int

The number of items per batch

Returns

IEnumerable<List<T>>

An enumerable of lists

Type Parameters

T

The 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

queue ConcurrentQueue<T>

queue object

Type Parameters

T

Queue 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

value string

The string value to be converted

type Type

The output type

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

value string

The string value to be converted

Returns

T

The converted value

Type Parameters

T

The 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

type Type

The 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

str string

String 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

str string

String 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

stream Stream

The 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

bytes byte[]

Byte array to convert.

encoding Encoding

The 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

value string

The original string

left char

Left bound of the substring

right char

Right 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

date DateTime

The 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

value double

The double value to check

Returns

bool

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

type Type

The type to be checked as a subclass of possibleSuperType

possibleSuperType Type

The possible superclass of type

Returns

bool

True if type is a subclass of the generic type definition possibleSuperType

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

data string

The 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

type Type

The type to test for a match

typeName string

The name of the type to match

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

list List<T>

List we're operating on.

oldIndex int

Index of variable we want to move.

newIndex int

New location for the variable

Type Parameters

T

Type of list

ProcessUntilEmpty<T>(IProducerConsumerCollection<T>, Action<T>)

public static void ProcessUntilEmpty<T>(this IProducerConsumerCollection<T> collection, Action<T> handler)

Parameters

collection IProducerConsumerCollection<T>
handler Action<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

s string

original string value

ending string

the string to be removed

Returns

string

Reset(Timer)

Add the reset method to the System.Timer class.

public static void Reset(this Timer timer)

Parameters

timer Timer

System.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

datetime DateTime

Datetime object we're rounding.

roundingInterval TimeSpan

Timespan 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

time TimeSpan

Base timespan we're looking to round.

roundingInterval TimeSpan

Timespan 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

time TimeSpan

TimeSpan To Round

roundingInterval TimeSpan

Rounding Unit

roundingType MidpointRounding

Rounding 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

dateTime long

Base DateTime object we're rounding down.

interval TimeSpan

Timespan 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

d double

Double we're rounding

digits int

Number of significant figures

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

time DateTime

Base datetime object to round up.

d TimeSpan

Timespan interval for rounding

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

input double

The 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

names List<string>

The list of class names

algorithmTypeName string

The 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

input double

Returns

double

SynchronouslyAwaitTask(Task)

Safely blocks until the specified task has completed executing

public static void SynchronouslyAwaitTask(this Task task)

Parameters

task Task

The 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

task Task<TResult>

The task to be awaited

Returns

TResult

The result of the task

Type Parameters

TResult

The 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

str string

The string to be broken into csv

size int

The expected size of the output list

Returns

List<string>

A list of the csv pieces

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

str string

The string to be broken into csv

size int

The expected size of the output list

Returns

List<string>

A list of the csv pieces

ToDouble(string)

Extension method for faster string to double conversion.

public static double ToDouble(this string str)

Parameters

str string

String 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

str string

String 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

str string

String 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

enum Enum

The 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

str string

String 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

data string

Data 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

str string

String 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

value double

The 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

waitHandle WaitHandle

The wait handle to wait on

millisecondsTimeout int

The number of milliseconds to wait, or Infinite(-1) to wait indefinitely.

cancellationToken CancellationToken

The CancellationToken to observe.

Returns

bool

true if the WaitHandle was set; otherwise, false.

Exceptions

System.Threading.OperationCanceledException

cancellationToken was canceled.

ArgumentOutOfRangeException

millisecondsTimeout is 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 cancellationToken has 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

waitHandle WaitHandle

The wait handle to wait on

cancellationToken CancellationToken

The CancellationToken to observe.

Returns

bool

Exceptions

InvalidOperationException

The maximum number of waiters has been exceeded.

System.OperationCanceledExcepton

cancellationToken was canceled.

ObjectDisposedException

The object has already been disposed or the CancellationTokenSource that created cancellationToken has 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

waitHandle WaitHandle

The wait handle to wait on

timeout TimeSpan

A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.

cancellationToken CancellationToken

The CancellationToken to observe.

Returns

bool

true if the WaitHandle was set; otherwise, false.

Exceptions

System.Threading.OperationCanceledException

cancellationToken was canceled.

ArgumentOutOfRangeException

timeout is 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 cancellationToken has been disposed.

WithEmbeddedHtmlAnchors(string)

Convert a string into the same string with a URL! :)

public static string WithEmbeddedHtmlAnchors(this string source)

Parameters

source string

The source string to be converted

Returns

string

The same source string but with anchor tags around substrings matching a link regex