Atc 4.3.0

dotnet add package Atc --version 4.3.0
                    
NuGet\Install-Package Atc -Version 4.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="Atc" Version="4.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Atc" Version="4.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Atc" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Atc --version 4.3.0
                    
#r "nuget: Atc, 4.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.
#:package Atc@4.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Atc&version=4.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Atc&version=4.3.0
                    
Install as a Cake Tool

Atc

Target Frameworks: netstandard2.0, net10.0

The foundation library for .NET development, providing a comprehensive collection of common utilities, extension methods, and helpers. Multi-targeting ensures compatibility with a wide range of .NET applications, from .NET Framework 4.7.2+ to the latest .NET versions.

Why Use This Library?

Atc eliminates boilerplate code and provides battle-tested implementations for common tasks. Instead of writing the same utility code in every project, Atc provides:

  • Rich Extension Methods: Extensions for all common .NET types (String, DateTime, Enum, Collections, etc.)
  • Logging Utilities: Structured logging helpers for ILogger
  • Data Structures: Specialized collections and data structures
  • Serialization Helpers: JSON serialization utilities with sensible defaults
  • Math & Geometry: Math operations, geospatial calculations, and coordinate systems
  • Networking Helpers: Network information and IP address utilities

Perfect for:

  • Reducing boilerplate in business applications
  • Standardizing common operations across projects
  • Improving code readability with expressive extension methods
  • Building reusable libraries

Installation

dotnet add package Atc

Target Frameworks

  • .NET Standard 2.0
  • .NET 10.0

The library multi-targets to provide broad compatibility with:

  • .NET Framework 4.7.2+
  • .NET Core 2.1+
  • .NET 5+
  • .NET 10.0

Key Dependencies

  • Microsoft.Extensions.Logging.Abstractions
  • System.Text.Json
  • System.ComponentModel.Annotations
  • Meziantou.Polyfill (for backward compatibility)

Main Components

Extension Methods (Extensions/)

Organized by category:

  • BaseTypes: String, Int, Double, Bool, Enum, DateTime, TimeSpan
  • Collections: List, Dictionary, IEnumerable, Array
  • Reflection: Type, Assembly, MethodInfo
  • Serialization: JSON serialization helpers
  • Stream: Stream and byte array operations

Logging (Logging/)

  • ILogger extensions for structured logging
  • LogKeyValueItem for key-value pair logging
  • LogItemFactory for creating log items
  • FileLoggerProvider and builder.AddFile(file) for a simple append-only log file

Math & Geometry (Math/)

  • MathEx: Extended math operations, including TrySolveLinearSystem for 2 x 2 systems
  • GeoSpatial calculations and coordinates
  • Cartesian and geographic coordinate systems
  • 2-D geometry for plans and drawings: Point2D/Point3D vector maths (operators, Length, Normalize, Dot, Cross, Rotate, IsNear, SnapToGrid), LineSegment2D, Arc2D, BoundingBox2D/BoundingBox3D, Transform2D, IntersectionHelper, arc helpers on CircleHelper, plus SlopeHelper, ClothoidHelper, CubicBezier2D and HelixHelper
  • Length units: LengthUnitType (metric and imperial), MeasurementSystemType, exact conversions in LengthUnitTypeHelper, and a culture-aware LengthFormatter
  • Angle helpers on MathHelper: NormalizeDegrees, DegreesDifference, AreDegreesEqual, Atan2Degrees, IsEquals with a tolerance and SnapToGrid

Helpers

  • NetworkInformationHelper: Network connectivity and IP address utilities
  • JsonSerializerOptionsFactory: Preconfigured JSON serialization options

Data Structures

  • Specialized collections
  • Custom data structures for common scenarios

Resources

Localized resources for:

  • English (default)
  • Danish (da-DK)
  • German (de-DE)

Code Documentation

Examples

ILogger examples

Using logger.LogKeyValueItems(..)

    // Collect data
    var logItems = new List<LogKeyValueItem>
        {
            new LogKeyValueItem(LogCategoryType.Error, "Key1", "Error1"),
            new LogKeyValueItem(LogCategoryType.Warning, "Key2", "Warning1"),
            new LogKeyValueItem(LogCategoryType.Information, "Key3", "Information1"),
            LogItemFactory.CreateError("Key4", "Error2"),
            LogItemFactory.CreateWarning("Key5", "Warning2"),
            LogItemFactory.CreateInformation("Key6", "Information2"),
        };

    // Log data
    logger.LogKeyValueItems(logItems);

