Skip to content

Latest commit

 

History

History
1421 lines (893 loc) · 59.1 KB

API.md

File metadata and controls

1421 lines (893 loc) · 59.1 KB

DotNet.CommonHelpers

Contents

AppSettingNotFoundException type

Namespace

DotNet.CommonHelpers.Exceptions

Summary

Represents errors that occur during application execution.

#ctor() constructor

Summary

Initializes a new instance of the AppSettingNotFoundException

Parameters

This constructor has no parameters.

#ctor(message) constructor

Summary

Initializes a new instance of the AppSettingNotFoundException class with a specified error message

Parameters
Name Type Description
message System.String The message that describes the error.

#ctor(message,innerException) constructor

Summary

Initializes a new instance of the AppSettingNotFoundException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Parameters
Name Type Description
message System.String The message that describes the error.
innerException System.Exception The exception that is the cause of the current exception, or a null reference if no inner exception is specified.

#ctor(info,context) constructor

Summary

Initializes a new instance of the AppSettingNotFoundException class with serialized data.

Parameters
Name Type Description
info System.Runtime.Serialization.SerializationInfo The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context System.Runtime.Serialization.StreamingContext The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.

AppSettings type

Namespace

DotNet.CommonHelpers

Summary

Get``1(key) method

Summary

Easier reading of App.config parameters.

Returns
Parameters
Name Type Description
key System.String Appsettings key
Generic Types
Name Description
T Type of the parameter
Exceptions
Name Description
DotNet.CommonHelpers.Exceptions.AppSettingNotFoundException Thrown when specified key is not found in the appsettings
Example
var timeret = AppSettings.Get<int>("Timeout");                

AsyncHelper type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Helper for running async functions synchronously

RunSync(func) method

Summary

Runs an async method synchronously

Parameters
Name Type Description
func System.Func{System.Threading.Tasks.Task}

RunSync``1(func) method

Summary

Runs an async function synchronously

Returns
Parameters
Name Type Description
func System.Func{System.Threading.Tasks.Task{``0}}
Generic Types
Name Description
TResult

CleanerCodeExtensions type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Extensions that make the code easier to read and mentain

Require``1(param,condition) method

Summary

Checks if the parameter meets the condition. It throws an exception if it does not

Parameters
Name Type Description
param ``0 parameter to be checked
condition System.Func{``0,System.Boolean} Condition to be met
Generic Types
Name Description
T
Example

int amount = 30; string productName = ""; amount.Require(a=>a>0); productName.Require(p=>!string.IsNullOrWhiteSpace(p));

DBHelper type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Makes querying the database easier/more elegant

ConnectionString property

Summary

Global connection string. It has to be set if you wish to execute queries without specifying the connectionString

QueryCommandTimeout property

Summary

Global query CommandTimeout in seconds

QueryDT(sqlQuery,connectionString,timeout) method

Summary

Executes the query. If connectionString and timeout are null it takes the default settings. If ConnectionString is null you have to set it before the 1st call with DBHelper.ConnectionString=...

Returns

Results of the query in a datatable

Parameters
Name Type Description
sqlQuery System.String SQL query to be executed
connectionString System.String SQL Database connection string
timeout System.Nullable{System.Int32} Command timeout in seconds
Example
var data = "SELECT * FROM [dbo].[Table]".QueryDT(); // gets results of the query as a DataTable        

EnumerationExtensions type

Namespace

DotNet.CommonHelpers.Extensions

GetEnumerator(range) method

Summary

Syntactic suggar for better looking loops

Parameters
Name Type Description
range System.Range
Example
foreach(var i in 4..10)
    Console.WriteLine(i);
    
foreach(var i in 42..13)
    Console.WriteLine(i);

LinqExtensions type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Linq extensions

Clone``1() method

Summary

Clones a list of clonable items

Parameters

This method has no parameters.

MaxIndex``1() method

Summary

Index of max value

Parameters

This method has no parameters.

ToConsoleSameLine``1() method

Summary

Write items to console using converter function func

Parameters

This method has no parameters.

ObjectShredder type

Namespace

DotNet.CommonHelpers.Extensions

Summary

EnumerableToDataTable``1(varlist) method

Summary

Converts an IEnumerable list to a DataTable

Returns

DataTable

Parameters
Name Type Description
varlist System.Collections.Generic.IEnumerable{``0}
Generic Types
Name Description
T Type with parameters (getters and setters)
Example
class Test { 
    public int id { get; set; } 
    public string name { get; set; } 
}
...
var input =  new[] { new Test() { id=1, name="x" } };
var ret = input.EnumerableToDataTable(); // returns a datatable

