YamatoDaiwa.CSharpExtensions
0.9.0
dotnet add package YamatoDaiwa.CSharpExtensions --version 0.9.0
NuGet\Install-Package YamatoDaiwa.CSharpExtensions -Version 0.9.0
<PackageReference Include="YamatoDaiwa.CSharpExtensions" Version="0.9.0" />
<PackageVersion Include="YamatoDaiwa.CSharpExtensions" Version="0.9.0" />
<PackageReference Include="YamatoDaiwa.CSharpExtensions" />
paket add YamatoDaiwa.CSharpExtensions --version 0.9.0
#r "nuget: YamatoDaiwa.CSharpExtensions, 0.9.0"
#:package YamatoDaiwa.CSharpExtensions@0.9.0
#addin nuget:?package=YamatoDaiwa.CSharpExtensions&version=0.9.0
#tool nuget:?package=YamatoDaiwa.CSharpExtensions&version=0.9.0
Yamato Daiwa CS(harp) extensions

The extensions of the standard classes
DateOnly
DateOnly CreateDateOnlyFromISO8601_String(string ISO8601_String)string ToISO8601_String()
DateTime
DateOnly CreateDateOnlyFromISO8601_String(string ISO8601_String)string ToISO8601_String()
EmailAddress
Public static fields
| Name | VALID_PATTERN |
| Type | Regex |
| Is readonly | Yes |
Contains the regular expression of the valid email address according w3resource.com.
Public static methods
bool IsValid(string potentialEmail)
Array
TElement[] LogEachElement<TElement>(Action<TElement>? logger = null)
Content
System.Threading.Tasks.Task<ResponseData> ReadExpectedToBeNonEmptyFromJsonAsync<ResponseData>(this System.Net.Http.HttpContent self)
Dictionary
Dictionary<TKey, TValue> SetPair(TKey key, TValue value)Dictionary<TKey, TValue> SetPairs(Dictionary<TKey, TValue> pairs)Dictionary<TKey, TValue> SetPairIfValueIsNotNull(TKey key, TValue? value)SetPairIfDictionary<TKey, TValue> SetPairIf<TKey, TValue>(TKey key, TValue value, bool condition) where TKey : notnullDictionary<TKey, TValue> SetPairIf<TKey, TValue>(TKey key, TValue value, Func<TKey, TValue, bool> condition) where TKey : notnull
DeletingOfOnePairByKey.Result<TKey, TValue> DeleteOnePairByKey(TKey key)DeletingOfOnePairByKey.Result<TKey, TValue> DeleteOnePairFromSwallowCopy(TKey key)
List
List<TElement> AddElementsToStart<TElement> (params TElement[] newElements)List<TElement> AddElementsToEnd<TElement> (params TElement[] newElements)List<TElement?> AddElementToEndIfNotNull<TElement>(TElement? newElement)AddElementToEndIfList<TElement> AddElementToEndIf<TElement>(TElement newElement, bool condition)List<TElement> AddElementToEndIf<TElement>(TElement newElement, Func<TElement?, bool> condition)
StringifyEachElementAndJoin<TElement>(string separator)ReplaceArrayElementsByPredicateList<TElement> ReplaceArrayElementsByPredicate<TElement>(Func<TElement, bool> predicate, TElement newElement, bool mustReplaceOnlyFirstOne)List<TElement> ReplaceArrayElementsByPredicate<TElement>(Func<TElement, bool> predicate, Func<TElement, TElement> replacer, bool mustReplaceOnlyFirstOne)
List<TElement> LogEachElement<TElement>(Action<TElement>? logger = null)
Number
bool IsValueOfAnyNumericType(object value)
String
bool IsNonEmpty()string ToUpperCamelCase()string ToLowerCamelCase()string RemoveAllSpecifiedCharacters(char[] charactersToRemove)
System.Text.Json.Nodes.JsonObject
JsonObject SetProperty(string dotSeparatedPath, object value)JsonObject SetProperties(Dictionary<string, object> dotSeparatedPathsAndValues)
Random values generators (RandomValuesGenerator class)
bool GetRandomBoolean()byte GetRandomByte(byte minimalValue = Byte.MinValue, byte maximalValue = Byte.MaxValue)ushort GetRandomUShort(ushort minimalValue = ushort.MinValue, ushort maximalValue = ushort.MaxValue)TArrayElement GetRandomArrayElement<TArrayElement>(TArrayElement[] targetArray)DateOnly GetRandomDate(DateOnly earliestDate, DateOnly latestDate)DateTime GetRandomDateTime(DateOnly earliestDate, DateOnly latestDate)
RegexExtensions
ReplaceMatchesWithRegularExpressionToDynamicValue method
Replaces matches in a string using a regular expression and a dynamic replacer delegate. This method is particularly useful when the replacement string depends on the content of capturing groups or the position of the match.
Example 1: Using named capturing groups
This example demonstrates how to convert Markdown-style links into HTML anchor tags using named capturing groups.
const string sample = "Meta description is [very important](https://www.orange-sha.co.jp/blog/web01_description/) for SEO.";
string result = RegexExtensions.ReplaceMatchesWithRegularExpressionToDynamicValue(new RegexExtensions.ReplacingOfMatchesWithRegularExpressionToDynamicValue.CompoundParameter
{
targetString = sample,
regularExpressionWithCapturingGroups = new Regex(@"\[(?<anchorText>.+?)\]\((?<URI>.+?)\)"),
replacer = matching => $"<a href=\"{ matching.namedCapturingGroups["URI"] }\">{ matching.namedCapturingGroups["anchorText"] }</a>"
});
// Result: Meta description is <a href="https://www.orange-sha.co.jp/blog/web01_description/">very important</a> for SEO.
Example 2: Using numbered capturing groups
This example shows how to use index-based capturing groups to reformat text.
const string sample = "Item 1: 100, Item 2: 200";
string result = RegexExtensions.ReplaceMatchesWithRegularExpressionToDynamicValue(new RegexExtensions.ReplacingOfMatchesWithRegularExpressionToDynamicValue.CompoundParameter
{
targetString = sample,
regularExpressionWithCapturingGroups = new Regex(@"Item (\d+): (\d+)"),
replacer = matching => $"({matching.numeratedCapturingGroups[1]})={matching.numeratedCapturingGroups[2]}"
});
// Result: (1)=100, (2)=200
Associated Records and Delegates
CompoundParameter record
Encapsulates the input data for the replacement operation.
| Property | Type | Description |
|---|---|---|
targetString |
string |
The string to search for matches. |
regularExpressionWithCapturingGroups |
Regex |
The regular expression to use. |
replacer |
Replacer |
The delegate that generates the replacement string. |
Replacer delegate
A function that takes a Matching object and returns a string?. If it returns null, the original match is preserved.
public delegate string? Replacer(Matching matching);
Matching record
Provides detailed information about a specific match.
| Property | Type | Description |
|---|---|---|
fullMatching |
string |
The complete text of the match. |
positionIndex |
int |
The zero-based starting position of the match. |
namedCapturingGroups |
Dictionary<string, string?> |
Values of named groups (e.g., (?<name>...)). |
numeratedCapturingGroups |
Dictionary<int, string?> |
Values of numbered groups (e.g., (...)). |
Data mocking
DataMocking class
NullablePropertiesDecisionStrategies enumeration
| Enumeration element | Description |
|---|---|
mustGenerateAll |
All nullable (optional) properties must be generated except the cases of incompatible properties. |
mustGenerateWith50PercentageProbabilityIfHasNotBeenPreDefined |
Nullable (optional) properties must be generated with 50% probability. |
mustSkipIfHasNotBeenPreDefined |
Nullable (optional) properties must not be randomly generated. |
DecideOptionalValue static method and NullablePropertiesDecisionSourceDataAndOptions structure
TValueType? DecideOptionalValue<TValueType>(NullablePropertiesDecisionSourceDataAndOptions<TValueType> sourceDataAndOptions)
struct NullablePropertiesDecisionSourceDataAndOptions<TPropertyType>
{
public required NullablePropertiesDecisionStrategies Strategy { get; init; }
public required Func<TPropertyType> RandomValueGenerator? { get; init; }
public TPropertyType? PreDefinedValue { get; init; }
}
Decides, will nullable (optional) value be available or no, and if yes, returns this value. Intended to be used when generating the properties for the class / structure.
The decision will depend mainly on specified nullable property decision strategy:
| Enumeration element | Description |
|---|---|
mustGenerateAll |
If target nullable property has not been predefined via NullablePropertiesDecisionStrategies.PreDefinedValue, it will be generated by specified RandomValueGenerator. It means the RandomValueGenerator must be specified for this strategy, otherwise ArgumentException will be thrown. |
mustGenerateWith50PercentageProbabilityIfHasNotBeenPreDefined |
If target nullable property has been predefined via NullablePropertiesDecisionStrategies.PreDefinedValue, this value will be returned otherwise will be generated by specified RandomValueGenerator with probability 50%. It means the RandomValueGenerator must be specified for this strategy, otherwise ArgumentException will be thrown. |
mustSkipIfHasNotBeenPreDefined |
If target nullable property has not been predefined via NullablePropertiesDecisionStrategies.PreDefinedValue, no random value will be generated. Only for the strategy RandomValueGenerator should be omitted. |
Errors classes
| Error class | Usage |
|---|---|
DataRetrievingFailedException |
Intended to be used when the data retrieving from some external resource (server, database, file, etc.) failed. |
DataSubmittingFailedException |
Intended to be used when the data submitting to any external resource (server, database, etc.) failed. |
DataRetrievingFailedException
- Constructor
DataRetrievingFailedException(string message)DataRetrievingFailedException(string message, Exception innerException)DataRetrievingFailedException(string messageSpecificPart, HttpResponseMessage response, object? responseData)
- Public static Methods
async Task<object?> TryToExtractResponseDataForLogging(HttpResponseMessage response)
MockGatewayHelper class
When mock the asynchronous data transactions, takes care about such routines as
- Randomizing of the pending interval
- Simulation of the error
- Logging
Public static methods
SetLogger
void SetLogger(Log log)
delegate void Log(string message)
Adds the logging method which will be invoked if the logging will be demanded in other methods.
SimulateDataRetrieving
Task<TResponseData> SimulateDataRetrieving<TRequestParameters, TResponseData>(
TRequestParameters requestParameters,
Func<TResponseData> getResponseData,
SimulationOptions options
)
where the SimulationOptions is the associated structure will be described below.
SimulateDataSubmitting
Task<TResponseData> SimulateDataSubmitting<TRequestData, TResponseData>(
TRequestData requestData,
Func<TResponseData> getResponseData,
SimulationOptions options
)
It's behaviour is almost even with SimulateDataRetrieving, but there are some differences:
- The logging
DataSubmittingFailedExceptionwill be thrown instead ofDataRetrievingFailedExceptionwhen error simulation mode is enabled.
Associated structure SimulationOptions
public struct SimulationOptions
{
public ushort? MinimalPendingPeriod__Seconds { get; init; }
public ushort? MaximalPendingPeriod__Seconds { get; init; }
public bool MustSimulateError { get; init; }
public bool MustLogResponseData { get; init; }
public required string GatewayName { get; init; }
public required string TransactionName { get; init; }
}
MinimalPendingPeriod__Seconds
| Type | ushort |
| Default value | 1 |
| Use case | If you want to see the loading placeholder for a while, increase this value. |
MaximalPendingPeriod__Seconds
| Type | ushort |
| Default value | 2 |
| Use case | If you want to see the loading placeholder for a while, increase this value. |
MustSimulateError
| Type | bool |
| Default value | false |
| Use case | If you want to check is the error message displays correctly in your GUI, set this flag to true. |
MustSimulateError
| Type | bool |
| Is required | Yes |
MustLogResponseData
| Type | bool |
| Is required | Yes |
| Note | System.Text.Json.JsonSerializer will be used for serializing. |
GatewayName
| Type | bool |
| Is required | Yes |
| Note | Used for logging only. "Gateway" could be called "service" or somehow else in your code. |
TransactionName
| Type | bool |
| Is required | Yes |
| Note | Used for logging only. |
URI_Builder
Provides a simple way to construct URIs with query parameters.
Build method
public static string Build(URI_Builder.SourceData sourceData)
Constructs a URI string based on the provided SourceData.
Example 1: Origin and path with query parameters
string result = URI_Builder.Build(new URI_Builder.SourceData
{
origin = "https://example.com",
path = "/search",
queryParameters = new Dictionary<string, object>
{
{ "q", "dotnet" },
{ "lang", "en" }
}
});
// Result: https://example.com/search?q=dotnet&lang=en
Example 2: Origin only
string result = URI_Builder.Build(new URI_Builder.SourceData
{
origin = "https://example.com"
});
// Result: https://example.com
Example 3: Numeric and Boolean query parameters
string result = URI_Builder.Build(new URI_Builder.SourceData
{
origin = "https://example.com",
queryParameters = new Dictionary<string, object>
{
{ "id", 123 },
{ "active", true },
{ "deleted", false }
}
});
// Result: https://example.com?id=123&active=true
// Note: Currently, only 'true' boolean values are included in the query string.
Associated record SourceData
public record SourceData
{
public string? origin { get; init; }
public string? path { get; init; }
public Dictionary<string, object>? queryParameters { get; init; }
}
origin
The base part of the URI (e.g., https://example.com).
path
The path part of the URI (e.g., /api/v1/users).
queryParameters
A dictionary containing query parameters. Supported value types are string, numeric types, Enum, and true boolean.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (3)
Showing the top 3 NuGet packages that depend on YamatoDaiwa.CSharpExtensions:
| Package | Downloads |
|---|---|
|
YamatoDaiwa.Frontend
The adaptation of the "Yamato Daiwa Frontend" toolkit for the Blazor framework |
|
|
YamatoDaiwa.PugCSharpStaticPreview
The class for the generating of the string resources for the Pug static preview basing on CSharp logic |
|
|
YamatoDaiwa.CSharpExtensions.Localizations.Japanese
The Japanese localization for "Yamato Daiwa CS(harp) Extensions" library. |
GitHub repositories
This package is not used by any popular GitHub repositories.