Using logger.LogKeyValueItem(..)

    // Collect data
    var logItem = LogItemFactory.CreateError("Key1", "Error1");

    // Log data
    logger.LogKeyValueItem(LogItemFactory.CreateError(logItem));

TimeSpanExtensions examples

Using GetPrettyTime() or GetPrettyTime(decimalPrecision)

The default value for decimalPrecision is 3.

var stopwatch = Stopwatch.StartNew();

DoSomthingThatTakesLongTime();

stopwatch.Stop();

Console.WriteLine($"Running time: {stopwatch.Elapsed.GetPrettyTime()}");

Result format could look like:

Running time: 14,015 sec
Running time: 13,234 min
Running time: 12,213 hours

NetworkInformationHelper examples

Using HasConnection()

This helper method ask a external internet service (GoogleDNS ping), to see it there is connection.

bool hasConnection = NetworkInformationHelper.HasConnection()

Using GetPublicIpAddress()

This helper method ask a external internet service (ipify.org), to get the external ip address.

IPAddress? ipAddress = NetworkInformationHelper.GetPublicIpAddress()

Telling local addresses from remote ones

IPAddress.Parse("192.168.1.10").IsPrivate();        // true (also 10/8, 172.16/12 and IPv6 fc00::/7)
IPAddress.Parse("8.8.8.8").IsRemoteAddress();       // true: not loopback, private, link-local or CGNAT
"localhost".IsRemoteHost();                         // false
"api.example.com".IsRemoteHost();                   // true (no DNS lookup is made)

String Extension Examples

Using EnsureFirstCharacterToUpper()

string result = "hello world".EnsureFirstCharacterToUpper();
// Result: "Hello world"

Using IsDigit(), IsNumeric(), and Validation Extensions

bool isDigit = "12345".IsDigit();                    // true
bool isNumeric = "123.45".IsNumeric();                // true
bool isEmail = "user@example.com".IsEmailAddress();   // true
bool isGuid = "550e8400-e29b-41d4-a716-446655440000".IsGuid(); // true

Using Truncate()

string longText = "This is a very long text that needs truncation";
string short = longText.Truncate(20);
// Result: "This is a very lo..."

Using ToTitleCase() and ToPascalCase()

string title = "hello world".ToTitleCase();    // "Hello World"
string pascal = "hello world".ToPascalCase();  // "HelloWorld"
string camel = "HelloWorld".ToCamelCase();     // "helloWorld"

Using TrimToNull()

string? a = "  Main Street  ".TrimToNull();  // "Main Street"
string? b = "   ".TrimToNull();              // null - nothing left, so treat it as not set
string? c = ((string?)null).TrimToNull();    // null

Using SplitIntoWords() and ToCasingStyle()

// Splits at separators, case changes and acronym ends - any input style works.
var words = "XMLParser.v2".SplitIntoWords();               // ["XML", "Parser", "v2"]

"getPetById".ToCasingStyle(CasingStyle.PascalCase);         // "GetPetById"
"XMLParser".ToCasingStyle(CasingStyle.CamelCase);           // "xmlParser"
"MyPetStore".ToCasingStyle(CasingStyle.KebabCase);          // "my-pet-store"
"my-pet-store".ToCasingStyle(CasingStyle.SnakeCase);        // "my_pet_store"
"myPetStore".ToCasingStyle(CasingStyle.UpperSnakeCase);     // "MY_PET_STORE"

Picking values out of command output and log lines

"Firmware: [2.4.1] ok".TryGetBetween("[", "]", out var version);   // true, "2.4.1"
"key=value=more".GetAfter("=");                                     // "value=more"
"Hello\n-- \nSignature".TruncateAt("\n-- ");                        // "Hello"
"\u001b[32mOK\u001b[0m".RemoveAnsiEscapeSequences();                // "OK"
"updated:2025-01-01T10:00".TryParseKeyValue(':', out var key, out var value);
                                                                    // key "updated", value "2025-01-01T10:00"
"Main Street 8".ContainsAll(["main", "8"], StringComparison.OrdinalIgnoreCase);  // true

Retry, paging and locking helpers

Deciding whether to retry

catch (Exception ex) when (ex.IsTransientNetworkError())
{
    // SocketException, TimeoutException, an I/O error, or an HttpRequestException
    // without a status code or with 408, 429, 500, 502, 503 or 504 - anywhere in the chain.
}

response.StatusCode.IsTransient();                         // true for 408, 429, 500, 502, 503, 504
ex.FindInnerException<SqlException>();                     // first match in the chain, or null

Turning a paged API into one stream with AsyncEnumerableFactory

// Numbered pages
var devices = AsyncEnumerableFactory.FromPages(
    (page, ct) => client.GetDevicesAsync(page, pageSize: 100, ct),
    page => page.Items,
    (page, number) => number + 1 < page.TotalPages);

// Continuation tokens
var blobs = AsyncEnumerableFactory.FromContinuationPages(
    (token, ct) => client.ListBlobsAsync(token, ct),
    page => page.Items,
    page => page.ContinuationToken);

await foreach (var device in devices)
{
    // pages are fetched one at a time, as they are needed
}

Using SemaphoreSlim.LockAsync()

private readonly SemaphoreSlim gate = new(1, 1);

using (await gate.LockAsync(cancellationToken))
{
    // one caller at a time; released even if this throws
}

using var handle = await gate.TryLockAsync(TimeSpan.Zero);
if (handle is null)
{
    return "Busy, try again later.";
}

Building URLs and reading embedded resources

new Uri("https://example.com/items?sort=name#top").WithQueryString("page", "2");
    // https://example.com/items?sort=name&page=2#top

var html = typeof(Program).Assembly.ReadManifestResourceAsString("Templates.Mail.html");
    // a missing name throws with the list of resources the assembly does have

Spacing out retries with RetryDelaySchedule

var schedule = new RetryDelaySchedule([TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(10)]);
schedule.GetDelay(1);                       // 10 seconds after the first failure
schedule.GetDelay(7);                       // 10 minutes: the last delay repeats
schedule.GetNextAttemptAt(2, failedAt);     // failedAt + 1 minute

var exponential = RetryDelaySchedule.Exponential(TimeSpan.FromSeconds(1), count: 10, maxDelay: TimeSpan.FromMinutes(1));

Waiting for a job with PollingHelper.PollUntilAsync()

var result = await PollingHelper.PollUntilAsync(
    ct => client.GetJobAsync(jobId, ct),
    job => job.Status is JobStatus.Succeeded or JobStatus.Failed,
    interval: TimeSpan.FromSeconds(5),
    timeout: TimeSpan.FromMinutes(10),
    progress: new Progress<Job>(job => logger.LogInformation("Job is {Status}", job.Status)),
    cancellationToken: ct);

if (result.IsTimedOut)
{
    // result.Value is the last job state, after result.Attempts calls and result.Elapsed
}

On .NET 10 an overload takes a TimeProvider, so tests can drive the waits with a fake clock.

Keeping a slow lookup fresh with RefreshingSnapshot<T> (.NET 10)

// Only the first call waits. An expired value is still returned at once while one reload runs
// in the background; a failed reload keeps the old value, logs a warning and retries after 30 seconds.
using var prices = new RefreshingSnapshot<PriceList>(
    ct => client.GetPriceListAsync(ct),
    timeToLive: TimeSpan.FromMinutes(5),
    logger: logger);

var priceList = await prices.GetAsync(ct);
prices.Invalidate(); // reload on the next call, e.g. after an update message

Durations, comparison and rules

Using Iso8601Duration for calendar durations

var month = Iso8601Duration.Parse("P1M");        // also P1Y, P2W, P1DT12H, PT15M, PT1.5H, -P1D
var start = new DateTimeOffset(2025, 1, 31, 0, 0, 0, TimeSpan.FromHours(1));

start.Add(month);                                 // 2025-02-28
start.Add(month, 3);                              // 2025-04-30 - multiplied first, not clamped three times

// Step through local midnights in a time zone, across daylight-saving changes
var copenhagen = TimeZoneInfo.FindSystemTimeZoneById("Europe/Copenhagen");
var monthStarts = Enumerable.Range(0, 12).Select(i => start.Add(month, i, copenhagen));

Iso8601Duration.Parse("PT90M").ToString();        // "PT1H30M"
Iso8601Duration.Parse("PT15M").TryGetTimeSpan(out var timeout);  // true, 00:15:00

Using IsEquivalentTo() and GetChangedPropertyNames()

// Compares public properties recursively: lists in order, sets in any order, dictionaries by key.
if (!stored.IsEquivalentTo(incoming, ["ETag", "Modified"]))
{
    var changed = stored.GetChangedPropertyNames(incoming, ["ETag", "Modified"]);
    // e.g. ["Status", "Address.City", "Lines[2].Quantity", "Settings[Theme]"]
    logger.LogInformation("Order {Id} changed: {Changed}", stored.Id, string.Join(", ", changed));
}

Using BooleanExpressionEvaluator for user-written rules

// NOT binds tightest, then AND, then XOR, then OR.
var result = BooleanExpressionEvaluator.Evaluate(
    "(DoorOpen AND NOT Armed) OR Alarm",
    trueIdentifiers: ["DoorOpen"]);                        // BooleanExpressionResult.True

BooleanExpressionEvaluator.Evaluate("A AND", ["A"]);       // Invalid - never throws
BooleanExpressionEvaluator.IsValid("A OR (B XOR C)");      // true
BooleanExpressionEvaluator.TryGetIdentifiers("A OR B", out var names);  // ["A", "B"]

// With a resolver, an unknown identifier gives Invalid, so a misspelt name is caught
BooleanExpressionEvaluator.Evaluate(rule, name => states.TryGetValue(name, out var on) ? on : null);

Code generation helpers

Using CSharpKeywordHelper and UniqueNameHelper

CSharpKeywordHelper.IsReservedKeyword("event");           // true
CSharpKeywordHelper.EscapeIfReservedKeyword("event");     // "@event"
CSharpKeywordHelper.IsValidIdentifier("2fa");             // false
CSharpKeywordHelper.EnsureIdentifierStart("2fa", "Header"); // "Header2fa"

var taken = new HashSet<string>(StringComparer.Ordinal);
UniqueNameHelper.Claim(taken, "id");                      // "id"
UniqueNameHelper.Claim(taken, "id");                      // "id2"

Using InvariantCasingHelper

// Invariant casing that keeps a letter as written when its cased form is no letter to this
// runtime (ICU can be newer than .NET's Unicode tables) - the same output on every platform.
string upper = InvariantCasingHelper.ToUpper("petStore");    // "PETSTORE"
string pascal = InvariantCasingHelper.ToUpperFirst("pet");   // "Pet"

Using HttpStatusCode.ToEnumName()

HttpStatusCode.NotFound.ToEnumName();    // "NotFound"
((HttpStatusCode)302).ToEnumName();      // "Found" (never the "Redirect" alias)
((HttpStatusCode)499).ToEnumName();      // "Status499"

File and process helpers

Using ApplyRetention() to clean up old files

var result = new DirectoryInfo(logFolder).ApplyRetention(new FileRetentionPolicy
{
    SearchPattern = "*.log",
    KeepNewest = 10,                       // per group
    MaxAge = TimeSpan.FromDays(30),
    KeepAtLeast = 1,                       // never delete the latest, however old
    GroupBy = f => f.Name.Split('_')[0],   // e.g. api_2025-01-01.log, worker_2025-01-01.log
    DryRun = true,                         // only report what would be deleted
});

// result.Deleted, result.Kept, and result.Failed (files in use, with the exception)

Using FileSystemTransaction to undo a half-done operation

// Files written through the transaction are put back (and new files and folders removed)
// unless the operation returns 0.
var exitCode = FileSystemTransaction.Run(() =>
{
    FileSystemTransaction.CreateDirectory(projectFolder);
    FileSystemTransaction.WriteAllText(Path.Combine(projectFolder, "Program.cs"), content);
    return RunNextStep();
});

Using FileHelper.WriteAllTextIfChanged()

// Leaves the file (and its timestamp) alone when it already holds the content.
bool written = FileHelper.WriteAllTextIfChanged(new FileInfo("Generated.cs"), content, useLineFeedLineEndings: true);

Using GlobHelper

GlobHelper.IsMatch("/api/v1/users/42", "/api/**/users/*");   // true
GlobHelper.IsMatch("src/a/b/Program.cs", "src/**/*.cs");     // true
GlobHelper.IsMatchAny("/pets/1", new[] { "/pets/*", "/users" }); // true

Running a tool with ProcessHelper

// Find "git" on PATH, close its stdin so it cannot wait for input, stop it after 30 seconds,
// and read stdout and stderr apart.
var git = ProcessHelper.FindExecutableInPath("git");
var result = await ProcessHelper.ExecuteAsync(
    new ProcessStartInfo(git!.FullName, "status --porcelain") { WorkingDirectory = repositoryPath },
    TimeSpan.FromSeconds(30));

if (result.IsSuccessful)
{
    Parse(result.StandardOutput); // warnings are in result.StandardError
}

Is the tool already running?

var exe = new FileInfo(@"C:\Tools\Importer\Importer.exe");
if (ProcessHelper.IsRunning(exe))
{
    return; // matched on the full path, not just the name
}

Downloading and unpacking with progress

var progress = new Progress<double>(percent => bar.Value = percent); // 0 to 100

// Written to "package.zip.partial" first, so a failed download never leaves a half file behind
await httpClient.DownloadToFileAsync(new Uri("https://example.com/package.zip"), zipFile, progress, ct);

// Empties the folder first, then extracts; optionally deletes the archive afterwards
await ZipHelper.ExtractToCleanDirectoryAsync(zipFile, installFolder, deleteZipAfter: true, ct);

// Any stream copy can report progress too
await source.CopyToAsync(destination, totalBytes: response.Content.Headers.ContentLength, progress);

Security and hashing

Checking a webhook signature with HmacSignatureHelper

// Header "X-Hub-Signature-256: sha256=5c1f..." over the raw request body; compared in constant time
var isValid = HmacSignatureHelper.IsValidHexSignature(
    HmacAlgorithm.Sha256,
    request.Headers["X-Hub-Signature-256"],
    rawBody,
    webhookSecret,
    prefix: "sha256=");

var signature = HmacSignatureHelper.ComputeHexSignature(HmacAlgorithm.Sha256, payload, secret); // lower-case hex

Using ToSha256Hex() and ToSha256()

"abc".ToSha256Hex();          // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
fileBytes.ToSha256();         // the 32-byte hash

Creating a self-signed certificate (.NET 10)

var options = new SelfSignedCertificateOptions("CN=my-service")
{
    Validity = TimeSpan.FromDays(90),
};
options.DnsNames.Add("localhost");
options.IPAddresses.Add(IPAddress.Loopback);

using var certificate = X509CertificateHelper.CreateSelfSigned(options);

var keyPem = certificate.ExportPrivateKeyPem();   // with the built-in certificate.ExportCertificatePem()
await certificate.ExportToFilesAsync(
    folder,
    "my-service",
    CertificateExportFormats.Pem | CertificateExportFormats.PrivateKeyPem | CertificateExportFormats.Pfx,
    pfxPassword: "secret");

Metrics and tracing (.NET 10)

Timing an operation with MeasureDuration()

private static readonly Histogram<double> ImportDuration =
    Meter.CreateHistogram<double>("import.duration", unit: "s");

using var scope = ImportDuration.MeasureDuration(new KeyValuePair<string, object?>("source", "erp"));
try
{
    await ImportAsync(ct);
    scope.SetTag("outcome", "ok");
}
catch (Exception ex)
{
    scope.SetError(ex); // sets the error.type tag
    throw;
}
// The elapsed seconds are recorded with the tags when the scope is disposed

Marking an Activity as failed

activity?.SetError(ex);                          // Error status plus an "exception" event
activity?.SetError("Upstream returned 503");    // Error status only
activity?.AddLinkIfNotNull(message.ParentContext); // link to the sender's trace, when there is one

Geometry examples

New angle and geometry helpers use the mathematical convention: 0 degrees points along +x and angles increase counter-clockwise. (CartesianHelper.ComputeCoordinateFromPolar is older and uses a clock-face convention; see its documentation.)

Working with headings

var heading = MathHelper.NormalizeDegrees(-30);                  // 330
var turn = MathHelper.DegreesDifference(350, 10);                // 20 (shortest signed turn)
var same = MathHelper.AreDegreesEqual(359.9, 0.1, tolerance: 0.5); // true
var toTarget = CartesianHelper.HeadingDegrees(from, to);         // [0, 360)
var ahead = CartesianHelper.PointFromHeading(start, heading, 120);

Vector maths on Point2D

var direction = (end - start).Normalize();
var midpoint = start.Lerp(end, 0.5);
var rotated = corner.RotateAround(pivot, 90);
var snapped = position.SnapToGrid(5);
var close = a.IsNear(b, tolerance: 0.5);

Following an arc, then placing the result

// A 30 degree left curve with radius 360, starting at the origin heading along +x
var arc = Arc2D.FromStartHeading(new Point2D(0, 0), headingDegrees: 0, radius: 360, sweepDegrees: 30, turnLeft: true);
var end = arc.EndPoint;               // (180, 48.23)
var endHeading = arc.EndHeadingDegrees; // 30
var polyline = CircleHelper.ArcPoints(new Point2D(0, 0), 0, 360, 30, turnLeft: true, maxStepDegrees: 5);

// Rotate a shape by 90 degrees and move it to (1000, 500)
var placement = Transform2D.FromRotationAndTranslation(90, new Point2D(1000, 500));
var placed = placement.Apply(end);
var placedHeading = placement.ApplyToHeading(endHeading);
var backToLocal = placement.Invert().Apply(placed);

Hit-testing and selection

var distance = segment.DistanceTo(mouse);           // also Arc2D.DistanceTo / ClosestPoint
var crossings = IntersectionHelper.Intersect(segment, arc, tolerance: 0.5);
var touched = IntersectionHelper.Intersects(arc, selectionBox);
var extent = BoundingBox2D.Of(points).Union(arc.Bounds).Inflate(10);

Length unit examples

Store lengths in millimeters and pick the unit when you show them:

var text = LengthFormatter.Format(188.3, LengthUnitType.Millimeter, decimals: 1);   // "188,3 mm" (da-DK)
var meters = LengthFormatter.Format(3000, LengthUnitType.Meter, 2, CultureInfo.InvariantCulture); // "3.00 m"
var inches = LengthFormatter.Format(188.3, LengthUnitType.Inch, 2, CultureInfo.InvariantCulture); // "7.41 in"
var room = LengthFormatter.FormatFeetAndInches(3000);                               // "9 ft 10 in"

var mm = LengthUnitTypeHelper.ToMillimeters(12, LengthUnitType.Inch);               // 304.8
var feet = LengthUnitTypeHelper.Convert(36, LengthUnitType.Inch, LengthUnitType.Foot); // 3
var system = MeasurementSystemTypeHelper.FromCulture(new CultureInfo("en-US"));    // Imperial

NugetFeedClient examples

Using GetLatestStableVersionAsync(..) to find the latest stable version of a package

The client reads the flat container resource of nuget.org (or another NuGet v3 feed) and returns the highest version that is not a prerelease. A version found is cached per instance; any failure (no network, an unknown package, an unexpected answer, a cancellation) gives null instead of an exception.

INugetFeedClient client = new NugetFeedClient();

Version? latest = await client.GetLatestStableVersionAsync("Atc", cancellationToken);

Pass your own HttpClient (for example from IHttpClientFactory, or one over a fake HttpMessageHandler in tests), and optionally the flat container address of another feed:

var client = new NugetFeedClient(
    httpClient,
    new Uri("https://pkgs.example.com/nuget/v3/flatcontainer/"));

SearchQueryHelper examples

Using Parse() to split a free-text search into terms

Words split on white space and commas, text in double quotes is one phrase (an unclosed quote runs to the end), and a full GUID becomes an identifier term. The helper only parses; the caller decides how each term matches, e.g. a word as a substring, a phrase as whole words and an identifier as an exact id.

var terms = SearchQueryHelper.Parse("\"Main Street 8\" Springfield 5b1eba26-8b25-f111-8341-7c1e52fbbe51");
// [ (Phrase, "Main Street 8"), (Word, "Springfield"), (Identifier, "5b1eba26-8b25-f111-8341-7c1e52fbbe51") ]

// Custom separators, or no GUID detection
var options = new SearchQueryOptions { WordSeparators = [';'], DetectGuids = false };
var custom = SearchQueryHelper.Parse("alpha;beta", options);
// [ (Word, "alpha"), (Word, "beta") ]

Using ParseFilter() for a single-value filter

SearchQueryHelper.NormalizeFilter("  *pump*  ");                          // "pump"
SearchQueryHelper.ParseFilter("1,5", new CultureInfo("da-DK"));           // (Number, "1,5", Number: 1.5)
SearchQueryHelper.ParseFilter("5b1eba26-8b25-f111-8341-7c1e52fbbe51", CultureInfo.InvariantCulture); // Identifier
SearchQueryHelper.ParseFilter("*", CultureInfo.InvariantCulture);         // None

Enum Extension Examples

Using GetName() and GetDescription()

public enum Status
{
    [Description("Currently Active")]
    Active,

    [Description("Temporarily Inactive")]
    Inactive
}

Status status = Status.Active;
string name = status.GetName();              // "Active"
string description = status.GetDescription(); // "Currently Active"

Using GetEnumValue<T>()

Status status = EnumExtensions.GetEnumValue<Status>("Active");
// Result: Status.Active

// With description
Status statusFromDescription = EnumExtensions.GetEnumValueFromDescription<Status>("Currently Active");
// Result: Status.Active

Using ToEnumOrDefault<T>()

DayOfWeek a = "monday".ToEnumOrDefault(DayOfWeek.Sunday);  // DayOfWeek.Monday
DayOfWeek b = "Funday".ToEnumOrDefault(DayOfWeek.Sunday);  // DayOfWeek.Sunday (unknown name)
DayOfWeek c = "42".ToEnumOrDefault(DayOfWeek.Sunday);      // DayOfWeek.Sunday (undefined number)