RawQuery type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Helpers for better looking dapper queries ex. var data = "SELECT ID, Name FROM dbo.MyTable".Query(cString);

ConnectionString property

Summary

Default connection string. It has to be set if you want to use Query commands without specifying the connection stirng

Example
RawQuery.ConnectionString = "myconnection string...";
var data = "SELECT * FROM TestTable".Query<dynamic>();

Execute(cString,sql,param,transaction,commandTimeout,commandType) method

Summary

Execute parameterized SQL.

Returns

The number of rows affected.

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute for this query.
param System.Object The parameters to use for this query.
transaction System.Data.IDbTransaction The transaction to use for this query.
commandTimeout System.Nullable{System.Int32} Number of seconds before command execution timeout.
commandType System.Nullable{System.Data.CommandType} Is it a stored proc or a batch?
Example
"EXEC dbo.DoSomething @id".Execute(param: new {id=123}); // executes stored procedure dbo.DoSomething with the parameter @id = 123

ExecuteAsync(cString,sql,param,transaction,commandTimeout,commandType) method

Summary

Execute a command asynchronously using Task.

Returns

The number of rows affected.

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute for this query.
param System.Object The parameters to use for this query.
transaction System.Data.IDbTransaction The transaction to use for this query.
commandTimeout System.Nullable{System.Int32} Number of seconds before command execution timeout.
commandType System.Nullable{System.Data.CommandType} Is it a stored proc or a batch?
Example
await "EXEC dbo.DoSomething @id".ExecuteAsync(param: new {id=123}); // executes stored procedure dbo.DoSomething with the parameter @id = 123

ExecuteScalarAsync``1(cString,sql,param,transaction,commandTimeout,commandType) method

Summary

Execute parameterized SQL that selects a single value asynchronously using Task.

Returns

The first cell returned, as TEntity.

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute.
param System.Object The parameters to use for this command.
transaction System.Data.IDbTransaction The transaction to use for this command.
commandTimeout System.Nullable{System.Int32} Number of seconds before command execution timeout.
commandType System.Nullable{System.Data.CommandType} Is it a stored proc or a batch?
Generic Types
Name Description
TEntity The type to return.
Example
var tableRowCount = await "SELECT count(1) FROM [dbo].[Table]".ExecuteScalarAsync<int>(); // gets number of records of dbo.Table        

ExecuteScalar``1(cString,sql,param,transaction,commandTimeout,commandType) method

Summary

Execute parameterized SQL that selects a single value.

Returns

The first cell returned, as TEntity.

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute.
param System.Object The parameters to use for this command.
transaction System.Data.IDbTransaction The transaction to use for this command.
commandTimeout System.Nullable{System.Int32} Number of seconds before command execution timeout.
commandType System.Nullable{System.Data.CommandType} Is it a stored proc or a batch?
Generic Types
Name Description
TEntity The type to return.
Example
var tableRowCount = "SELECT count(1) FROM [dbo].[Table]".ExecuteScalar<int>(); // gets number of records of dbo.Table        

QueryAsync``1(cString,sql,param,transaction,commandTimeout,commandType) method

Summary

Executes a query asynchronously using Task, returning the data typed as TEntity.

Returns

A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is created per row, and a direct column-name===member-name mapping is assumed (case insensitive).

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute for the query.
param System.Object The parameters to pass, if any.
transaction System.Data.IDbTransaction The transaction to use, if any.
commandTimeout System.Nullable{System.Int32} The command timeout (in seconds).
commandType System.Nullable{System.Data.CommandType} The type of command to execute.
Generic Types
Name Description
TEntity The type of results to return.
Example
var data = await "SELECT * FROM [dbo].[Table]".QueryAsync<dynamic>(); // gets results of the query as IEnumerble dynamic type
class Table{
    public int ID {get;set;}
    public string Name {get;set;}
}
var tableData = await "SELECT * FROM [dbo].[Table]".QueryAsync<Table>(); // gets results of the query and mapps them to IEnumerable<Table>

Query``1(cString,sql,param,transaction,buffered,commandTimeout,commandType) method

Summary

Executes a query, returning the data typed as TEntity.

Returns

A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is created per row, and a direct column-name===member-name mapping is assumed (case insensitive).

