A collection of common utilities and extension methods.
This is the place for all "common" helpers, extension methods and utilities. There is only one condition: The helpers may not require any third party packages.
AsyncHelperRun async method in a synchonous context.RandomHelperUseful randomizing methods.TempPathHelperCreate temp files or folders safely.DisposableBase class that implementsIDisposablecorrectly.
SortedListIList<T>implementation that inserts the items sorted using binary search.
There are a lot of extensions methods available. here we sort them by the type they are implemented on.
IsIndexWithinChecks if the given index is within the array.ToMemoryStreamCreates aMemoryStreamfrom a byte array.
GetResourceAsStringAsyncGets the content of the given embedded resource location as string.
RepeatRepeats the givencharthe specified number of times.
AddIfNotContainsAdds item(s) to collection if they are not already in the collection.IsNullOrEmptyChecks if the collection is null or empty.RemoveMatchingRemoves all items from the collection that match a given predicate.
The custom interfaces IConverter and ITryConverter provide a fluent interface for
converting strings to numeric, boolean and Guid values.
string value = "5";
int result = value.Convert().ToInt();
string value = "5";
bool success = value.TryConvert().ToInt(out int result);char value = '5';
int result = value.Convert().ToInt();
char value = '5';
bool success = value.TryConvert().ToInt(out int result);The Convert() extension methods also provide overloads to provide a custom IFormatProvider. The default format provider is CultureInfo.CurrentCulture.
AddMonthsToEndOfMonthAdds the months to end of month.AddWeeksAdds an amount of weeks to a date value.CalculateAgeCalculates the age based on a passed reference date.GetDayCountOfYearGet the number of days within that date year.GetDaysGet the number of days between two dates.GetDaysOfMonthCountReturns the number of days in the month of a provided date.GetFirstDayOfMonthReturns the first day of the month of a provided date.GetFirstDayOfWeekGets the first day of the week using a specific culture.GetLastDayOfMonthReturns the last day of the month of a provided date.GetLastDayOfWeekGets the last day of the week using a specific culture.GetNextWeekdayGets the next occurrence of the specified weekday.GetPeriodOfDayReturns the period of the dayPeriodOfDay.Morning,PeriodOfDay.Afternoon,PeriodOfDay.Evening.GetPreviousWeekdayGets the previous occurrence of the specified weekday.GetWeekOfYearGets the week number for a date time value based on the current culture settings.GetWeeksWeekdayGets the next occurrence of a specified weekday within the current week using a specific culture.IsDateEqualDetermines if the date part of twoDateTimevalues are equal.IsLeapYearReturns if or not aDateTimeis during a leap year.IsTimeEqualDetermines if the time part of twoDateTimevalues are equal.IsTodayDetermines if a date isDateTime.Today.IsWeekdayDetermines if aDateTimeorDayOfWeekis a weekday.IsWeekendDetermines if aDateTimeorDayOfWeekis a weekend.MidnightGets aDateTimerepresenting midnight on a specified date.NextMonthGets the next month.NoonGets aDateTimerepresenting noon on a specified date.OrdinalSuffixConverts the day of a date to an ordinal string, f.e. 3 to '3rd'.SetTimeSets the time of the aDateTimewith a specified precicion. All other parts are set to zero.ToUnixTimestampConverts aDateTimeto a UNIX timestamp (seconds since 01.01.1970).
ContainsValueReturnstrueif the value is contained in a dictionary.GetOrAddGets a value from a dictionary with given key. Returns a default value if the value cannot be found.GetOrDefaultGets a value from a dictionary. Returnsdefaultif the value cannot be found.TryGetValueTries to get a value from a dictionary.
All operations utilize a cache of the enums metadata that is built lazily when using the extensions methods.
EnumOptionsGets all options of an enum type.EnumValuesGets all values of an enum type.HasFlagA generic version ofEnum.HasFlag(enum)"IsEmptyGets a flag, indicating if the enum has no values.MaxValueGets the maximum value of the enum.MinValueGets the minimum value of the enum.
AsReadOnlyConverts an enumerable to a read-only collection.ForEachExecutes anActionfor every item in the enumerable.IsAnyChecks if a enumerable is not null or empty.IsNullOrEmptyChecks if the enumerable is null or empty.
IsEmptyChecks aGuidisGuid.Empty.
AddForAdds a value to a list if the value matches a predicate.AddRangeAdds values to a list (IList<T>).AddRangeForAdds values to a list if the value to add matches a predicate.AddRangeSortedAdds values into a list sorted.AddSortedAdds a value into a list sorted.
ToContentStringConverts the content of the memory stream to a string.
IsNullChecks if a nullable has no value.
The numeric extensions methods are available for the following primitives: byte, short, int, long
IsBetweenDetermines if a value is between the specified values a and b (inclusive).IsEvenDetermines whether a value is even.IsOddDetermines whether a value is odd.OrdinalizeOrdinalize a number, f.e. 6 to '6th'.TimesPerforms a specified action n times based on the value.
GetDefaultValueGets the type default value for a type. In case of reference types:nulland for values typesdefault(T).IsNullReturnstrue, if the specified target reference is equal to the null reference.LockingExecutes anActionby locking on a given object.
GetClaimValueGets the first value of the given claim type and returns its value.GetClaimValuesGets all values of the given claim type and returns their values.GetDisplayNameGets the display name from theClaimsIdentityor uses the subject.GetSubjectIdGets the subject identifier.IsAuthenticatedDetermines whether a principal is authenticated.
DefinesAttributeReturnstrueif aMemberInfoinstance is marked with the specified attribute.GetMemberTypeGets the underlying type of aMemberInfoinstance.IsIndexerDetermines if aPropertyInfois an indexer.IsPropertyDetermines if aMethodInfois a property.IsPropertyGetterDetermines if aMethodInfois a property getter.IsPropertySetterDetermines if aMethodInfois a property setter.
CopyToCopies aStreaminto a another one.CopyToMemoryCopies aStreaminto a localMemoryStream.GetBytesGets all bytes of aStream.GetReaderOpens aStreamReaderfor aStream.GetWriterOpens aStreamWriterfor aStream.RewindRewinds (set the current position to 0) aStream.WriteWrites all bytes to the aStream.
ConcatWithConcatenates a string with additional strings and an optional delimiter character.EnsureEndsWithEnsures that a string ends with a given suffix.EnsureStartsWithEnsures that a string starts with a given prefix.FormatInvariantWithApplies formatting to a string using the invariant culture.FormatWithApplies formatting to a string using the current culture.FromBase64Decodes a string from base64 to its normal representation.GetBytesConverts a string to abyte[]using a specific encoding.IsNullOrEmptyDetermines if a string isnullorstring.Empty.- **
IsNullOrWhiteSpace**Determines if a string isnullorstring.Emptyor consists of whitespace-only characters. IsNumericChecks if the contents of a string is a numeric value.LeftGets a substring of a string from beginning of the string.RemovePostFixRemoves the first occurrence of postfixes from the end of a string.RemovePrefixRemoves the first occurrence of prefixes from the beginning of a string.RemoveSpacesRemoves all whitespace (not line endings, etc.) from a string.RemoveSpecialCharactersRemoves all special characters from a string.RepeatRepeats a string value as provided by the repeat count.ReplaceDiacriticsReplaces all diacritical marks with an ascii representation, fe. 'ü' to 'u'.ReplaceWithEmptyReplaces all occurrences of a string in an input string withstring.Empty.- **
Reverse**Reverses the a string. RightGets a substring of a string from end of the string.SplitUsesstring.Split(string[], StringSplitOptions)method to split a string by a separator.ToBase64Encodes string to base64.ToEnumConverts a string to a matching enum value of a given enum type.ToMemoryStreamConverts a string to aMemoryStream.TruncateTruncates a string to a specified length and optionally replaces the truncated part with '...' suffix.UrlSafeDecodeEncodes a string for safe usage in URLs, f.e. for password reset or email confirmation tokens.UrlSafeEncodeDecodes a given URL-safe string.
PluralizeReturns the plural form of a word.SingularizeReturns the singular form of a word.TitleizeReturn a string in a form that can be used as title.HumanizeHumanizes a string.PascalizePascalizes a string.CamelizeCamelizes a string.UnderscoreReplaces all dashes with underscores.CapitalizeCapitalizes a string.UncapitalizeUncapitalizes a string.OrdinalizeOrdinalizes the given number that is given as string, f.e. '6' to '6th'.DasherizeConverts all underscores to dashes.
CreateInstanceCreates an instance of a type.DefinesAttributeReturnstrueif the type is marked with a specified attribute.GetBaseClassesGets all base classes recursively for a type.ImplementsReturnstrueif type implements a specified interface.IsAssignableToChecks if a type is assignable to another type.IsCollectionDetermines if the a type is a collection.IsEnumerableDetermines if the a type is an enumerable.IsNullableDetermines if the a type is a nullable.IsNumericDetermines if the a type is numeric.IsPrimitiveDetermines whether a type is a primitive.UnwrapNullableTypeGets the type without nullable if the type is aNullable<T>.
GetSubDomainGets the sub-domain part from aUri.
IsDefaultDetermines if a value is empty (default(T)).IsNullableDetermines if a type is a nullable.ToNullableonverts a value to a corresponding nullable type.
A collection of custom data annotations.
[CompositeIndex]- An attribute to provide the composite indices of an entity.
- Targets classes.
- Allows multiple.
[DateOnly]- A marker attribute to signal potential data stores to only store the date.
- Targets properties and fields.
- Denys multiple.
[DatePrecision]- An attribute to provide the date precision to potential data stores.
- Targets properties and fields.
- Denys multiple.
[Ignore]- A marker attribute to signal potential data stores to ignore this value.
- Targets properties and fields.
- Denys multiple.
[Index]- An attribute to provide an index of the entity.
- Targets properties and fields.
- Denys multiple.
[Reference]- An attribute to signal potential data stores that this property should be stored as database reference.
- Targets properties and fields.
- Denys multiple.
[Contains]- A validation that checks if the annotated property contains the given check value.
- Targets properties and fields.
- Denys multiple.
[EndsWith]- A validation attribute that checks if the value end with the given value.
- Targets properties and fields.
- Denys multiple.
[EnforceTrue]- A validation attribute that checks if the value is
true. - Targets properties and fields.
- Denys multiple.
- A validation attribute that checks if the value is
[ListLength]- A validation attribute to check the length of a list.
- Targets properties and fields.
- Denys multiple.
[ListMaxLength]- A validation attribute to check the maximum length of a list.
- Targets properties and fields.
- Denys multiple.
[ListMinLength]- A validation attribute to check the minimum length of a list.
- Targets properties and fields.
- Denys multiple.
[NotEmpty]- A validation attribute to check if an enumerable contains at least one element.
- Targets properties and fields.
- Denys multiple.
[RequiredIf]- A validation attribute that checks if the value is required when a condition is met.
- Targets properties and fields.
- Denys multiple.
[StartsWith]- A validation attribute that checks if the value starts with the given value.
- Targets properties and fields.
- Denys multiple.
[Currency]- A data-type attribute for currency values.
- Targets properties, fields and parameters.
- Denys multiple.
[Date]- A data-type attribute for date values.
- Targets properties, fields and parameters.
- Denys multiple.
[DateTime]- A data-type attribute for date-time values.
- Targets properties, fields and parameters.
- Denys multiple.
[Duration]- A data-type attribute for duration (timespan) values.
- Targets properties, fields and parameters.
- Denys multiple.
[ImageUrl]- A data-type attribute for image-url values.
- Targets properties, fields and parameters.
- Denys multiple.
[MultilineText]- A data-type attribute for multiline text values.
- Targets properties, fields and parameters.
- Denys multiple.
[Password]- A data-type attribute for password values.
- Targets properties, fields and parameters.
- Denys multiple.
[PostalCode]- A data-type attribute for postal code values.
- Targets properties, fields and parameters.
- Denys multiple.
[Select]- A data-type attribute to signal that the values comes from a selection of values.
- Targets properties, fields and parameters.
- Denys multiple.
[Text]- A data-type attribute for text values.
- Targets properties, fields and parameters.
- Denys multiple.
[Time]- A data-type attribute for time values.
- Targets properties, fields and parameters.
- Denys multiple.
[Upload]- A data-type attribute for upload values.
- Targets properties, fields and parameters.
- Denys multiple.
A collection of LINQ expression utilities and extension methods.
The extenions methods use several utility classes that are publicly available through this library to be used forother use-cases:
EvaluatorEnables the partial evaluation of queries.LocalCollectionExpanderExpands local collection values.ParameterRebinderUsed for rebinding of parameters.
The utility classes are used to evaludate as much as possible to create a string representation of an Expression.
The result of the extension can f.e. be used to create cache keys for expression-based data queries.
Expression<Func<Person, string>> expression = x => x.Name;
string? str = expression.ToExpressionString();The other extension methods can be used to compose given expressions.
AndCreates anExpressionthat represents an bitwise AND operation.AndAlsoCreates anExpressionthat represents a conditional AND operation that evaluates the second operand only if it has to.OrCreates anExpressionthat represents an bitwise OR operation.OrElseCreates anExpressionthat represents a conditional OR operation that evaluates the second operand only if it has to.