Lyo.Common.Core
3.0.0
dotnet add package Lyo.Common.Core --version 3.0.0
NuGet\Install-Package Lyo.Common.Core -Version 3.0.0
<PackageReference Include="Lyo.Common.Core" Version="3.0.0" />
<PackageVersion Include="Lyo.Common.Core" Version="3.0.0" />
<PackageReference Include="Lyo.Common.Core" />
paket add Lyo.Common.Core --version 3.0.0
#r "nuget: Lyo.Common.Core, 3.0.0"
#:package Lyo.Common.Core@3.0.0
#addin nuget:?package=Lyo.Common.Core&version=3.0.0
#tool nuget:?package=Lyo.Common.Core&version=3.0.0
Lyo.Common.Core
The slice of the old Lyo.Common that nothing else has to pay for is Lyo.Common.Core. It holds the identifier generators, the enum vocabulary, the string and scalar extensions,
the TypeConversion engine, the temp-spool and path helpers, cryptographic randomness, and the HTTP header and content-disposition constants — everything that needs no logger and
no configuration binder.
Reference this directly when you only need primitives. If you also need the record catalogs (LyoTypeInfo, FileTypeInfo, LanguageCodeInfo) reference
Lyo.Common.Metadata, which includes this package; for LyoJsonSerializerOptions and the scalar converters use
Lyo.Common.Json.
Every namespace here sits under the package name — Lyo.Common.Core plus .Conversion, .Attributes, .Extensions, .Enums, .Records, .Net, .Identifiers, .Security,
.Pathing, and .Archives. There is no longer a Lyo.Common package or namespace: the facade that once carried that name is gone, and each sibling owns its own.
Features
- ID generators (
Identifiers/).LyoGuid,Ksuid,Snowflake,NanoId,Ulid, andAutoIncrementIdGeneratorfor thread-safe, sortable identifiers. MediaContainer(Records/). Extensible container catalog (Mp4,WebM,Wav,Mp3,S16le, …) withFormat,Extension,TryFromName/TryFromFormat/TryFromExtension,Custom, andTryFromAudioFormat(TTSAudioFormatstays). Lookups are thread-safe. Resolve MIME viaFileTypeInfo.FromExtensionin Metadata; Core does not reference Metadata.- Enum vocabulary (
Enums/).FileTypeFlags(includingVideo),FileSizeUnit,FileTypeCategory,LyoTypeCategory,PortCategory,HttpStatusCodeCategory,HttpHeaderCategory,HttpHeaderPresence,LyoTypeEditorKind,TextLetterCase,SortDirection,USState/CountryCode, and the calendar and demographic enums. MIME strings live onMimeTypeInfoinLyo.Common.Metadata, not as a Core enum. - String and scalar extensions (
Extensions/).StringExtensions(ellipsis, truncate, null/whitespace probes),ScalarExtensions(ToScalar<T>and parsing helpers),DictionaryExtensions(GetValueAs<T>), andStreamExtensions(copy helpers, bounded reads). CollectionExtensions. Materialization helpers (AsReadOnlyCollectionOrToList,AsListOrToList) that skip a copy when the source is already the right shape.- HTTP primitives (
Net/).LyoHttpHeaders(X-Api-Key,Authorization,X-Request-Id,X-Correlation-Id, plus theCorrelationIdsprobe order),LyoContentEncodings(deflate/gzip/zstd/br/identity), andContentDisposition.Inline/.Attachment, which emit RFC 5987filename*alongside an ASCIIfilenameso non-Latin names survive every browser. UserAgentGenerator(Net/).Generate(UserAgentFormat, version)builds one desktop User-Agent for Chromium, Edge, Firefox, or Safari. The OS token comes from the host (RuntimeInformationandEnvironment.OSVersion). Callers pass format and version only.- Cryptographic random (
Security/CryptographicRandom).RandomNumberGenerator-backed int, byte, and string helpers. Other Lyo packages use this instead ofSystem.Randomfor security-adjacent work. - Conversion surface (
Conversion/). TheTypeConversionengine (GetUnderlyingType,ConvertTo,EnumOrDefault<T>,EnumOrNull<T>,IsObjectEnumerable),TypeConversionException(carryingSourceType,Value,TargetType), andTypeConversionExtensions, the reflection helpersIsNullable(),IsNumericType(),GetCollectionElementType(),IsCollectionType(),IsObjectEnumerable(),GetFriendlyTypeName(), andTryGetAsEnumerable<T>(). ByteConvert(Conversion/).GetBytes/GetStringtake anEncodingand use UTF-8 when it is omitted, including span overloads onnetstandard2.0. Hex has no separators. Upper hex matchesConvert.ToHexString.FromHexaccepts either letter case and rejects whitespace.CharsetEncodingbuffer methods,HexEncoding, andBinaryEncodingcall this.LyoReflection. Extension members onType,object,Expression,MemberInfo,PropertyInfo, andFieldInfo: ignore-caseFindProperty/FindField/FindMethod, dottedGetPropertyValue/SetPropertyValue,TryGetMemberPath,PublicStaticFields<T>catalog discovery,IsScalar/IsSimple, andTryCreateInstance/DefaultValue. Named so it does not clash withSystem.Reflection.- Temp and path handling (
Pathing/).PathHelpersfor cross-platform joining, normalization, and traversal rejection against aPathStyle(Windows/Posix/Native), andTempSpoolfor scratch directories and files with best-effort cleanup.TryDeleteDirectory/TryDeletereturnfalserather than logging, so the caller decides whether a failed cleanup is worth a log line. - ZIP archives (
Archives/).ZipFileBuilder.Create()queues bytes, text, streams, and disk files.Openloads an existing archive for update, andRemovedrops an entry.Buildreturns bytes.BuildTo/BuildToAsyncwrite a caller stream, andBuildToFilewrites a path.WithCompressionLevel(default optimal) andWithCommentare archive options.ZipEntryOptionsoverrides compression, last-write time, comment, and Unix mode (0755is0x1ED) on one entry. Disk adds on non-Windows hosts keep the file mode.AddDirectorykeeps relative paths, includes empty directories, and takes an include filter. Entry names must be relative and must not contain a..segment. Adds after build throw; a secondBuildreturns the same bytes.ZipFileReaderlists entries, reads one, andExtractTorestores time and mode while refusing a path that escapes the destination. Utilities. File-size conversion acrossFileSizeUnit(1024-based), URI redaction for secret-looking query values, SHA256 over a buffer, path, or stream, andGetPropertyPath/GetPropertyName/IsScalarTypewrappers overLyoReflection.Disposable. Base class plus lambdaIAsyncDisposable/IDisposablefactories.- Context bags.
ContextBag<TKey>is a single-threaded map.new ContextBag()ignores case;caseSensitive: truekeeps ordinal keys.Setstores a value or a factory that runs on the first read.TryGetAs<T>andGetRequired<T>convert throughTypeConversion.CreateScopereads the parent and writes only the child.Freezelocks that bag's own slots.BindableBagreads public properties from bound objects on lookup. StringValueAttribute(Attributes/). Attaches a string token to an enum field; the metadata extensions inLyo.Common.Metadataread it.
Examples
Context bag
using Lyo.Common.Core;
var bag = new ContextBag();
bag.Set("Atk", 10);
bag.Set("Damage", current => current.GetRequired<int>("Atk") * 2);
var stats = new BindableBag();
stats.Bind(player); // Atk is read from the object on lookup
int atk = stats.GetRequired<int>("Atk");
Identifiers and scalars
using Lyo.Common.Core.Identifiers;
using Lyo.Common.Core.Extensions;
string ksuid = Ksuid.NewId(); // sortable 27-char base62
string nano = NanoId.New(size: 21); // url-safe random
string ulid = Ulid.NewUlid();
Guid guid = LyoGuid.NewSequential(); // UUID v7-style, for index locality
int parsed = "42".ToScalar<int>();
string shortened = ksuid.Truncated(start: 6, end: 20);
Member paths and scalars
using Lyo.Common.Core;
object? city = person.GetPropertyValue("Address.City");
bool isScalar = typeof(Guid?).IsScalar();
string? path = expr.TryGetMemberPath(); // Convert-wrapped Guid? lambdas included
Pack a ZIP
using System.Text;
using Lyo.Common.Core.Archives;
var zipBytes = ZipFileBuilder.Create()
.WithComment("bundle")
.AddFile("file1.txt", Encoding.UTF8.GetBytes("Content 1"))
.AddFile("run.sh", "#!/bin/sh", options: new() { UnixMode = 0x1ED })
.AddFileFromPath("/path/to/report.pdf")
.AddDirectory("/path/to/docs", "docs/")
.Build();
using var reader = ZipFileReader.Open(new MemoryStream(zipBytes));
reader.ExtractTo("/path/to/out");
Downloads and secure randomness
using Lyo.Common.Core.Net;
using Lyo.Common.Core.Security;
// RFC 5987 filename* plus an ASCII fallback, so non-Latin names survive every browser.
response.Headers["Content-Disposition"] = ContentDisposition.Attachment("отчёт.pdf");
response.Headers[LyoHttpHeaders.CorrelationId] = correlationId;
string token = CryptographicRandom.GetString(32);
Identifier matrix
| Generator | Sortable | Length | Notes |
|---|---|---|---|
Ksuid |
(time-prefix) | 27 chars (base62) | Drop-in monotonic-ish id; good URL safety. |
LyoGuid |
(sequential) | 36 chars (GUID) | UUID v7-style for DB index locality. |
NanoId |
configurable (default 21) | URL-safe random; collision rates documented per length. | |
Snowflake |
int64 | Configurable worker + datacenter ids. | |
Ulid |
26 chars (Crockford base32) | ULID spec. | |
AutoIncrementIdGenerator |
int64 | Pure in-process counter for tests / fixtures. |
ZipFileBuilder
Create(). Start an empty builder. Entries and options are queued until build.Open(path)/Open(stream, leaveOpen). Load an existing archive for update. The stream must be seekable. Opening records entry names and the archive comment and does not read entry bodies.Remove(entryName). Drop a queued entry, or mark an existing entry for deletion. An unknown name throws. Adding that name again is allowed after it is removed.WithCompressionLevel(CompressionLevel)/WithComment(string?). Archive-wide options. Compression defaults to optimal and applies to entries that do not override it.AddFile(name, byte[] | Stream | string, ZipEntryOptions?). Queue one entry. The string overload encodes as UTF-8 unless anEncodingis passed. Streams stay open until build and are not disposed.ZipEntryOptions.UnixModestores permission bits in the high half of the external attributes.AddFiles(IReadOnlyDictionary<string, byte[]>)/AddFiles(params string[] filePaths). Queue several entries. Disk paths use the file name, the file's last-write time, and, off Windows, the file mode.AddFileFromPath(path, entryName?)/AddDirectory(path, entryPrefix, include?). Queue a file or a directory tree. Empty directories become trailing-slash entries.includereceives the relative path. Disk adds copy the Unix mode unlessUnixModeis set.Build()/BuildAsync(CancellationToken). Write the archive to a byte array. Further adds throw. A later build returns the same bytes.BuildTo(Stream)/BuildToAsync(Stream, CancellationToken)/BuildToFile(path)/BuildToFileAsync(path, CancellationToken). Write the archive to a stream or path.BuildToFilecallsBuildTo. Updating a different destination copies the original archive, then updates it. Untouched entries stay compressed.
ZipFileReader
Open(path)/Open(stream, leaveOpen). Read an archive.Open(path)owns the file stream.CommentandEntries. EachZipFileEntryexposesName,Length,CompressedLength,LastWriteTime,Comment,UnixMode, andIsDirectory.Read(entryName)returns the uncompressed bytes.OpenEntry(entryName)returns a stream; dispose it before opening another entry.ExtractTo(directory)/ExtractToAsync(directory, CancellationToken). Create directories and files under the destination, restore last-write time and Unix mode, and throwInvalidFormatExceptionwhen an entry path escapes the destination.
Why this package exists
A reference to Lyo.Common just to use an enum also dragged in a configuration binder and a logging abstraction. Record catalogs and the JSON contract now live in their own
packages, so taking a dependency for FileTypeFlags no longer brings those along. System.Text.Json is still referenced here on netstandard2.0 only, for the JSON branch of
TypeConversion. On net10.0 the serializer is in-box; the split is about a clearer graph, not a smaller payload.
Dependencies
Generated from ProjectReference / PackageReference (same model as docs/Lyo.ProjectGraph.html).
Lyo.Exceptions(direct, lyo)Microsoft.Bcl.AsyncInterfaces10.0.5(direct, microsoft, netstandard2.0)System.Memory4.6.3(direct, microsoft, netstandard2.0)System.Text.Json10.0.5(direct, microsoft, netstandard2.0)
| Product | Versions 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. |
-
.NETStandard 2.0
- Lyo.Exceptions (>= 3.0.0)
- Microsoft.Bcl.AsyncInterfaces (>= 10.0.5)
- System.Memory (>= 4.6.3)
- System.Text.Json (>= 10.0.5)
-
net10.0
- Lyo.Exceptions (>= 3.0.0)
NuGet packages (136)
Showing the top 5 NuGet packages that depend on Lyo.Common.Core:
| Package | Downloads |
|---|---|
|
Lyo.KeyStore
Key management interface and local implementation for encryption key storage, versioning, and rotation. |
|
|
Lyo.PackageMetadata
Multi-ecosystem package catalog types and IPackageMetadataStore for stack traces and persistence adapters. |
|
|
Lyo.Diagnostic
Diagnostic utilities for classifying exceptions, decoding and sanitising stack traces, and enriching structured logs for observability. |
|
|
Lyo.EntityReference.Models
Shared entity reference (EntityRef), composite id encoding, optional logical CLR type names, JSON converter, and association row contracts for Lyo modules. No database dependency. |
|
|
Lyo.Common.Metadata
Lyo registry records and the extensions that bridge enums to them: file type, MIME, language, social platform, port, HTTP status, geographic, and CLR type metadata. |
GitHub repositories
This package is not used by any popular GitHub repositories.