Jakar.Extensions
10.12.2
See the version list below for details.
dotnet add package Jakar.Extensions --version 10.12.2
NuGet\Install-Package Jakar.Extensions -Version 10.12.2
<PackageReference Include="Jakar.Extensions" Version="10.12.2" />
<PackageVersion Include="Jakar.Extensions" Version="10.12.2" />
<PackageReference Include="Jakar.Extensions" />
paket add Jakar.Extensions --version 10.12.2
#r "nuget: Jakar.Extensions, 10.12.2"
#:package Jakar.Extensions@10.12.2
#addin nuget:?package=Jakar.Extensions&version=10.12.2
#tool nuget:?package=Jakar.Extensions&version=10.12.2
Jakar.Extensions
Extensions and helpers for .NET 10: observable and concurrent collections, security, async LINQ, span and hashing helpers, JSON models, diagnostics and view models. It is trim and Native AOT compatible. Contributions and ideas are welcome.
Installation
dotnet add package Jakar.Extensions
It brings in Jakar.Json (JSON, including the [JsonModel] source generator) and Jakar.Spans (ValueStringBuilder and other span primitives).
Related packages
Since 10.12 these live in their own packages. They depend on Jakar.Extensions and keep the Jakar.Extensions namespace, so code that used them only needs the package reference (and a recompile):
| Package | What it is |
|---|---|
| Jakar.Files | LocalFile, LocalDirectory, LocalFileWatcher, TempFile, FilePaths, FileData/FileMetaData, EmbeddedResources<T>, IniConfig, PreferenceFile<TSelf>, AppPreference, plus IAppInfo, AppSettings, LanguageApi and the LocalFile / EmbeddedResources overloads of IDataProtector, DataProtector and PasswordRequirements (as extension members). |
| Jakar.ErrorOr | Error, Errors, Alert, ErrorOrResult<T>: RFC 7807-style errors and results. Since 10.12.1 it is a dependency of Jakar.Extensions (it depends on Jakar.Json only), so it comes with this package. |
| Jakar.Http | WebRequester, WebHandler, WebResponse<T>, ErrorResponse, HeaderCollection, networking exceptions. Depends on Jakar.ErrorOr and Jakar.Files. |
| Jakar.Users | UserModel, GroupModel, RoleModel, UserAddress, LoginRequest*, Claims, Permissions, UserRights, JwtParser, EmailBuilder. Depends on Jakar.Files. |
| Jakar.Logging | Serilog and file logging: AppLoggerOptions, FileLoggerProvider, Enricher, OpenTelemetryActivityEnricher, ScreenShot, and the Serilog properties of AppInformation, DeviceInformation, GcInfo and ThreadInformation. Depends on Jakar.Files. |
Pair, StringTags, Status, Statuses, IErrorDetails, IErrorTitles/ErrorTitles and NullAsEmptyArrayConverter live in Jakar.ErrorOr since 10.12.1 and are type-forwarded from here (no source or binary change). The MIME types, None, Email, IUserName and SelfLogger stay in Jakar.Extensions.
JSON
Since 10.11 the library serializes with Jakar.Json only: source-generated readers and writers, no System.Text.Json, no Newtonsoft.Json and no reflection.
Models are
[JsonModel]types (IJsonSerializable<TSelf>). Put[JsonModel]on apartialclass, record or struct; the generator writesToJson(),FromJson(json),TryFromJson, UTF-8 and stream overloads, andISpanFormattable/ISpanParsable<TSelf>.[JsonModel] public sealed partial class Invoice : BaseClass<Invoice> { public decimal Total { get; init; } } Invoice invoice = Invoice.FromJson(json); string text = invoice.ToJson();Generic helpers:
Json.Serialize(value)/json.FromJson<T>()for models;Json.Serialize<T, TConverter>/Json.Deserialize<T, TConverter>for any other shape (e.g.JsonArrayConverter<string, JsonStringConverter>).Root-level arrays:
Json.Serialize(invoices),JsonCodec.FromJsonList<Invoice>(json)(andWebHandler.AsJsonList<Invoice>(token)in Jakar.Http).Untyped JSON is a
JNodetree (JObjectNode,JArrayNode,JValueNode):json.FromJson(), and the helpersGet<T>,TryGet<T>,GetOrDefault<T>,As<T>,TryGetValue<T>,TryAdd,TryUpdate,Set.Older JSON still reads. The library's models accept JSON written by 10.10 and earlier: case-insensitive property names, numbers in strings, comments and trailing commas (
[assembly: JsonDefaults]). Declare the sameJsonDefaultsin your assembly for your own models.
Migrating from 10.10
IJsonModel<TSelf>,JsonTypeInfo,JsonSerializerContexts (JakarExtensionsContext,UserGuidJsonContext,UserLongJsonContext),Json.Options,Json.AddResolverandJson.GetTypeInfoare gone: put[JsonModel]on your types, and constrain generic code toIJsonSerializable<T>.- System.Text.Json attributes aren't read:
[JsonIgnore]→[JsonSkip],[JsonConstructor]→[JsonCreator],[JsonRequired]→[JsonMandatory],[JsonPropertyName]→[JsonKey],[JsonExtensionData]→[JsonOverflow]. AdditionalDatais aJObjectNode?(ordinal keys).ErrorResponse,FeedBackTrackerException,ExceptionDetails.DataandLoginRequestValue.DatauseJNode/JObjectNode.- Output is Jakar.Json's layout, compact by default (
{"Name" : "value"}); preference files are written indented. PreferenceFile<TSelf>subclasses implementCopyFrom(TSelf loaded), which copies their declared preferences on load and reload.AppVersionandEmailare written as JSON strings (ISpanFormattable+ISpanParsable<T>);AppVersion.ToJson()/AppVersion.FromJson(json)remain.- Observable collections implement
IJsonCollection<TSelf, T>: as[JsonModel]members they write their unfiltered contents and read in bulk. As a root,ToJson()/FromJson(json)need[JsonModel]elements; useObservableJson.ToJson<TSelf, TValue, TConverter>for others. LocalFile/LocalDirectoryserialize as{"FullPath", "FileEncoding"}/{"FullPath"}; a plain path string no longer reads.WebRequester:CreateJsonContent/CreateJsonArrayContenttake Jakar.Json writer options;WebHandler.AsJson<T>,AsJsonArray<T>andAsJsonList<T>take noJsonTypeInfo.
Migrating from 10.11
- Add the package for the types you use (table above): Jakar.Files, Jakar.ErrorOr, Jakar.Http, Jakar.Users or Jakar.Logging. It's a binary break: recompile against 10.12.
- Jakar.Extensions no longer depends on Serilog,
Microsoft.IdentityModel.*,Microsoft.Extensions.HttporZLinq.FileSystem; they come with Jakar.Logging, Jakar.Users, Jakar.Http and Jakar.Files. AppInformation,DeviceInformation,GcInfoandThreadInformationlost their Serilog members: Jakar.Logging addsGetProperty()/ToProperty()back as extension members.DeviceInformationis no longer anILogEventEnricher: usedevice.ToEnricher()(DeviceInformationEnricher).Error.TryCreate(WebResponse<T>, ...)is in Jakar.Http;global using static Jakar.Extensions.WebRequester/Claimsno longer come from Jakar.Extensions.
Base classes
BaseClass/BaseClass<TSelf>: a model base with property change notifications (INotifyPropertyChanging,INotifyPropertyChanged), JSON extension data (AdditionalData), and equality and comparison forTSelf.BaseRecord: the record counterpart, with JSON extension data.
Collections
- Observable:
ObservableCollection<T>,ConcurrentObservableCollection<T>,ObservableDictionary<TKey, TValue>,ObservableConcurrentDictionary<TKey, TValue>,ObservableHashSet<T>. They raise change notifications and can show a filtered view (OverrideFilter); the list types also keep a sort order (Comparer<T>). - Queues and stacks:
ConcurrentDeque<T>,FixedSizedDeque<T>,FixedSizedQueue<T>,LockFreeDeque<T>,LockFreeStack<T>. - Other:
ArrayBuffer<T>(a growable buffer struct),AsyncChannel<T>,ValueLinkedList<T>,MultiDict<TKey>.
Status codes and MIME types
Status,Statuses: HTTP status codes, their titles (IErrorTitles) and the status for an exception.MimeType,MimeTypeNames: MIME types, their names and file extensions.
Security
SecuredString: sensitive text kept in aSecureString.PasswordValidatorandPasswordRequirements: password rules and validation.OneTimePassword: TOTP codes.IDataProtector/IDataProtectorProvider/DataProtector: encrypt and decrypt data.
Errors
ExceptionDetails: exceptions as serializable data.StringTags,IErrorDetails(from Jakar.ErrorOr): the details of anError(inspired by ErrorOr).
Miscellaneous
Validate: string and state validation.Tasks: task helpers such asSafeFireAndForget.Types: type inspection (IsBuiltInType,IsNullableType,IsCollection,IsDictionary,IsList,IsSet,HasInterface,TryGetUnderlyingEnumType,MethodName,MethodSignature, ...).AppVersion: application versions with formatting and parsing.BaseViewModeland theCommand/IAsyncCommandtypes: view models.TelemetrySource,StopWatch,SelfLogger: diagnostics.
Method lists
Many of these have several overloads.
- AsyncLinq:
Add,AddDefault,AddOrUpdate,AsAsyncEnumerable,Average,CastSafe,Consolidate,ConsolidateUnique,Enumerate,EnumeratePairs,First,FirstOrDefault,ForEach,ForEachAsync,ForEachParallel,ForEachParallelAsync,GetArray,IsEmpty,Last,LastOrDefault,Max,Min,Random,RandomKeys,RandomValues,Range,Remove,Single,SingleOrDefault,Sorted,ToArray,ToArrayBuffer,ToConcurrentObservableCollection,ToHashSet,ToImmutableArray,ToList,ToObservableCollection,TryAdd,WhenAllParallelAsync,WhereNotNull,WhereNotNullAsync. - Hashes:
Concatenate,GetHash,Hash,Hash128,HashAsync,Hash_MD5,Hash_SHA1,Hash_SHA256,Hash_SHA384,Hash_SHA512,HashAsync_MD5,HashAsync_SHA1,HashAsync_SHA256,HashAsync_SHA384,HashAsync_SHA512,ToBytes,TryGetData. AlsoHashCodeU64/HashCodeU128. - Types:
Construct,GetNullabilityInfo,GetParameterInfo,HasInterface,IsAnyBuiltInType,IsBuiltInNullableType,IsBuiltInType,IsCollection,IsDictionary,IsDictionaryEntry,IsEqualType,IsGenericType,IsInitOnly,IsJsonNode,IsKeyValuePair,IsList,IsNullable,IsNullableType,IsOneOf,IsSet,MethodClass,MethodInfo,MethodName,MethodSignature,TryGetUnderlyingEnumType,TryGetUnderlyingType. - Spans:
All,Any,As,AsArraySegment,AsBytes,AsImmutableArray,AsMemory,AsReadOnlyMemory,AsReadOnlySpan,AsSpan,Average,ClampEnd,ClampStart,Contains,ContainsAll,ContainsAny,ContainsExact,ContainsNone,ConvertToString,CopyTo,Count,Create,CreateSpan,EndsWith,Enumerate,First,FirstOrDefault,GetVectors,IsNullOrWhiteSpace,Join,Last,LastIndexOf,LastOrDefault,Max,Min,QuickSort,RefSelect,Remove,RemoveAll,Replace,Select,SequenceEqual,SequenceEqualAny,Single,SingleOrDefault,Slice,StartsWith,Sum,ToMemory,ToMemoryStream,ToReadOnlyMemory,Trim,TrimEnd,TrimStart,TryAsSegment,TryCopyTo,TryGetCount.
Versioning
Versions follow <.NET major>.<library major>.<library minor>: 10.10.0 targets .NET 10, library major 10, minor 0. See the repository README.
License
MIT. See LICENSE.txt. Contributions are welcome: open an issue or a pull request on GitHub.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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
- CommunityToolkit.Diagnostics (>= 8.4.2)
- Jakar.ErrorOr (>= 10.2.0)
- Jakar.Json (>= 10.3.0)
- Jakar.Spans (>= 10.1.0)
- JetBrains.Annotations (>= 2026.2.0)
- Microsoft.CodeAnalysis.CSharp (>= 5.12.0)
- Microsoft.Extensions.Configuration.Binder (>= 11.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 11.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 11.0.0)
- Microsoft.Extensions.Options (>= 11.0.0)
- Nito.Collections.Deque (>= 1.2.1)
- OneOf (>= 3.0.271)
- OneOf.Extended (>= 3.0.271)
- OneOf.SourceGenerator (>= 3.0.271)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.21.0)
- OpenTelemetry.Instrumentation.Http (>= 1.21.0)
- OpenTelemetry.Instrumentation.Runtime (>= 1.21.0)
- Otp.NET (>= 1.4.1)
- System.ComponentModel.Annotations (>= 5.0.0)
- System.IO.Hashing (>= 11.0.0)
- ZLinq (>= 1.6.1)
- ZXing.Net (>= 0.16.11)
NuGet packages (6)
Showing the top 5 NuGet packages that depend on Jakar.Extensions:
| Package | Downloads |
|---|---|
|
Jakar.Database
Package Description |
|
|
Jakar.Extensions.Blazor
Extensions to aid in development. |
|
|
Jakar.Shapes
Extensions to aid in development. |
|
|
Jakar.Extensions.Serilog
Extensions to aid in development. |
|
|
Jakar.SqlBuilder
Easy Sql Building |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.13.0 | 71 | 11/18/2026 |
| 10.12.2 | 155 | 11/16/2026 |
| 10.12.1 | 81 | 11/16/2026 |
| 10.12.0 | 153 | 11/16/2026 |
| 10.11.1 | 198 | 10/25/2026 |
| 10.11.0 | 121 | 10/24/2026 |
| 10.10.0 | 202 | 10/17/2026 |
| 10.9.3 | 213 | 8/26/2026 |
| 10.9.1 | 171 | 7/2/2026 |
| 10.9.0 | 163 | 6/19/2026 |
| 10.8.3 | 215 | 3/11/2026 |
| 10.8.2 | 175 | 3/11/2026 |
| 10.8.1 | 176 | 3/11/2026 |
| 10.8.0 | 184 | 3/2/2026 |
| 10.7.0 | 177 | 2/17/2026 |
| 10.6.0 | 188 | 2/16/2026 |
| 10.5.0 | 199 | 2/4/2026 |
| 10.4.1 | 203 | 2/2/2026 |
| 10.4.0 | 192 | 2/2/2026 |
| 10.3.4 | 204 | 1/28/2026 |
10.12.2: Adds the static extension Error.Unauthorized(ref readonly PasswordValidator.Results, instance, description, type) that 10.12.1's notes promised but did not ship (Error.Unauthorized(in results) failed to compile with CS1615). 10.12.1: Jakar.ErrorOr no longer depends on Jakar.Extensions; Jakar.Extensions depends on it instead. Pair, Pair<TValue>, StringTags, Status, Statuses, IErrorDetails, IErrorTitles, ErrorTitles and NullAsEmptyArrayConverter<T, TConverter> moved to Jakar.ErrorOr and are type-forwarded (no source or binary change); Status.GetErrorTitle()/GetErrorType() stay here. New: PasswordValidator.Results.ToStringTags() and the static extension Error.Unauthorized(ref readonly PasswordValidator.Results, ...) (both were in Jakar.ErrorOr). Requires Jakar.ErrorOr 10.2.0 or later (10.1.0 depends on Jakar.Extensions 10.12.0). 10.12.0: BREAKING: five areas moved to their own packages, which depend on Jakar.Extensions and keep the Jakar.Extensions namespace (add the package and recompile): Jakar.Files (LocalFile, LocalDirectory, LocalFileWatcher, TempFile, FilePaths, PathExtensions, FileData/FileMetaData, EmbeddedResources, IniConfig, PreferenceFile, AppPreference/IAppPreferences, and with them IAppInfo, AppSettings/IAppSettings/IScreenshot and LanguageApi; the LocalFile/EmbeddedResources overloads of IDataProtector, DataProtector and PasswordRequirements are extension members there, so IDataProtector implementations drop them and IDataProtector.Decryptor/DecryptorAsync became DataProtectorFiles.Decryptor/DecryptorAsync), Jakar.ErrorOr (Error, Errors, Alert, ErrorOrResult, ErrorExtensions, All/Some/Success/Unknown), Jakar.Http (WebRequester, WebHandler, WebResponse, ErrorResponse, HeaderCollection, UriExtensions, networking exceptions; Error.TryCreate(WebResponse) is a static extension there), Jakar.Users (user/group/role/address models, LoginRequest*, Claims, ClaimType, Permissions, UserRights, JwtParser, EmailBuilder) and Jakar.Logging (AppLoggerOptions, Enricher, FileLoggerProvider, ScopeProvider, NullScope, OpenTelemetryActivityEnricher, IOpenTelemetryActivityEnricher, ScreenShot). Status, Statuses, the MIME types, StringTags, IErrorTitles/ErrorTitles, None, Email, IUserName and SelfLogger stay here. Serilog, Microsoft.IdentityModel.*, Microsoft.Extensions.Http and ZLinq.FileSystem are no longer dependencies. AppInformation, DeviceInformation, GcInfo, GcMemoryInformation, GcGenerationInformation and ThreadInformation lost their Serilog members (Jakar.Logging adds GetProperty/ToProperty back as extension members); DeviceInformation is no longer an ILogEventEnricher (device.ToEnricher() in Jakar.Logging). The global using static WebRequester/Claims no longer flows from here. 10.10.0: ValueStringBuilder and Sizes moved to the new dependency Jakar.Spans (same namespace, type-forwarded, so no source or binary change); Jakar.Spans adds ValueUtf8Builder and ValueSpanReader<T>. BREAKING: System.Text.Json replaces Newtonsoft.Json; the library is trim and Native AOT compatible (source-generated metadata only). New dependency Jakar.Json (IJsonModel<TSelf>, the [JsonModel] source generator and analyzers, pooled element-wise JSON arrays, SerializeAsStringJsonConverter<T>, plus the Jakar.Json serializer, which [JsonModel] uses behind IJsonModel when it supports the type: most models' ToJson/FromJson now run on it, laid out as Jakar.Json writes ("name" : value) with the context's options mirrored; JsonTypeInfo stays System.Text.Json's); types stay in the Jakar.Extensions namespace. IJsonModel<TSelf> requires static JsonTypeInfo (add [JsonModel]). JToken/JObject/JValue removed: AdditionalData is Dictionary<string, JsonElement>?, ErrorResponse/WebHandler.AsJson/FeedBackTrackerException use JsonNode, ExceptionDetails.Data is JsonObject, LoginRequestValue uses JsonElement. Json.Settings/LoadSettings replaced by Json.Options/AddResolver/GetTypeInfo; generic ToJson<T>(this T) only for IJsonModel types (else Json.Serialize). Typed JsonNode/JsonElement get/add/update/remove helpers. JSON written by 10.x still reads (case-insensitive names, numbers in strings, comments, trailing commas); output keeps PascalCase. PreferenceFile stores {TSelf}.json and imports an existing .ini. Observable collections serialize their unfiltered contents and read in bulk. LocalFile/LocalDirectory serialize as {"FullPath"}. ExceptionDetails(Exception, bool) became Create / CreateWithMethodInfo. WebRequester: AsJson(JsonTypeInfo), AsJsonArray/AsJsonList, BaseClass bodies serialized as their runtime type. Fixes: Json.ToJson(ReadOnlySpan) serialized the whole pooled rental; LocalFile.WriteAsync(string) wrote empty files; LoginRequest copy constructors passed the login as the password; Email.TryParse returned the inverse; GcInfo did not deserialize MemoryInfo. Removed the unused ValueOf package. 10.11.0: BREAKING: built on Jakar.Json 10.3.0, which no longer has System.Text.Json: the library serializes with Jakar.Json only. IJsonModel<TSelf>, the System.Text.Json contexts (JakarExtensionsContext, UserGuidJsonContext, UserLongJsonContext), Json.Options/AddResolver/GetTypeInfo and every JsonTypeInfo overload are removed: models are [JsonModel] types (IJsonSerializable<TSelf>), and generic helpers are constrained to IJsonSerializable<T> or take an IJsonConverter<T> (Json.Serialize<T, TConverter> / Json.Deserialize<T, TConverter>). JsonNode/JsonElement/JsonObject became Jakar.Json's JNode/JObjectNode: AdditionalData (JObjectNode?, ordinal keys, [JsonOverflow]), ErrorResponse, FeedBackTrackerException, ExceptionDetails.Data, LoginRequestValue.Data, IniConfig.ToJsonObject/FromJsonObject and the typed get/add/update helpers; the JsonElement helpers are gone. Output uses Jakar.Json's layout, compact by default; preference files are written indented. PreferenceFile<TSelf> subclasses implement CopyFrom(TSelf). AppVersion is no longer a [JsonModel] (it is written as a JSON string, as before; ToJson/FromJson remain). Observable collections: the System.Text.Json converters are removed; IJsonCollection<TSelf, T> covers [JsonModel] members, root ToJson/FromJson need [JsonModel] elements (or ObservableJson.ToJson/FromJson with a converter). LocalFile/LocalDirectory no longer read a plain path string. WebRequester.CreateJsonContent/CreateJsonArrayContent take JsonWriterOptions, and CreateJsonContentOfRuntimeType resolves the type with JsonCodecRegistry. Jakar.Json's attributes are kept in this assembly's metadata (JAKAR_JSON_KEEP_ATTRIBUTES), so [JsonModel] types in other assemblies see [JsonOverflow] on BaseClass.AdditionalData. New: NullAsEmptyArrayConverter<T, TConverter>; StringTags reads missing or null Tags/Entries as empty. BREAKING: IIObservableCollection<TValue> renamed to IObservableCollection<TValue>. BREAKING: Command<TValue> now follows CommunityToolkit.Mvvm AsyncRelayCommand<T> semantics and implements the new IAsyncCommand<TValue>: ExecutionTask, IsRunning, CanBeCanceled, IsCancellationRequested (with PropertyChanged), ExecuteAsync returning Task, Cancel(), NotifyCanExecuteChanged() (CanExecute no longer raises CanExecuteChanged itself), CommandOptions (AllowConcurrentExecutions, FlowExceptionsToTaskScheduler), CreateCancelCommand(); CanExecute is false while running by default; starting a cancellable handler cancels the previous token; Execute rethrows handler failures on the calling context unless FlowExceptionsToTaskScheduler; object parameters of the wrong type throw ArgumentException. Command<TValue>.Executable accepts CancellationToken-taking handlers, adds Execute(object?, TValue?, CancellationToken), is 16 bytes instead of 72, and no longer drops the Task from Func<TValue?, Task> handlers (it is now awaited). Fixed SelfLogger.WriteLine throwing FormatException for named template holes such as {Error}. Internal folder restructure. Removed the unused Portable.BouncyCastle dependency and System.* package references that are part of the net10.0 shared framework. 10.11.1: Fixed ArrayBuffer<T>.Create / ToArrayBuffer() on sources that cannot report their count (e.g. after Order()): the result held 64 slots padded with default values instead of exactly the source's items. 10.10.0: TelemetrySource uses W3C activity IDs: the process-wide hierarchical default is gone and the StartActivity idFormat default is now Unknown (default parameter values are compiled into call sites, so recompile callers). StartActivity respects the sampler: it returns null instead of throwing when sampled out, no longer forces IsAllDataRequested, the Recorded trace flag (traceFlags is now ActivityTraceFlags?) or Ok status, and keeps the parent tracestate. Constructing a TelemetrySource no longer clears Activity.Current. AppVersion has a TypeConverter, so it binds from configuration strings. TelemetrySpan can target a specific TelemetrySource via TelemetrySpan.Create(TelemetrySource, string).