Maestria.Extensions 3.3.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Maestria.Extensions --version 3.3.0                
NuGet\Install-Package Maestria.Extensions -Version 3.3.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Maestria.Extensions" Version="3.3.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Maestria.Extensions --version 3.3.0                
#r "nuget: Maestria.Extensions, 3.3.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Maestria.Extensions as a Cake Addin
#addin nuget:?package=Maestria.Extensions&version=3.3.0

// Install Maestria.Extensions as a Cake Tool
#tool nuget:?package=Maestria.Extensions&version=3.3.0                

Maestria.Extensions

Build status NuGet MyGet Apimundo

Build History

donate

What is Maestria.Extensions?

Extension function pack to increase productivity and improve source code writing. By default, all extension methods are safe.

What is Maestria Project?

This library is part of Maestria Project.

Maestria is a project to provide productivity and elegance to your source code writing.

Where can I get it?

First, install NuGet. Then, install Maestria.Extensions from the package manager console:

PM> Install-Package Maestria.Extensions

or install from the dotnet cli command line:

> dotnet add package Maestria.Extensions

How do I get started?

First, import "Maestria.Extensions" reference:

using Maestria.Extensions;

Then in your application code, use fluent syntax

// AggregateExtenions
<Array>.Max();
<Array>.Min();

// Base64Extensions
<byte[]>.ToBase64(<byte[]>)
<string>.ToBase64(<string>, <Encoding>)

var decoded = <byte[]>.FromBase64(<encoded-byte[]>, <Encoding>)
var decoded = <string>.FromBase64(<encoded-string>, <Encoding>)

// CollectionExtensions
<IEnumerable>.IsNullOrEmpty()
<IEnumerable>.HasItems()
<IDictionary>.TryGetValue(<key>, <@default-value>)
<IEnumerable>.Iterate(item => <action>)
await <IEnumerable>.Iterate(async item => await <action>)
<IEnumerable>.Iterate((item, index) => <action>)
await <IEnumerable>.Iterate(async (item, index) => await <action>)

// EnumExtensions
<Enum>.GetDisplayName()
<Enum>.GetDescription()
EnumExtensions.GetValues<TEnum>()
EnumExtensions.GetValues(typeof(<TEnum>))

// ExceptionExtensions
<Exception>.GetAllMessages()
<Exception>.GetMostInner()

// HashExtensions
"value".GetHashMd5()
"value".GetHashSha1()
"value".GetHashSha256()
"value".GetHashSha384()
"value".GetHashSha512()
HashExtensions.ComputeHash(<HashAlgorithm>, "value")

// RoundExtensions
<floating-point>.Round(<digits>)
<floating-point>.Round(<digits>, <MidpointRounding>)
<floating-point>.RoundUp(<digits>)

// TruncateExtensions
<floating-point>.Truncate(<digits>)

// StringExtensions
<string>.TrimStart(<start-comparison>, <ignore-case>)
<string>.TrimEnd(<start-comparison>, <ignore-case>)
<string>.AddToBeginningIfNotStartsWith(<start-comparison>, <ignore-case>)
<string>.AddToBeginningIfHasValue(<start-comparison>, <prefix>)
<string>.AddToEndIfNotEndsWith(<start-comparison>, <ignore-case>)
<string>.AddToEndIfHasValue(<start-comparison>, <prefix>)
<string>.EscapeXml()
<string>.Format(<values-to-format>)
<string>.IsNullOrEmpty()
<string>.IsNullOrWhiteSpace()
<string>.EmptyIf(<string>)
<string>.EmptyIfNull()
<string>.EmptyIfNullOrWhiteSpace()
<string>.HasValue() // Check if text is not null and not white space
<string>.EqualsIgnoreCase(<camparison-value>, <auto-trim>)
<string>.OnlyNumbers()
<string>.RemoveAccents()
<string>.Join(<separator>)
<string>.SubstringBeforeFirstOccurrence("-")
<string>.SubstringBeforeLastOccurrence("-")
<string>.SubstringAfterFirstOccurrence("-")
<string>.SubstringAfterLastOccurrence("-")
<string>.SubstringAtOccurrenceIndex("-", 1)
<string>.SubstringSafe(<start-index>, <length>)
<string>.LimitLen(<length>)
<string>.LimitLenReverse(<length>)
<string>.OnlyLettersOrNumbersOrUnderscoresOrHyphensTest(<string>)
<string>.ToSnakeCase()

