DailyCommonExtensionsApp 2.0.0
dotnet add package DailyCommonExtensionsApp --version 2.0.0
NuGet\Install-Package DailyCommonExtensionsApp -Version 2.0.0
<PackageReference Include="DailyCommonExtensionsApp" Version="2.0.0" />
<PackageVersion Include="DailyCommonExtensionsApp" Version="2.0.0" />
<PackageReference Include="DailyCommonExtensionsApp" />
paket add DailyCommonExtensionsApp --version 2.0.0
#r "nuget: DailyCommonExtensionsApp, 2.0.0"
#:package DailyCommonExtensionsApp@2.0.0
#addin nuget:?package=DailyCommonExtensionsApp&version=2.0.0
#tool nuget:?package=DailyCommonExtensionsApp&version=2.0.0
DailyCommonExtensionsApp
A collection of daily-useful .NET extensions and a flexible SmartLogger for modern .NET applications. This package provides LINQ, Date, and String extensions, as well as a composite logger supporting Sentry and Application Insights providers.
Features
- LINQ Extensions: Enhance LINQ queries with additional utility methods.
- Date Extensions: Simplify date and time manipulations.
- String Extensions: Useful string manipulation helpers.
- SmartLogger: Composite logger supporting multiple providers (Sentry, Application Insights) with easy configuration.
Configuration Management
ConfigurationMergerManager
Merges configuration objects with support for nested properties, collections, and dictionaries. // Example usage var baseConfig = new AppConfig { SettingA = "BaseA", SettingB = "BaseB", Items = new List<string> { "Item1" } }; var clientConfig = new AppConfig { SettingA = "ClientA", Items = new List<string> { "Item2" } };
var merged = ConfigurationMergerManager.MergeConfigurations(baseConfig, clientConfig);
Date Extensions
The DateExtensions
class provides useful methods for working with dates:
// Check if date exists (not null, min, or max)
DateTime? date = DateTime.Now;
bool exists = DateExtensions.IsDateExists(date);
// Check weekend/weekday bool isWeekend = date.Value.IsWeekend(); bool isWeekday = date.Value.IsWeekday();
// Get start/end of day var startOfDay = date.Value.StartOfDay(); // 00:00:00 var endOfDay = date.Value.EndOfDay(); // 23:59:59.999
// Add weekdays var newDate = date.Value.AddWeekdays(5); // Adds 5 working days
// Calculate age int age = birthDate.CalculateAge();
// Get relative time string relative = someDate.ToRelativeTime(); // e.g. "5 minutes ago"
Task Extensions
The TaskExtensions
class provides methods for handling multiple tasks:
// Wait for all tasks in parallel
await tasks.WhenAllAsync();
// Execute tasks sequentially await tasks.WhenAllSequentialAsync();
// Execute tasks in parallel with chunking await tasks.WhenAllParallelAsync(chunkSize: 10);
DataTable Extensions
The DataTableExtensions
class provides methods for working with DataTables:
// Get distinct values from a column
var distinctValues = table.GetDistinctColumnValues<string>("ColumnName");
// Group by with aggregation var grouped = table.GroupByExtension("Category", "Amount", GroupType.Sum);
// Get distinct rows for multiple columns var distinct = table.GetDistinctColumnValues("Column1", "Column2");
Enumerable Extensions
The EnumerableExtensions
class provides LINQ-style extension methods:
// Safe enumeration of null collections
var items = nullableList.OrEmptyIfNull();
// Check if collection has items bool hasItems = collection.HasItems();
// Partition collection based on predicate var (matches, nonMatches) = list.Partition(x ⇒ x > 5);
// Chunk collection into smaller pieces var chunks = list.Chunk(size: 100);
Smart Enum
The SmartEnum<T>
base class provides a type-safe enum alternative:
public abstract class MemberType : SmartEnum<MemberType>
{
public static readonly MemberType Standard = new StandardMember();
public static readonly MemberType Premium = new PremiumMember();
protected MemberType(int value, string name) : base(value, name) { }
}
// Usage var memberType = MemberType.FromName("Premium"); var value = MemberType.Premium.Value;
External Object Injection
The InjectExternalObjectExtensions
provides methods to attach external data to objects:
var key = new ExampleKey { Id = 1, Name = "Key1" };
var value = new ExampleValue { Data = "Sample Data" };
// Set value key.SetValues(value);
// Get value var retrieved = key.GetValues<ExampleKey, ExampleValue>();
// Try get value if (key.TryGetValue<ExampleKey, ExampleValue>(out var existingValue)) { // Use existingValue }
// Remove value key.RemoveValues<ExampleKey, ExampleValue>();
Logging
The LoggingHttpHandler
provides HTTP request/response logging with sensitive data masking:
services.AddHttpClient("MyClient")
.AddHttpMessageHandler<LoggingHttpHandler>();
Requirements
- .NET 9.0 or later
- C# 13.0 or later
Installation
Install via NuGet Package Manager: Install-Package DailyCommonExtensionsApp Or via .NET CLI: dotnet add package DailyCommonExtensionsApp
Usage
Extensions
Import the namespace and use the extension methods directly on your objects: using DailyCommonExtensionsApp.Extensions;
// Example: String extension string input = "example"; bool isNullOrEmpty = input.IsNullOrEmpty();
// Example: Date extension DateTime today = DateTime.Now; bool isWeekend = today.IsWeekend();
// Example: LINQ extension var list = new List<int> { 1, 2, 3 }; var sum = list.SafeSum();
SmartLogger
Configure SmartLogger with your preferred providers in your application's startup: using DailyCommonExtensionsApp.SmartLogger;
var options = new SmartLoggerOptions { EnabledProviders = new List<string> { "Sentry", "AppInsights" }, Sentry = new SentrySettings { Dsn = "<your-dsn>", Debug = true }, AppInsights = new AppInsightsSettings { ConnectionString = "<your-connection-string>" } };
// Register SmartLoggerProvider in DI or logging builder
Example: Registering in ASP.NET Core
builder.Services.AddLogging(logging ⇒ { logging.ClearProviders(); logging.AddProvider(new SmartCompositeLoggerProvider(/* your providers */)); });
SmartLoggerOptions
EnabledProviders
: List of enabled providers (e.g., "Sentry", "AppInsights")Sentry
: SentrySettings (Dsn, Debug)AppInsights
: AppInsightsSettings (ConnectionString)
License
MIT License
Author
Chirag Patel
DailyCommonExtensionsApp API Reference
This document provides an overview of all classes in the DailyCommonExtensionsApp
project, their main functionalities, and sample usage.
EnumExtensions
Functionality: Utility methods for working with enums (get names, values, parse, descriptions, etc).
**Sample Usage:**var names = EnumExtensions.GetNames<MyEnum>(); var values = EnumExtensions.GetValues<MyEnum>(); bool isDefined = MyEnum.Value1.IsDefined(); string desc = EnumExtensions.GetDescription(MyEnum.Value1);
RazorExtensions
Functionality: Extension methods for ASP.NET Core Razor views (conditional partial rendering).
Sample Usage:@await Html.PartialIfElseAsync("_PremiumPartial", "_StandardPartial", Model.IsPremium, Model)
LookupExtensions
Functionality: Extension methods for ILookup<TKey, TElement>
to filter/group by element count.
**Sample Usage:**var lookup = list.ToLookup(x ⇒ x.Key); var exact = lookup.GetKeysWithExactCount(2);
DateExtensions
Functionality: Date and time utility methods (weekend/weekday, start/end of day, add weekdays, etc).
**Sample Usage:**var isWeekend = DateTime.Now.IsWeekend(); var endOfDay = DateTime.Now.EndOfDay();
ConfigurationMergerManager
Functionality: Merge two configuration objects, supporting nested objects, lists, and dictionaries.
**Sample Usage:**var merged = ConfigurationMergerManager.MergeConfigurations(baseConfig, clientConfig);
Common
Functionality: General utility methods (e.g., CSV escaping).
**Sample Usage:**var escaped = Common.Escape("value,with,comma");
TaskExtensions
Functionality: Extensions for working with multiple tasks (parallel, sequential, chunked execution).
**Sample Usage:**await tasks.WhenAllAsync(); await tasks.WhenAllParallelAsync(10);
JsonConvert
Functionality: Custom JSON converters for property ordering (System.Text.Json and Newtonsoft.Json).
Sample Usage:// Use with System.Text.Json or Newtonsoft.Json serialization settings
StringExtensions
Functionality: String and collection formatting, masking, JSON conversion, and more.
**Sample Usage:**var csv = new[] { "a", "b" }.AsCommaSeparatedString(); var masked = "SensitiveData".ToMasked(2, 5);
SmartEnum
Functionality: Type-safe enum pattern with value and name, plus lookup by value/name.
**Sample Usage:**var member = MemberType.FromName("Premium");
EndpointResult, Result, ErrorResult
Functionality: Generic result pattern for API endpoints, with success/error handling.
**Sample Usage:**Result<string, string> result = Result<string, string>.Success("ok"); IResult endpointResult = new EndpointResult<string, string>(result);
GenericResult (Results, Errors, RequestResponseInfo)
Functionality: Generic result wrapper for API responses, with error and request/response info.
**Sample Usage:**var success = Results<string, string>.Success("ok", 200); var failure = Results<string, string>.Failure("error");
DataTableExtensions
Functionality: Extensions for DataTable: distinct values, group by, filtering, CSV export, etc.
**Sample Usage:**var distinct = table.GetDistinctColumnValues("Col1"); var grouped = table.GroupByExtension("GroupCol", "ValueCol", GroupType.Sum);
Coordinates, CoordinatesDistanceExtensions, UnitOfLength
Functionality: Geographical coordinate representation and distance calculation.
**Sample Usage:**var dist = coord1.DistanceTo(coord2, UnitOfLength.Kilometers);
ZipUtilities
Functionality: Download and extract ZIP files with progress.
**Sample Usage:**await ZipUtilities.DownloadZipFileAsync(url, "downloads", null); var files = ZipUtilities.ExtractZipFiles(zipPath, null);
CsvValidatorExtensions
Functionality: Validate CSV headers for required columns and order.
**Sample Usage:**bool valid = header.HasValidColumns(required, true, out var missing, out var orderValid);
InjectExternalObjectExtensions
Functionality: Attach external data to objects at runtime (like dynamic properties).
**Sample Usage:**key.SetValues(value); var v = key.GetValues<ExampleKey, ExampleValue>();
ObjectExtensions
Functionality: Deep clone, property checks, object-to-dictionary, and masked clone.
**Sample Usage:**var clone = obj.DeepClone(); var dict = obj.ToDictionary<string>();
KiotaSerializationExtensions
Functionality: Additional data serialization helpers for objects.
**Sample Usage:**var dict = holder.GetAdditionalDataAsStringDictionary();
LoggingHttpHandler
Functionality: HTTP handler for logging requests/responses with sensitive data masking.
**Sample Usage:**services.AddHttpClient().AddHttpMessageHandler<LoggingHttpHandler>();
More
Other utility classes and records (e.g., GroupType, OrderByClause, RawRange, etc.) are also included for advanced scenarios.
.NET 9.0+ required.
For more details, see the source code and XML documentation in each file.
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 was computed. 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. |
-
net9.0
- Microsoft.AspNetCore.Html.Abstractions (>= 2.3.0)
- Microsoft.AspNetCore.Mvc.Razor (>= 2.3.0)
- Microsoft.AspNetCore.Razor.Runtime (>= 2.3.0)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.7)
- Microsoft.Extensions.Logging (>= 9.0.7)
- Microsoft.Extensions.Logging.ApplicationInsights (>= 2.23.0)
- Microsoft.Extensions.Options (>= 9.0.7)
- MinimalApis.Extensions (>= 0.11.0)
- Newtonsoft.Json (>= 13.0.3)
- OpenTelemetry (>= 1.12.0)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.12.0)
- Sentry (>= 5.11.2)
- Sentry.Extensions.Logging (>= 5.11.2)
- System.Collections (>= 4.3.0)
- System.Text.RegularExpressions (>= 4.3.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.