Parameters
Name Type Description
cString System.String The connection string to query on. If cString is null you have to set it before the 1st call with RawQuery.ConnectionString
sql System.String The SQL to execute for the query.
param System.Object The parameters to pass, if any.
transaction System.Data.IDbTransaction The transaction to use, if any.
buffered System.Boolean Whether to buffer results in memory.
commandTimeout System.Nullable{System.Int32} The command timeout (in seconds).
commandType System.Nullable{System.Data.CommandType} The type of command to execute.
Generic Types
Name Description
TEntity The type of results to return.
Example
var data = "SELECT * FROM [dbo].[Table]".Query<dynamic>(); // gets results of the query as IEnumerble dynamic type
class Table{
    public int ID {get;set;}
    public string Name {get;set;}
}
var tableData = "SELECT * FROM [dbo].[Table]".Query<Table>(); // gets results of the query and mapps them to IEnumerable<Table>

ReflectionCopy type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Deep copying of objects using reflection

Copy(source,destinationType) method

Summary

Copies an array (source) to a destination array of type destinationType

Returns
Parameters
Name Type Description
source System.Collections.Generic.List{System.Object}
destinationType System.Type

Copy(source,destinationType) method

Summary

Makes a shallow copy of a similar object (same properties!)

Returns
Parameters
Name Type Description
source System.Object
destinationType System.Type

CopyList``1(source) method

Summary

Copies an array (source) to a destination array of type T

Returns
Parameters
Name Type Description
source System.Object

CopyList``1(source,skipParams) method

Summary

Copies an array (source) to a destination array of type T that skips the parameters in skipParams list

Returns
Parameters
Name Type Description
source System.Object
skipParams System.Collections.Generic.List{System.String}

Copy``1(source,skipParams) method

Summary

Makes a shallow copy of a similar object (same properties!)

Returns
Parameters
Name Type Description
source System.Object
skipParams System.Collections.Generic.List{System.String}
Generic Types
Name Description
T

Copy``1(source) method

Summary

Makes a shallow copy of a similar object (same properties!)

Returns
Parameters
Name Type Description
source System.Object
Generic Types
Name Description
T

Modify(source,destination) method

Summary
Parameters
Name Type Description
source System.Object
destination System.Object

Modify(source,destination,skipParams) method

Summary
Parameters
Name Type Description
source System.Object
destination System.Object
skipParams System.Collections.Generic.List{System.String} list of parameter names to be ignored

SerializationExtension type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Easier object serialization and deserialization

XmlDeserialize``1(xml) method

Summary

Deserializes an xml string in to an object of Type T

Returns

A new object of type T is successful, null if failed

Parameters
Name Type Description
xml System.String Xml as string to deserialize from
Generic Types
Name Description
T Any class type

XmlSerialize``1(obj) method

Summary

Serializes an object of type T in to an xml string

Returns

A string that represents Xml, empty otherwise

Parameters
Name Type Description
obj ``0 Object to serialize
Generic Types
Name Description
T Any class type

StringExtensions type

Namespace

Dotnet.CommonHelpers.Extensions

Summary

Additional extension methods for strings.

SpecialChars constants

Summary

List of special character for trimming. Default values are ' ', '\t', '\r', '\n', '.', ',', '!', '?', '/', '\'

ConvertHexToBin() method

Summary

Converst a hex representation of the string into binary one

Parameters

This method has no parameters.

Example
var t1 = "A0".ConvertHexToBin(); // returns false        

EmptyIfNull(s) method

Summary

Returns empty string if string is null

Returns
Parameters
Name Type Description
s System.String

EqualsCI(a,b) method

Summary

Case insesitive equals operator

Returns

true if strings are equal (case insensitive)

Parameters
Name Type Description
a System.String 1st parameter
b System.String 2nd parameter
Example
var ret = "Test".EqualsCI("test"); // returns true;

FixSpaces(input) method

Summary

Replaces multiple spaces with one

Returns

string with multiple spaces removed

Parameters
Name Type Description
input System.String
Example
var ret = "to     je testno  besedilo".FixSpaces(); // returns "to je testno besedilo"

GetNumbers() method

Summary

Splits the string and keeps only the numbers. Anything other than a number is treated as a separator

Parameters

This method has no parameters.

Example
var numbers = "1,24b32test3    6".GetNumbers(); // returns {1,24,32,3,6}

HasQuotes() method

Summary

Checks if a string starts with openingQuote and ends with closing quote

Parameters

This method has no parameters.

Example
bool hasQuotes = "someString".HasQuotes(); // returns false

IsAnagram() method

Summary

Returns true if the Second word is an anagram of the current string

Parameters

This method has no parameters.

Example
var t1 = "ABC".IsAnagram("ABE"); // returns false
var t2 = "ELVIS".IsAnagram("LIVES"); // returns true