Guarding MapTo() with EnumHelper.GetNameDifferences<TSource, TTarget>()

MapTo maps enums by name, so a value added to one enum and not the other only fails at run time. A unit test catches it at build time:

[Fact]
public void PetType_And_ApiPetType_HaveTheSameNames()
{
    var differences = EnumHelper.GetNameDifferences<PetType, ApiPetType>();
    Assert.False(differences.HasDifferences, differences.ToString());
    // fails with e.g. "Only in PetType: Bird. Only in ApiPetType: Unknown."
}

// When the target may have extra values, check one direction only:
Assert.Empty(EnumHelper.GetNameDifferences<PetType, ApiPetType>().OnlyInSource);

Claims Extension Examples

Using GetDisplayName(), GetUsername(), GetEmail() and GetAppId()

string? objectId = User.GetIdentity();     // Microsoft Entra ID object id (oid)
string? name = User.GetDisplayName();      // "name" claim, e.g. "Jane Doe"
string? username = User.GetUsername();     // ClaimTypes.Name, else "preferred_username"
string? email = User.GetEmail();           // ClaimTypes.Email, else "email", else an email-shaped username
string? appId = User.GetAppId();           // "azp" (v2 tokens), else "appid" (v1 tokens)

GuidHelper examples

Using CreateDeterministic()

// The same components always give the same Guid - a stable id derived from natural keys.
Guid id = GuidHelper.CreateDeterministic("device", "123");
// Always 9174bb27-8d27-375a-3046-9518b6264ddc

Collection Extension Examples

Using AddIfNotContains()

var list = new List<string> { "apple", "banana" };
list.AddIfNotContains("orange");  // Adds "orange"
list.AddIfNotContains("apple");   // Does nothing, already exists

Using ForEach()

var numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.ForEach(n => Console.WriteLine(n * 2));

Using IsNullOrEmpty()

List<string>? list = null;
bool isEmpty = list.IsNullOrEmpty();  // true

list = new List<string>();
isEmpty = list.IsNullOrEmpty();       // true

list.Add("item");
isEmpty = list.IsNullOrEmpty();       // false

DateTime Extension Examples

Using GetAge()

DateTime birthDate = new DateTime(1990, 5, 15);
int age = birthDate.GetAge();  // Current age in years

Using GetPrettyTimeDiff()

DateTime past = DateTime.Now.AddMinutes(-45);
string diff = past.GetPrettyTimeDiff();
// Result: "45 minutes ago"

Using IsBetween()

DateTime now = DateTime.Now;
DateTime start = DateTime.Now.AddHours(-1);
DateTime end = DateTime.Now.AddHours(1);

bool isBetween = now.IsBetween(start, end);  // true

Calendar periods in a time zone

StartOfDay() and StartOfMonth() keep the value's UTC offset, so across a daylight saving time change they can miss the real start. The overloads that take a TimeZoneInfo use the zone's own offset at that moment.

var copenhagen = TimeZoneInfo.FindSystemTimeZoneById("Europe/Copenhagen");
var instant = new DateTimeOffset(2025, 10, 30, 12, 0, 0, TimeSpan.FromHours(1));

instant.StartOfMonth(copenhagen);                                  // 2025-10-01 00:00 +02:00
instant.StartOfWeek(copenhagen);                                   // Monday 2025-10-27 00:00 +01:00
instant.IsStartOfPeriod(CalendarPeriod.Day, copenhagen);           // false

// A local time that does not exist moves forward; one that occurs twice takes its first occurrence.
copenhagen.ToDateTimeOffset(new DateTime(2025, 3, 30, 2, 30, 0)); // 2025-03-30 03:30 +02:00

On .NET 10 there are also DateOnly versions (StartOfWeek, EndOfMonth, …), instant.ToDateOnly(timeZone) and timeProvider.GetToday(timeZone).

Time buckets and periods

var time = new DateTimeOffset(2025, 1, 1, 10, 37, 0, TimeSpan.Zero);
time.FloorTo(TimeSpan.FromMinutes(15));    // 10:30
time.CeilingTo(TimeSpan.FromMinutes(15));  // 10:45

// A round bucket size for a chart of the last 30 days, and a complete series with empty buckets filled in
var bucketSize = TimeBucketHelper.GetBucketSize(TimeSpan.FromDays(30), maxBuckets: 200); // 6 hours
var series = TimeBucketHelper.Fill(rows, r => r.Time, from, to, bucketSize, t => new Row(t, 0));

// Split a long range into requests of at most 7 days
foreach (var (periodFrom, periodTo) in from.SplitIntoPeriods(to, TimeSpan.FromDays(7)))
{
    await client.GetDataAsync(periodFrom, periodTo);
}

Validating an optional from/to pair

// Both or neither, from not after to, and at most 31 days apart
if (!DateTimeOffsetHelper.TryValidateRange(query.From, query.To, TimeSpan.FromDays(31), out var error))
{
    return Results.BadRequest(error);
}

JSON Serialization Examples

Using JsonSerializerOptionsFactory

using Atc.Serialization;

// Create default options
var options = JsonSerializerOptionsFactory.Create();

// Serialize with camelCase
var json = JsonSerializer.Serialize(myObject, options);

// Deserialize
var obj = JsonSerializer.Deserialize<MyType>(json, options);

Using CopyTo() to apply options you cannot replace

// ASP.NET Core minimal APIs: copy every setting and converter, not just a few.
services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(
    o => JsonSerializerOptionsFactory.Create().CopyTo(o.SerializerOptions));

Keeping embedded JSON as JSON with RawJsonStringJsonConverter

public sealed class StoredMessage
{
    [JsonConverter(typeof(RawJsonStringJsonConverter))]
    public string Payload { get; set; } = "{\"id\":1}";
}

// {"Payload":{"id":1}} instead of {"Payload":"{\"id\":1}"}; other text is written as a normal string

Copying between look-alike types with MapViaJson<T>()

// A DTO defined again in another assembly, matched by JSON property names
var contract = internalModel.MapViaJson<PublicContract>(options);

Using StringEnumMemberJsonConverterFactory for strict and lenient enums

// Names come from [JsonStringEnumMemberName], else [EnumMember], else the member name.
// Non-nullable enums are strict; a nullable enum reads an unknown value (e.g. one a
// third-party API added later) as null instead of failing the whole response.
var options = new JsonSerializerOptions();
options.Converters.Add(new StringEnumMemberJsonConverterFactory(
    onUnknownValue: (type, value) => logger.LogWarning("Unknown {Type} value {Value}", type.Name, value)));

Using AsyncEnumerableFactory.FromException<T>()

// A stream that fails when enumerated, e.g. to test error handling.
IAsyncEnumerable<Item> failing = AsyncEnumerableFactory.FromException<Item>(new HttpRequestException("Gone"));

Math and Geometry Examples

Using GeoSpatial Helpers

using Atc.Math.GeoSpatial;

var coordinate1 = new CartesianCoordinate(55.6761, 12.5683); // Copenhagen
var coordinate2 = new CartesianCoordinate(51.5074, -0.1278); // London

// Calculate distance in kilometers
double distance = coordinate1.DistanceTo(coordinate2);

Contributing

Contributions are welcome! Please see the main repository README for contribution guidelines.

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.  net9.0 was computed.  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. 
.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 (36)

Showing the top 5 NuGet packages that depend on Atc:

Package Downloads
Atc.Rest

Atc.Rest is a basic collection of classes and extension methods for ASP.NET Core WebApi.

Atc.CodeDocumentation

Atc.CodeDocumentation is a markdown generator for source code.

Atc.OpenApi

Atc.OpenApi is a collection of classes and extension methods for Microsoft.OpenApi.

Atc.XUnit

Atc.XUnit is a collection of helper method for code compliance of documentation and tests.

Atc.Rest.ApiGenerator

Atc.Rest.ApiGenerator is a WebApi C# code generator using a OpenApi 3.0.x specification YAML file.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.3.0 0 12/3/2026
4.2.0 282 11/28/2026
4.1.0 3,243 11/9/2026
4.0.0 4,731 10/19/2026
3.0.186 8,560 8/25/2026
3.0.185 279 8/25/2026
3.0.181 6,652 7/29/2026
3.0.174 7,100 6/24/2026
3.0.173 414 6/24/2026
3.0.172 322 6/24/2026
3.0.67 6,677 4/25/2026
3.0.46 1,804 4/15/2026
3.0.45 602 4/10/2026
3.0.44 2,146 4/9/2026
3.0.43 287 4/9/2026
3.0.41 353 4/9/2026
3.0.40 323 4/9/2026
3.0.18 6,954 2/9/2026
3.0.16 9,027 12/15/2025
3.0.12 572 11/28/2025
Loading failed