// Guid
<Guid>.IsEmpty()
<Guid?>.IsNullOrEmpty()
<string>.IsNullOrWhiteSpace()
<Guid>.IfEmpty(<value>)
<Guid?>.IfNullOrEmpty(<value>)

// SyntaxExtensions
<object>.IsNull()
<object>.HasValue() or <object>.IsNotNull() // Same result
<object>.In(<array-of-values>)
<IComparable>.Between(<starting-value>, <ending-value>)
<IComparable>.LimitMaxAt(<max-value>)
<IComparable>.LimitMinAt(<min-value>)

// Pipelines
var value = <string>
    .OnlyNumbers()
    .DetachedCall(x => Console.WriteLine(x)) // <<< Call a method with current value and continue execution pipeline
    .Format("mask"); // value is only the number of string formatted and only numbers are written on console

<string>
    .OnlyNumbers()
    .OutVar(out var variableToExternalFromScopeAccess) // <<< Create variable with current value on external scope and continua execution pipeline
    .Format("mask"); // value is only the number of string formatted and only numbers are written on console

If fluent expressions

It's possible to execute fluent comparisons expression with the syntax: <value>.IfGreater(<value-to-compare>).Then(<result-if-compare-is-true>).

The methods for comparison operations are: IfGreater, IfGreaterOrEqual, IfLest. IfLessOrEqual, If and IfNot.

Rules:

  • When condition it's false, result the pipeline is <value>.
  • When <value> or <value-to-compare> is null:
    • Result only true if both are null and comparison is equality operation If.
    • When an only value is null, the result is true if the operation is not equality comparison IfNot.
    • When <value> is Nullable<>, <result-if-compare-is-true> always if Nullable<> data type.
    • But when <value> is not Nullable<>, <result-if-compare-is-true> allow use Nullable<> and not Nullable<> data type.
    • All other operations comparisons result in false.
  • It's possible return null value at <result-if-compare-is-true>, but then indicated syntax is <value>.NullIf(<value-to-compare>).

Examples:

<IComparable>.IfGreater(10).Then(5)
<IComparable>.IfGreaterOrEqual(10).Then(5)
<IComparable>.IfLest(10).Then(5)
<IComparable>.IfLessOrEqual(10).Then(5)
<IComparable>.If(10).Then(5)
<IComparable>.IfNot(10).Then(5)

Delegates expression only executes when the condition it's true.

<IComparable>.IfGreater(10).Then(() => 5)
<IComparable>.IfGreaterOrEqual(10).Then(() => 5)
<IComparable>.IfLest(10).Then(() => 5)
<IComparable>.IfLessOrEqual(10).Then(() => 5)
<IComparable>.If(10).Then(() => 5)
<IComparable>.IfNot(10).Then(() => 5)

Other fluent comparison operations:

// IfNullExtensions
<object>.IfNull(<output-value-when-null>)
<string>.IfNullOrEmpty(<output-value-when-null-or-empty-string>)
<string>.IfNullOrWhiteSpace(<output-value-when-null-or-empty-white-space>)

// NullIfExtensions
<object>.NullIf(<comparison-value>)
<floating-point>.NullIf(<comparison-value>, <tolerance-to-comparasion>)

<string>.NullIf(<comparison-value>, <ignore-case>)
<string>.NullIfEmpty(<comparison-value>)
<string>.NullIfWhiteSpace(<comparison-value>)

<IComparable>.NullIfIn(<comparison-value>)
<IComparable>.NullIfBetween(<comparison-value>)

Data Types

ISimpleResult, SimpleResult and SimpleResult< TValue>

This structure has success and message for simple method result, extensible with generic TValue on "Value" property.

SimpleResult ok = SimpleResult.Ok(<optional-message>);
SimpleResult fail = SimpleResult.Fail("Fail message");

// Implict conversions
SimpleResult ok = true;
SimpleResult fail = "Fail message"
SimpleResult fail = new Exception("Fail message")


// Initializer
var result = new SimpleResult
{
    Success = true,
    Message = "Successfully processed"
}

To improve then development experience, there are implicit conversions to assign data from:

  • bool: To set or verify property Success.
  • string: To set fail message and Success to false.
  • Exception: To set fail message, Exception and Success to false.
  • TValue: To set value and Success to true (Even if null).

And implicit conversions to assingn data to:

  • bool:
    • SimpleResult: Get data from property Success.
    • SimpleResult<TValue>: Get data from property Success
  • Exception: Get data from property Exception
  • TValue: Get data from property Value

The property SuccessAndHasValue check if Success == true and Value != null in SimpleResult<TValue>.

Caution on SimpleResult<TValue>: Implicit comparison if (mySimpleResultVariable) is equivalent to if (mySimpleResultVariable.Success).
Use explicit if (mySimpleResultVariable.SuccessAndHasValue) when result value can be null with success is true

Use cases:

public SimpleResult Execute(Args args)
{
    if (args == null)
        return "Argument cannot be null";  // <===== Implicit cast to failure result
    try
    {
        // Execute actions
        return true; // <===== Implicit cast success result
    }
    catch (Exception e)
    {
        return e; // <===== Implicit cast to failure result
    }
}

public SimpleResult<int> Execute2(Args args)
{
    if (args == null)
        return "Argument cannot be null";  // <===== Implicit cast to failure result
    try
    {
        // Execute actions
        return 10; // <===== Implicit cast success result
    }
    catch (Exception e)
    {
        return e; // <===== Implicit cast to failure result
    }
}

// ...

var result = Execute(...);
var result2 = Execute2(...);

if (result && result2) // <===== Implicit cast to boolean
{
    // ...
}


Try<TSuccess, TFailure>

Auxiliary data type to increment the expressibility of method results when success and failure need different structures.
To facilitate development there is support for implicit conversion.

public void Try<PersonCreated, CustomError> Save(Person value) 
{
    ...
    if (condition)
        return new CustomError() { Code = 999, Message = "Failure message" }
    return new PersonCreated { Id = 123 };
}

...

var result = Save(person);
if (result)
    Console.WriteLine(result.Value.Id);
else
    Console.WriteLine($"Error {result.Failure.Code}: {result.Failure.Message}");

Settings

It's possible set default settings for library:

Extensions.GlobalSettings.Configure(cfg => cfg
    .FloatAndDoubleTolerance(default-float-and-double-comparasion-tolerance) // Default is 0.00001f

Development Guidelines

  • Create file with extensions method name
  • this argument name must be value for single object or values to IEnumerable inheritances
  • Put new file into folder /src/Extensions/<extended-data-type>
    • Expressions methods like If, NullIf, Is, In, EmptyIf, Between, must be located in src/Extensions/Comparable folder
    • Numbers extensions methods must bet located in src/Extensions/Number
  • The I prefix for interfaces must be omitted from the folder name.
  • src\Settings\MaestriaExtensionSettings: File to configure global defaults behaviors

buy-me-a-coffee smile.png

If my contributions helped you, please help me buy a coffee 😄

donate

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.5.0 1,764 1/26/2024
3.4.2 9,346 11/9/2022
3.4.1 345 11/9/2022
3.4.0 335 11/9/2022
3.3.2 1,091 10/7/2022
3.3.1 805 9/12/2022
3.3.0 417 9/12/2022
3.2.3 734 8/27/2022
3.2.2 417 8/26/2022
3.2.1 409 8/26/2022
3.2.0 2,704 5/31/2022
3.1.3 6,912 11/24/2021
3.1.2 539 11/3/2021
3.1.0 842 9/8/2021
3.0.2 376 9/8/2021
3.0.1 4,714 8/4/2021
3.0.0 435 8/4/2021
2.1.4 1,613 7/5/2021
2.1.3 657 6/22/2021
2.1.2 458 6/20/2021
2.1.1 470 6/7/2021
2.1.0 495 6/4/2021
2.0.13 418 6/1/2021
2.0.12 550 5/25/2021
2.0.11 411 5/20/2021
2.0.10 396 5/16/2021
2.0.9 380 5/4/2021
2.0.8 473 4/4/2021
2.0.7 341 4/3/2021
2.0.6 364 4/2/2021
2.0.5 389 3/28/2021
2.0.4 385 3/28/2021
2.0.3 425 3/27/2021
2.0.2 442 3/27/2021
2.0.1 458 3/19/2021
2.0.0 351 3/19/2021
1.2.5 482 3/14/2021
1.2.4 458 1/10/2021
1.2.3 444 1/10/2021
1.2.2 560 9/1/2020
1.2.1 492 8/14/2020
1.2.0 569 8/9/2020
1.1.1 580 7/28/2020
1.1.0 570 7/12/2020
1.0.10 494 4/19/2020
1.0.9 509 4/14/2020
1.0.8 494 4/14/2020
1.0.7 630 4/11/2020
1.0.6 647 12/20/2019
1.0.5 632 12/16/2019
1.0.4 541 12/16/2019
1.0.3 506 11/25/2019
1.0.2 499 11/18/2019
1.0.1 586 10/14/2019
1.0.0 576 10/9/2019