Tharga.Toolkit.Standard 1.19.0

dotnet add package Tharga.Toolkit.Standard --version 1.19.0
                    
NuGet\Install-Package Tharga.Toolkit.Standard -Version 1.19.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="Tharga.Toolkit.Standard" Version="1.19.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tharga.Toolkit.Standard" Version="1.19.0" />
                    
Directory.Packages.props
<PackageReference Include="Tharga.Toolkit.Standard" />
                    
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 Tharga.Toolkit.Standard --version 1.19.0
                    
#r "nuget: Tharga.Toolkit.Standard, 1.19.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 Tharga.Toolkit.Standard@1.19.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=Tharga.Toolkit.Standard&version=1.19.0
                    
Install as a Cake Addin
#tool nuget:?package=Tharga.Toolkit.Standard&version=1.19.0
                    
Install as a Cake Tool

Tharga.Toolkit.Standard

NuGet Nuget License

.NET Standard 2.0 toolkit with utilities for strings, dates, collections, comparisons, timers, and more.

Installation

dotnet add package Tharga.Toolkit.Standard

Features

String Extensions

// Null/empty helpers
string val = "".NullIfEmpty();         // null
bool empty = "".IsNullOrEmpty();       // true
string safe = ((string)null).IfEmpty("fallback"); // "fallback"

// Random strings (cryptographically secure)
var random = StringExtension.GetRandomString(12, 20);
var pin = 6.RandomString(StringExtension.NumericCharacters); // "482917"

// Base64
var encoded = "hello".ToBase64();      // "aGVsbG8="
var decoded = encoded.FromBase64();    // "hello"

// Truncate
var short = "hello world".Truncate(5); // "hello"

Compare

Deep object comparison that returns a list of differences.

var obj1 = new { Name = "Alice", Age = 30 };
var obj2 = new { Name = "Bob", Age = 30 };

var diffs = obj1.Compare(obj2);
foreach (var diff in diffs)
{
    Console.WriteLine(diff.Message);
}

// Ignore sort order in collections
var diffs2 = list1.Compare(list2, CompareExtensions.CompareMode.IgnoreSortOrder);

Public instance fields and properties are compared; static members are not.

Since 1.18, a record, struct or other value with its own Equals is compared wherever it appears. Before, it was skipped when an equal value had been compared earlier, so a difference in it could go unreported.

Since 1.19, a diff names the member it was found on, not the member's type: SomeTestClass.StringProperty rather than SomeTestClass.String. The path is the type of the compared root, then each member name, for example Order.Lines.OrderLine.Price; an item in a collection adds its type name (and its index, for arrays). A member that is null on one side is reported against the member (Order.Customer), and a member missing on the other object is named the same way. Code that matched on the old ObjectName / OtherObjectName values needs updating.

Since 1.18, two DateTime values are compared exactly: a difference below one second, down to a single tick, is reported, and so is a different Kind with the same clock time. Before, both compared as equal.

DateTime Extensions

// Local formatting
var dateStr = DateTime.UtcNow.ToLocalDateString();       // "2024-01-15"
var timeStr = DateTime.UtcNow.ToLocalTimeString();       // "14:30:00"

// Duration strings (relative time)
var ago = someDate.ToDurationString();                    // "3 hours ago"
var swedish = someDate.ToDurationString(new DurationOptions
{
    StringOptions = DurationStringOptionsExtensions.Get(Language.Sv)
}); // "3 timmar sedan"

// TimeSpan formatting
var span = TimeSpan.FromMinutes(45).ToTimeSpanString();  // "45 minutes"

ManagedTimer

Async timer with interval correction, skip detection, and rich events.

var timer = new ManagedTimer(
    TimeSpan.FromSeconds(5),
    async iteration => { /* your work */ },
    autoStart: true
);

timer.BeforeExecuteEvent += (s, e) => { /* can cancel via e.Cancel = true */ };
timer.AfterExecuteEvent += (s, e) => { /* check e.Exception, e.Elapsed */ };
timer.StateChangedEvent += (s, e) => { /* Started, Executing, Waiting, Stopped */ };

timer.Stop();

Start() and Stop() are safe in any order, and a restart waits for what was left of the interval. Exceptions from the callback reach AfterExecuteEvent and the timer keeps running; an exception from an event handler reaches AfterExecuteEvent too, and stops the timer.

The interval must be larger than zero. Since 1.18, a zero interval passed to the constructor, and a zero or negative one set through Interval, throws ArgumentOutOfRangeException.

Enumerable Extensions

var item = items.TakeRandom();                     // random element
var shuffled = items.RandomOrder();                 // random order
var tail = items.TakeAllButFirst();                 // skip first
var init = items.TakeAllButLast();                  // skip last
var chunks = items.TakeChunks(10);                  // split into groups of 10
bool empty = EnumerableExtensions.IsNullOrEmpty(items);
var safe = EnumerableExtensions.EmptyIfNull(items); // never null

Luhn Check Digits

var check = "7992739871".CheckDigit();       // "3"
var full = "7992739871".AppendCheckDigit();   // "79927398713"
bool valid = "79927398713".HasValidCheckDigit(); // true

// Also works with int, long, and IList<int>
int digit = 36155.CheckDigit(); // 0

Password Hasher

PBKDF2-based password hashing.

var hash = PasswordHasher.HashPassword("myPassword");
bool ok = PasswordHasher.VerifyPassword("myPassword", hash);   // true
bool bad = PasswordHasher.VerifyPassword("wrong", hash);       // false

// After a successful verification, replace a hash that was created with older parameters
if (ok && PasswordHasher.NeedsRehash(hash)) hash = PasswordHasher.HashPassword("myPassword");

New hashes use PBKDF2-HMAC-SHA512 with 210,000 iterations (PasswordHasher.DefaultIterations), a 16-byte salt and a 32-byte hash, written as $HASH|V2$SHA512${iterations}${salt}${hash}, so everything needed to verify a hash is stored with it. Verification compares the hashes in constant time.

Since 1.18, new hashes use this format and these defaults. Hashes in the earlier $HASH|V1${iterations}${hash} format (PBKDF2-HMAC-SHA1, 10,000 iterations by default) still verify: if they were created with a non-default saltSize or hashSize, pass the same values to VerifyPassword. NeedsRehash returns true for them. Versions before 1.18 cannot verify the new format.

Collections

// Two-level concurrent dictionary
var dict = new ConcurrentTwoLevelDictionary<string, string, int>();
var (before, after) = dict.AddOrUpdate("users", "alice", 42);

// Observable concurrent dictionary (INotifyCollectionChanged)
var observable = new ObservableConcurrentDictionary<string, int>();
observable.CollectionChanged += (s, e) => { /* react to changes */ };
observable.Add("key", 1);
observable.TryAdd("key", 2);   // false, the key exists

Since 1.18, ObservableConcurrentDictionary follows the IDictionary contract: Add throws ArgumentException when the key exists (use TryAdd to add only when it is missing), and Remove(KeyValuePair) removes only when the value matches too. Setting the indexer for a new key raises Add with Count and Keys changes; for an existing key it raises Replace with the old value. Before, Add ignored an existing key, Remove(KeyValuePair) removed by key alone, and the indexer always raised Replace with the key as the old item.

Semaphore Executor

Key-based async semaphore: same key = sequential, different keys = concurrent.

var executor = new SemaphoreExecutor<string>();
var result = await executor.ExecuteAsync("user-123", async () =>
{
    // Only one operation per key at a time
    return await ProcessAsync();
});

Since 1.18, each executor has its own locks. Before, every SemaphoreExecutor<TKey> with the same TKey shared them, so unrelated executors blocked each other and a call from one into another deadlocked. Code that must not run at the same time for a key now has to share one executor instance, for example a singleton. The lock is not reentrant: calling the same executor with the same key from inside its own action waits forever.

Claims Extensions

Extract identity, email, and display name from ClaimsPrincipal, ClaimsIdentity, or raw claims.

// Identity extraction (checks sub, oid, nameid, uid, NameIdentifier)
var (identity, type) = principal.GetIdentity();

// Email extraction (checks email, ClaimTypes.Email, emails, preferred_username, name)
var email = principal.GetEmail();
var domain = principal.GetEmailDomain();

// Display name extraction — tries in order:
// 1. "name" (OIDC)  2. ClaimTypes.Name (WS-Fed)  3. "nickname" (Auth0)
// 4. given_name + family_name  5. ClaimTypes.GivenName + Surname
// 6. preferred_username (non-email)  7. email prefix, title-cased
var displayName = principal.GetDisplayName();
// e.g. "daniel.bohlin@example.com" → "Daniel Bohlin"

// Domain-based role assignment (email claim only: email, ClaimTypes.Email or emails;
// email_verified must be true when present; preferred_username and name are not used)
principal.AddRoleForDomain("Developer", "example.com", "contoso.com");

// Opt in to preferred_username when no email claim is present (name is never used)
principal.AddRoleForDomain("Developer",
    new RoleForDomainOptions { TrustPreferredUsername = true },
    "example.com");

Since 1.17, AddRoleForDomain no longer uses preferred_username or name by default. If your identity provider sends the address only in preferred_username, add the email claim at the provider or use the opt-in above. Some providers do not verify the email claim, so check what yours guarantees before granting roles by domain.

Other Extensions

// Org number parsing (Swedish format)
if ("556123-4567".TryParseOrgNo(out var orgNo))
    Console.WriteLine(orgNo); // "556123-4567"

// Byte size formatting
long bytes = 1536;
Console.WriteLine(bytes.ToReadableByteSize(decimalPlaces: 1)); // "1.5 KB"

// Enum mapping
var target = sourceEnum.MapEnum<TargetEnum, SourceEnum>();

// Exception data helpers
throw new Exception("error")
    .AddData("userId", 123)
    .AddData("action", "save");

// Smart enum
public class Color : Enumeration
{
    public static readonly Color Red = new(1, "Red");
    public static readonly Color Blue = new(2, "Blue");
    private Color(int id, string name) : base(id, name) { }
}
var all = Enumeration.GetAll<Color>();

GitHub repo

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 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. 
.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.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Tharga.Toolkit.Standard:

Package Downloads
Tharga.Toolkit

Tools for hashing, claims, API keys, collections, DateTime, Luhn, Compare and more. Includes all features from Tharga.Toolkit.Standard.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.19.0 143 11/16/2026
1.18.0 417 11/15/2026
1.17.0 1,596 10/27/2026
1.16.7 502 10/25/2026
1.16.6 116 10/25/2026
1.16.5 158 10/25/2026
1.16.4 2,133 9/28/2026
1.16.3 1,784 8/24/2026
1.16.2 1,137 8/17/2026
1.16.1 256 8/14/2026
1.16.0 2,414 7/26/2026
1.15.25 2,646 6/8/2026
1.15.24 1,550 5/14/2026
1.15.23 1,381 4/28/2026
1.15.22 186 4/28/2026
1.15.21 801 4/16/2026
1.15.20 462 4/5/2026
1.15.19 642 3/25/2026
1.15.18 1,000 1/31/2026
1.15.16 423 12/28/2025
Loading failed