Left(s,length) method

Summary

Returns the "lenght" leftmost characters

Returns
Parameters
Name Type Description
s System.String
length System.Int32

LimitDomain(input) method

Summary

Truncates the url, so it contains only the domain and two first folders, if they exist ex http://www.google.com/reader/test?234iojapjapriogjerg becomes http://www.google.com/reader

Returns

Truncated url

Parameters
Name Type Description
input System.String
Example
var ret = "http://www.google.si/search/dva".LimitDomain(); // returns "http://www.google.si/search"

MD5() method

Summary

Returns a MD5 hash of the string

Parameters

This method has no parameters.

Example
var ret = "test".MD5();  // returns "C8059E2EC7419F590E79D7F1B774BFE6"

RemoveDiacritics() method

Summary

Removes diacritics from a string (ščžć...)

Parameters

This method has no parameters.

Example
var x = "ščepec".RemoveDiacritics(); // returns "scepec"

RemoveDiacriticsAndNormalize() method

Summary

Removes diacritics (ščž..) and normalizes string https://stackoverflow.com/questions/3288114/what-does-nets-string-normalize-do replaces spaces with hypens(-) removes + and .

Parameters

This method has no parameters.

RemoveHtmlTags(text) method

Summary

Removes HTML tags from string. (all text that is between < and >)

Returns

Text without html tags

Parameters
Name Type Description
text System.String
Example
var ret = "

RemoveSpacesAndNewLines(input) method

Summary

Remove spaces and newlines from string

Returns

Clean string, without spaces and newlines

Parameters
Name Type Description
input System.String

RemoveStrings(text,tags) method

Summary

Removes all strings specified in tags

Returns

Cleaned string

Parameters
Name Type Description
text System.String
tags System.String[] Strings to be removed / replaced with empty.

Reverse() method

Summary

Reverses the string

Parameters

This method has no parameters.

Example
var ret = "ABCD".Reverse(); // returns "DCBA"

Right(value,length) method

Summary

Get substring of specified number of characters on the right.

Returns

right lenght of characters

Parameters
Name Type Description
value System.String
length System.Int32
Example
var ret = "testno".Right(2); // returns "no"

SHA1() method

Summary

Returns a SHA1 hash of the string

Parameters

This method has no parameters.

Example
var ret = "test".SHA1();  // returns "C8059E2EC7419F590E79D7F1B774BFE6"

SplitAtFirstSpace(text) method

Summary

Split string at first space into two strings.

Returns

Split string

Parameters
Name Type Description
text System.String String to be split
Example
var ret = "John Fitzgerald Kennedy".SplitAtFirstSpace() // returns {"John", "Fitzgerald Kennedy"}

StringToIntArray() method

Summary

Converts a delimited string array to an array of ints. Tokens that can't be converted are left out

Parameters

This method has no parameters.

Example
var ret = "1,3,e,c,11,abba".StringToIntArray(); // returns {1,3,11}        

StripHtml(input) method

Summary

Strips html tags from input

Returns
Parameters
Name Type Description
input System.String

ToDate() method

Summary

Converts a string to Datetime. If no conversion is possible it returns null

Parameters

This method has no parameters.

Example
var ret1 = "3.2.2015".ToDate();  // returns [3.02.2016 00:00:00] datetime object
var ret1 = "33.2.2015".ToDate(); // returns null

TrimEndSpecialChars() method

Summary

Trims the ending of a string if a character is any of SpecialChars

Parameters

This method has no parameters.

Example
var ret = "! !?someString!".TrimEndSpecialChars(); // returns "! !?someString"

TrimSpecialChars() method

Summary

Trims a string of SpecialChars

Parameters

This method has no parameters.

Example
var ret = "! !?someString!".TrimSpecialChars(); // returns "someString"

TrimStartSpecialChars() method

Summary

Trims the beginning of a string if a character is any of SpecialChars

Parameters

This method has no parameters.

Example
var ret = "! !?someString!".TrimStartSpecialChars(); // returns "someString!"

TruncateAtWord(text,length) method

Summary

Truncate the string before specified length, without breaking words.

Returns

Truncated string

Parameters
Name Type Description
text System.String String to be truncated
length System.Int32 Max length of the truncated string

TryParseInt32() method

Summary

Parses a string to an int. If the string is not an int it returns null

Parameters

This method has no parameters.

Example
var ret = "! !?someString!".TryParseInt32(); // returns null
var out2 = "123".TryParseInt32(); // returns 123

ValueObject type

Namespace

DotNet.CommonHelpers.Extensions

Summary

Learn more: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects