DRN.Framework.SharedKernel 0.11.0-preview006

Prefix Reserved
This is a prerelease version of DRN.Framework.SharedKernel.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package DRN.Framework.SharedKernel --version 0.11.0-preview006
                    
NuGet\Install-Package DRN.Framework.SharedKernel -Version 0.11.0-preview006
                    
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="DRN.Framework.SharedKernel" Version="0.11.0-preview006" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DRN.Framework.SharedKernel" Version="0.11.0-preview006" />
                    
Directory.Packages.props
<PackageReference Include="DRN.Framework.SharedKernel" />
                    
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 DRN.Framework.SharedKernel --version 0.11.0-preview006
                    
#r "nuget: DRN.Framework.SharedKernel, 0.11.0-preview006"
                    
#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 DRN.Framework.SharedKernel@0.11.0-preview006
                    
#: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=DRN.Framework.SharedKernel&version=0.11.0-preview006&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=DRN.Framework.SharedKernel&version=0.11.0-preview006&prerelease
                    
Install as a Cake Tool

master develop Quality Gate Status

Security Rating Maintainability Rating Reliability Rating Vulnerabilities Bugs Lines of Code Coverage

DRN.Framework.SharedKernel

Lightweight package containing domain primitives, exceptions, and shared code suitable for Contract and Domain layers.

TL;DR

  • Target framework - Targets .NET 11; includes build-time domain analyzers
  • Domain primitives - SourceKnownEntity, AggregateRoot, DomainEvent for DDD patterns
  • Typed exceptions - ExceptionFor creates exceptions with status codes consumed by DRN Hosting
  • JSON conventions - Global System.Text.Json defaults with camelCase, enums-as-strings
  • Shared extensions - Casing and safe path helpers for lower-layer packages
  • Source Known IDs - Internal long keys and external Guid identifiers with type and partition validation

Table of Contents


DDD project layers

Name a participating project <organization alias>.<layer>[.<module>]. For example, DRN.Nexus.Domain.Orders has the organization alias DRN.Nexus, the layer Domain and the module Orders. Projects without a recognized layer skip this naming rule. See layer responsibilities and naming examples.

Hosted requires direct project references to Application and Infra. Infra requires a direct Domain project reference with corresponding subdomains. Each Domain project must directly reference at least one Contract project and may consume additional Contract packages. See the diagnostic reference and scaffolding guide.

Project and ownership terminology

Term Meaning Example
Organization alias (project alias) All project-name segments before the layer. Multiple aliases can coexist in one solution. DRN.Nexus in DRN.Nexus.Infra
Layer (project role) The architectural responsibility identified by a project-name segment. The seven layers are Application, Domain, Contract, Utils, Hosted, Infra and SharedKernel. Infra implements persistence for domain types.
Module The optional single segment after the layer. It distinguishes projects within the same layer and alias. Orders in DRN.Nexus.Infra.Orders
Root namespace The namespace from which placement is measured. For a participating project, RootNamespace matches the full project name, including case. The assembly name may differ. Sample.Infra in Sample.Infra.Databases.QA
Project stem The segment that supplies the default domain in project layout. Use the module when present, otherwise the final segment of the organization alias. Orders in DRN.Nexus.Infra.Orders, or Nexus in DRN.Nexus.Infra
Domain The top-level business boundary. The Domain layer holds its model. Other layers can serve the same boundary. Billing in Billing.Domain and Billing.Infra
Subdomain A business capability or technical area within a domain. Its name normally comes from the owning namespace and folder. QA in Sample.Domain.QA.Tag
Domain layout Project (default) takes the domain from the project stem or an explicit DrnDomain. Folders takes the domain and subdomain from the first two ownership folders. In project layout, an explicit domain must match a named module. For a Billing domain and Sales subdomain, the owner path is Sales/ in project layout and Billing/Sales/ in folder layout.
Owner / owner path The domain and subdomain responsible for a type. In a path such as Databases/<owner>/, substitute the subdomain in project layout or <domain>/<subdomain> in folder layout. The analyzer also tracks the declaring assembly and named module when comparing owners. Databases/QA/ or Databases/Billing/Sales/
Entity stem / role stem The type name with its role suffix removed. The entity stem names the entity's folder inside its subdomain. TagEntity gives Tag, CategoryDto gives Category, and SalesContext gives Sales.

In the Sample app, Sample.Domain/QA/Tag/TagEntity.cs puts the Tag entity stem inside the QA subdomain. Its repository lives at Sample.Infra/Databases/QA/Repositories/TagRepository.cs. Both paths identify the same owner: domain Sample, subdomain QA. See ownership and persistence for explicit subdomain mappings and cross-project ownership checks.

QuickStart: Beginner

Define an entity and collect a domain event. SharedKernel supplies the domain types; EntityFramework integration assigns missing IDs during save and wires ID operations during save or materialization.

using DRN.Framework.SharedKernel.Attributes;
using DRN.Framework.SharedKernel.Domain;

[DomainOnly]
public enum UserEntityTypes : byte { User = 1 }

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class UserEntityTypeAttribute(UserEntityTypes kind)
    : EntityTypeAttribute<DefaultApp>((byte)kind);

[UserEntityType(UserEntityTypes.User)]
public class UserEntity : AggregateRoot
{
    [Personal]
    public string Name { get; private set; }

    public override UserDto ToDto() => new(this);

    public UserEntity(string name)
    {
        Name = name;
        AddDomainEvent(new UserCreated(this)); // Collected on the entity for infrastructure handling
    }
}

public class UserCreated(UserEntity user) : EntityCreated(user)
{
    [Personal]
    public string UserName => user.Name;
}

The constructor alone does not assign EntityId or CreatedAt. The event reads EntityId from its entity, so it observes the ID assigned later. Event collection does not publish the event.

QuickStart: Advanced

Place the example UserDto in the Contract project's subdomain and Users folder. The example exposes inherited identity and timestamps only. Use the UserEntity above with a repository implementation. This service maps entities to DTOs, filters by creation date, and reports missing users:

using System;
using System.Threading.Tasks;
using DRN.Framework.SharedKernel;
using DRN.Framework.SharedKernel.Domain;
using DRN.Framework.SharedKernel.Domain.Pagination;
using DRN.Framework.SharedKernel.Domain.Repository;

public class UserDto(SourceKnownEntity? entity = null) : Dto(entity);

public class UserService(ISourceKnownRepository<UserEntity> repository)
{
    public async Task<PaginationResultModel<UserDto>> GetUsersAsync(PaginationRequest request)
    {
        var filter = EntityCreatedFilter.After(DateTimeOffset.UtcNow.AddDays(-30));
        var result = await repository.PaginateAsync(request, filter);

        return result.ToModel(user => user.ToDto());
    }

    public async Task<UserDto> GetUserAsync(Guid id)
    {
        var user = await repository.GetOrDefaultAsync(id);
        if (user is null)
            throw ExceptionFor.NotFound($"User {id} not found");

        return user.ToDto();
    }
}

Domain Primitives

Domain types live in DRN.Framework.SharedKernel.Domain. Persistence integration belongs to DRN.Framework.EntityFramework and DrnContext.

Entity and AggregateRoot

  • SourceKnownEntity: Holds internal identity, external identity, domain events, and audit timestamps.
  • AggregateRoot: Marker class for DDD aggregate roots.
  • AggregateRoot<TModel>: Adds a writable Model through IEntityWithModel<TModel>, where TModel : class. Model starts as null! and must be populated by the application.

Entity and aggregate base constructors accept an optional internal long id = 0.

Entity member Contract
long Id Internal setter; ignored by JSON; column order IdColumnOrder = 0
Guid EntityId External ID from EntityIdSource; serialized under the name Id
DateTimeOffset CreatedAt Derived from the encoded ID timestamp
DateTimeOffset ModifiedAt Protected internal setter; concurrency check; ModifiedAtColumnOrder = 1
SourceKnownEntityId EntityIdSource Internal setter; ignored by JSON
abstract Dto ToDto() Concrete entities override this covariantly to return their Contract DTO via new(this)

SourceKnownEntity implements IHasEntityId, IEquatable<SourceKnownEntity>, and IComparable<SourceKnownEntity>. See SourceKnownEntity.cs and AggregateRoot.cs.

Application Partitions

IAppId requires static abstract byte AppId { get; } in the range 0..127. Define an attribute for the domain and apply it to each eligible concrete entity with its enum member. The attribute accepts a byte-backed enum and forwards the value to EntityTypeAttribute<TApp>(byte).

Partition AppId and Value Attribute example
DefaultApp 0 [UserEntityType(UserEntityTypes.User)] in the QuickStart
NexusApp 126 [NexusEntityType(NexusEntityTypes.User)] in the Nexus domain
TestApp 127 Define a fixture attribute derived from EntityTypeAttribute<TestApp>

IAppId.DefaultAppId, NexusAppId, and TestAppId expose these constants; MaxAppId is 127. Different partitions may reuse an entity type byte. See IAppId.cs.

Compile-Time Roslyn Analyzers

The diagnostic reference groups all analyzer and generator rules by requirement and lists their severity settings.

Declare legacy subdomain names once with DrnSubdomainAlias in shared Directory.Build.props. DRNSTRUCTURE009 checks handwritten types in Contract, Domain, Application services, Infra persistence and Hosted controllers. Alias configuration and severity

DRNDTO004 places entity-owned requests and responses beside their DTO. Declare DrnContractMessage in the Contract project when a message has a different name or is shared across entities. Message ownership examples

The analyzer and code-fix assemblies target net10.0 for IDE compiler-host compatibility. Runtime and application projects remain on net11.0. Tooling requires a .NET 10 or newer host with compatible Roslyn 5.12 APIs. An IDE worker's runtime is independent of the application's target framework. After rebuilding changed tooling assemblies, reload the solution if the IDE still reports assembly-load failures.

Data classification

Register one project catalog as EmbeddedResource or AdditionalFiles. Build targets forward it to compiler analysis and publish metadata retained in reference assemblies. Analyzers inherit catalogs from referenced SharedKernel consumers without loading dependency code. diagnostic-rules.json is also accepted. Identical files are deduplicated. Distinct own catalogs are rejected. Invalid catalogs report DRNCLASSIFICATION007. Rules are isolated per compilation. Backend runtime uses explicit classifications rather than catalog name matching. See configuration and schema.

The shared catalog includes cvv, cvc, pincode, username, firstname, lastname, dateofbirth, birthdate, and iban. Matching public readable properties require classification or a reviewed false-positive annotation, including case and separator variants.

DRNCLASSIFICATION005 exempts EF migration column definitions and constraint selectors recognized through EF API symbols and column-operation metadata. Data objects and logging inside migrations remain checked. See schema boundaries.

DRNCLASSIFICATION006 checks statically known dictionary keys, including nested initializers and direct local writes. Use AddDictionary/SanitizeDictionary classifications or an exact adjacent DiagnosticNameExemption comment. Configured analyzer paths and other children remain checked. Exploration is bounded. Dynamic and unexamined keys have no runtime name fallback. See dictionary classifications.

Configured paths remain enforced at AddDictionary/SanitizeDictionary calls. Inline positive classification constructors with constant exact keys protect their whole entries. NonSensitive and unknown classification expressions cannot waive configured paths. Dictionary name checks, including ILogger scopes, accept known null, empty and exact [redacted] values.

DRNCLASSIFICATION001 through DRNCLASSIFICATION006, DRNCLASSIFICATION008, DRNCLASSIFICATION011, and DRNCLASSIFICATION012 analyze generated sources without reporting diagnostics in generated code. Runtime classification remains active for DRN capture APIs.

DRNCLASSIFICATION003 accepts the exact compile-time [redacted] value and checks AddIfNotNullOrEmpty except constant null/empty values. Exact adjacent comments acknowledge reviewed names. Configured analyzer paths, classified values, declarations, and children remain enforced. Backend runtime uses explicit classifications without scanning names again.

Browser diagnostics and compiler analysis consume the same baseline catalog, including ipadd and client. Reviewed operational IP addresses and client identifiers need property exemptions or exact capture comments. Backend runtime protection uses explicit classifications.

Compiler checks cover statically known values and paths. See application responsibilities for dynamic data.

DRNCLASSIFICATION008 checks sensitive ILogger placeholders, scope dictionary keys, and direct classified-property captures. Remove or redact sensitive values. Standard ILogger does not apply DRN runtime redaction. Reviewed name-only false positives can use adjacent comments. DRNCLASSIFICATION009 reports malformed comments. DRNCLASSIFICATION010 warns only on unused DiagnosticNameExemption comments, never redundant attributes or reason/policy exemptions. DRNCLASSIFICATION011 fails captures that exceed the model-analysis work limit so configured paths cannot silently escape verification. Capture a smaller model or explicitly classify sensitive subtrees. See logging boundaries.

Diagnostic classification also applies to all public readable instance non-indexer model properties in directly and transitively dependent projects, even without logging calls. DRNCLASSIFICATION001 requires classification or explicit Sensitive(false) for matching names. DRNCLASSIFICATION002 rejects invalid opt-outs and offers Use Sensitive(true) as an individual code fix. DRNCLASSIFICATION003 reports matched scalar/untyped capture paths and external property names, and DRNCLASSIFICATION004 identifies unsupported custom Microsoft classification families. DRNCLASSIFICATION005 requires matching anonymous properties, including nested and inferred members, to move to an annotated named class or record. Named model properties own classification without built-in logging-prefix matches. [IgnoreLog], reason strings and capture policies do not suppress declaration requirements. Personal/Sensitive-derived company attributes are supported. See classification, code fixes, and runtime boundaries.

DRNCLASSIFICATION012 reports a direct property capture that exceeds the 256 interface-property scan limit before classification can be determined. Remove the capture, explicitly redact its value, or declare classification directly on the captured property or type.

Controller authorization

DRNAUTHORIZATION001 checks inherited and custom public actions, including actions hidden with IgnoreApi. [NonAction] methods are exempt. Inherited class and overridden-action policies count. Bare [Authorize], roles-only declarations and blank policy names do not establish an explicit named policy. Anonymous access bypasses authorization even if a policy is present. Register policies with ASP.NET Core and implement resource checks in application code. See Source-Known Controllers.

Entity identity

DRN.Framework.SharedKernel includes these identity checks for referencing projects and NuGet consumers.

Diagnostic ID Severity Title Description
DRNENTITY001 Error Missing entity type attribute Concrete, effectively non-private SourceKnownEntity classes must declare a derived domain attribute.
DRNENTITY002 Error Duplicate EntityType value Every entity class in the domain compilation and referenced assemblies must have a unique EntityType byte value per AppId.
DRNENTITY003 Error Invalid entity type attribute usage Entity type attributes must not be placed on abstract classes, private classes, or non-SourceKnownEntity types.
DRNENTITY004 Warning Duplicate entity class name Warns when multiple entities across the domain model share identical unqualified class names within the same AppId to prevent EF Core and messaging collisions.
DRNENTITY005 Error Multiple AppIds in single compilation Allows at most one non-test partition unless a multi-application or test exemption applies. TestApp (127) is excluded from the count.
DRNENTITY006 Error Unresolvable or non-constant application partition A concrete IAppId implementation must publish a constant partition and return it from its getter, including in projects that declare no entities.
DRNENTITY007 Error AppId outside the supported range Concrete IAppId implementations and entity type attribute declarations must use a partition from 0 through 127, including in projects that declare no entities.
DRNENTITY008 Error Unsupported entity attribute constructor Each derived attribute in the chain must declare one constructor that forwards one byte-backed enum parameter unchanged. Applying the byte-taking framework attribute directly also produces this error. For an entity in a referenced assembly, the message names the assembly and entity to update.
DRNENTITY009 Error Invalid constant application partition Constant AppId values in EntityTypeId construction and property initializers/assignments must be within 0..127.
DRNENTITY010 Error Undefined constant entity ID format Constant SourceKnownEntityIdFormat arguments and assignments must be defined enum values.
DRNENTITY011 Warning Hidden entity identity member Descendant members must not hide Id, EntityId, or EntityIdSource, with or without the new keyword.
DRNENTITY012 Warning Concrete generic entity Concrete, effectively non-private entities must not introduce type parameters or be nested inside generic containers. Use abstract generic bases with separately attributed concrete descendants.
DRNENTITY013 Error Use a concrete entity type Rejects known abstract entities in entity/utility/repository metadata calls, method groups, direct typeof lookups, and Source-Known repository bindings, including derived types, declarations, and aliases.
DRNENTITY014 Error Entity ID operations are not initialized Rejects GetEntityId, ToSecure, or ToPlain calls on provably fresh entities in straight-line code, including simple local aliases and constructor this calls.
var identity = new EntityTypeId(7, 200); // DRNENTITY009
operations.Parse(externalGuid, (SourceKnownEntityIdFormat)99); // DRNENTITY010
SourceKnownEntity.GetEntityTypeId<AggregateRoot>(); // DRNENTITY013
ISourceKnownRepository<AggregateRoot> repository; // DRNENTITY013

// Resolve the concrete runtime type through the instance overload instead.
SourceKnownEntity.GetEntityTypeId(aggregate);

Usage checks apply to test projects too. DRNENTITY009 and DRNENTITY010 inspect constants without propagating mutable local values; use non-constant inputs for runtime rejection tests. Dynamic values still require runtime validation.

DRNENTITY013 allows runtime-instance metadata overloads, application-only Validate<TApp>, unresolved type parameters, and unbound generic definitions. It does not trace dynamic Type values or consumer wrappers. Use concrete bindings such as ISourceKnownRepository<OrderEntity>: forwarding TEntity through SourceKnownRepository<AppDbContext, TEntity> is valid, but later binding it to AggregateRoot is rejected. No public parameterless constructor is required.

Entity ID operations are attached during EF materialization or while saving an Added entity, before the database save succeeds. Constructing an entity with an existing numeric ID, calling Add, or obtaining an ID record through the utility does not itself attach operations. Initialization and IsPendingInsert do not prove persistence.

var order = new OrderEntity(); // Constructor must be available and provably passive.
var alias = order;
alias.GetEntityId<CustomerEntity>(customerGuid); // DRNENTITY014

// Use injected operations when working before entity initialization.
var customerId = ids.Validate<CustomerEntity>(customerGuid);

DRNENTITY014 recognizes source constructor chains with empty bodies or instance-field/auto-property assignments from constants/parameters, constant member initializers, and empty standard List<T> initializers. Compiled constructors and object initializers are unknown. Tracking stops at unknown calls, arbitrary getters/setters, control flow, awaits, captures, or ref aliases. Potentially null inputs and static metadata helpers are excluded. No diagnostic proves initialization; runtime guards remain required.

Derived entity attributes use a pass-through constructor:

using DRN.Framework.SharedKernel.Attributes;
using DRN.Framework.SharedKernel.Domain;

[DomainOnly]
public enum DomainEntityTypes : byte { Order = 2 }

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class DomainEntityTypeAttribute(DomainEntityTypes kind)
    : EntityTypeAttribute<DefaultApp>((byte)kind);

Parameter names may differ. Primary and ordinary constructors are supported. Reordered, additional, fixed-value, overloaded, or transformed mappings produce DRNENTITY008. AppId comes from the generic TApp binding. A derived property hiding AppId does not change it.

For a custom partition, publish a constant such as public const byte Value = 5; and return it from public static byte AppId => Value;. When source is available, the analyzer checks the getter that implements IAppId.AppId, including explicit interface implementations. A mutable or branching getter that cannot be verified against the constant produces DRNENTITY006. Consumers of compiled partitions use the published constant.

The analyzer checks source attribute declarations even when no entity uses them yet. For compiled references, Roslyn exposes constructor signatures but not bodies. Signatures are checked; forwarding relies on producer-side validation. Run the analyzer when building domain attribute libraries. It cannot prove forwarding in a precompiled library built with validation disabled.

An entity is effectively private if it or any containing type is private. Such entities are excluded from required-attribute and collision checks in both local and referenced analysis; annotating one locally reports DRNENTITY003.

  • Cross-assembly checks include entities declared in the current project and in referenced domain and DRN.Framework.* assemblies. Direct and transitive project references participate when built against a compatible SharedKernel assembly. The analyzer skips entities declared in referenced System.* and Microsoft.* assemblies and in external assemblies referenced directly or transitively by DRN Framework. An application entity still participates when its base type comes from a skipped assembly. A shared reference contributes its entities once.
  • DRNENTITY005 exemptions: Set <AllowMultipleAppIds>true</AllowMultipleAppIds>, <IsTestProject>true</IsTestProject>, or <UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>. Test assembly names also qualify when they contain .Test., start with Test., or end with .Tests or .Test, case-insensitively.

See SourceKnownEntityTypeAnalyzer.cs for diagnostic checks and the package project for analyzer packaging.

Identity Rule: Always use Guid EntityId (mapped as Id in DTOs) for all public-facing contracts, API route parameters, and external lookups. The internal long Id must never be exposed outside the infrastructure/domain boundaries.

DTO Mapping Rule: DTOs should implement a primary constructor accepting a SourceKnownEntity? to automatically map Id, CreatedAt, and ModifiedAt. Avoid manual mapping of these fields.

Entity and DTO Exposure Prohibition: Never expose entities or internal Dto types through public APIs or Contract messages. Map to explicit Contract *Request and *Response models instead. Entities are only permitted in Razor Pages (Internal UI).

The advanced quickstart defines UserDto once and uses its base constructor for identity and timestamp mapping. Dto.AdditionalData stores JSON extension data. See Dto.cs.

Domain Events

Entities collect events through AddDomainEvent and expose them through GetDomainEvents. SharedKernel does not supply publication or outbox dispatch. EF save interception invokes lifecycle hooks; override GetCreatedEvent, GetModifiedEvent, or GetDeletedEvent to supply events. Each hook returns null by default.

Event contract excerpt from DomainEvent.cs:

public interface IDomainEvent
{
    Guid Id { get; }
    DateTimeOffset Date { get; }
    Guid EntityId { get; }
}

public abstract class DomainEvent(SourceKnownEntity sourceKnownEntity) : IDomainEvent
{
    public Guid Id { get; protected init; } = Guid.NewGuid();
    public Guid EntityId => sourceKnownEntity.EntityId;
    public DateTimeOffset Date { get; protected init; } = DateTimeOffset.UtcNow;
}

public abstract class EntityCreated(SourceKnownEntity sourceKnownEntity) : DomainEvent(sourceKnownEntity);
public abstract class EntityModified(SourceKnownEntity sourceKnownEntity) : DomainEvent(sourceKnownEntity);
public abstract class EntityDeleted(SourceKnownEntity sourceKnownEntity) : DomainEvent(sourceKnownEntity);

SourceKnownEntityId & SourceKnownId

The identifier system has three forms:

Form Representation Purpose
Source Known ID (SKID) 64-bit long, 8 bytes Sortable database key containing creation time, application, instance and sequence fields
Source Known Entity ID (SKEID) 128-bit Guid Supports integrity, entity-type, and application-partition validation without a database lookup
Secure SKEID 128-bit Guid Conceals the encoded identity fields

ISourceKnownEntityIdOperations defines Generate, nullable/nonnullable Parse, all Validate overloads, ToSecure, and ToPlain in SharedKernel. Utils provides these operations through ISourceKnownEntityIdUtils. EntityFramework makes ID operations available on saved and queried entities. ID validation checks structure and identity metadata; application authorization still controls access to the entity.

Parse(Guid, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) accepts ConfiguredDefault, Secure, Plain or Auto from DRN.Framework.SharedKernel.Domain. ConfiguredDefault selects the immutable ISourceKnownEntityIdOperations.DefaultFormat, initialized from Nexus settings (Secure or Plain). Secure accepts only secure IDs, Plain accepts only plain IDs, and Auto accepts either valid form. Domain GUID helpers apply the selected format and requested identity checks. Conversions accept both forms. Format is non-nullable: omit it or pass ConfiguredDefault instead of null. See Utils parsing and validation.

Record contract excerpt from SourceKnownEntityId.cs:

public readonly record struct SourceKnownId(
    long Id,
    DateTimeOffset CreatedAt, // 250ms tick precision
    uint InstanceId,          // 18-bit per-tick sequence
    byte AppId,               // 7 bits, 0..127
    byte AppInstanceId        // 6 bits, 0..63
);

public readonly record struct SourceKnownEntityId(
    SourceKnownId Source,
    Guid EntityId,
    byte EntityType,
    bool Valid,
    bool Secure
);

Valid reports parsing validity. Secure identifies the encrypted form of EntityId. EntityTypeId combines EntityType and Source.AppId. Use the ID operations API to generate, parse, and convert identifiers.

SourceKnownEntityId equality and hashing use the external GUID. Ordering uses application partition, entity type, and numeric source ID. Different GUID representations of the same source identity can compare as zero while remaining unequal. Consequently, hash-based and sorted collections can deduplicate these values differently. Normalize representations or supply an explicit comparer when collection identity matters.

Numeric Source-Known IDs can be negative. Their sign does not indicate validity.

Trusted minimum generation time

SourceKnownGenerationTime sets one process-wide epoch and minimum UTC for new IDs. The default origin is 2025-01-01T00:00:00Z; the default minimum is 2026-09-09T00:00:00Z. Only encoded epoch 0, including both halves of its 33-bit timestamp range, is supported.

Configure before startup or first ID/epoch use:

SourceKnownGenerationTime.Initialize(
    minimumUtc: "2026-09-01T00:00:00Z",
    defaultEpoch: "2025-01-01T00:00:00Z");

An override can move the minimum earlier or later. Supplying an epoch requires an explicit minimum in the same call. Both inputs require ISO 8601 UTC ending in Z or +00:00, with seconds and up to seven fractional digits. The minimum rounds upward to a 250ms boundary relative to the epoch; an unrepresentable minimum fails.

Startup or first generation freezes both values before checking time, even if that check fails. Reading the configured epoch, parsing IDs, and converting historical dates also freeze the pair. Identical settings or omitted overrides retain it; later conflicts fail. Historical parsing and GUID reconstruction from existing numeric IDs do not enforce the generation floor.

Keep the origin unchanged across every service and restart using a dataset. IDs do not store it, so changing it changes the interpretation of existing timestamps. Generation rejects times outside epoch 0 rather than rolling over. Hosted configuration uses SourceKnownIdSettings; see Utils configuration and clock behavior.

Source baseline contract

The default minimum is the same in every build configuration. It detects clocks below the configured floor but does not prove current UTC or prevent rollback across restarts.

ID Validation & Retrieval Strategies

Context Call Requirement
Service sourceKnownEntityIdUtils.Validate<UserEntity>(externalGuid) Inject the Utils ID utility
Repository userRepository.GetEntityId(externalGuid) Use ISourceKnownRepository<UserEntity>
Domain entity userInstance.GetEntityId<UserEntity>(externalGuid) Entity ID assigned and ID operations wired

GetEntityId helpers throw UnprocessableEntityException while the current entity is pending insertion. Missing ID operations cause ConfigurationException. For a parsed SourceKnownEntityId, choose validation by the expected boundary:

Method Checks
ValidateId() Stored Valid is true; no expected identity
Validate<TEntity>() Stored validity, entity type and the entity's declared application partition
Validate(EntityTypeId expected) Stored validity and both supplied identity components

Parsed-record validation has no format parameter and accepts either representation. It neither reads settings nor reauthenticates the GUID. Records are publicly constructible, so treat them as trusted internal values rather than authenticated transport input. Operations Parse/Validate authenticate untrusted GUIDs and select the format: ConfiguredDefault uses DefaultFormat, while Auto enables mixed-format detection. Undefined enum values throw ArgumentOutOfRangeException at that parsing boundary.

Identity validation requires an expected application partition: use Validate<TEntity>() to obtain it from the entity declaration, or Validate(new EntityTypeId(entityType, expectedAppId)) to supply both components. EntityTypeId requires both constructor arguments, including explicit 0 for the default partition, and has no implicit conversion from byte. Validation never derives the expected partition from the incoming ID.

Domain helpers follow the same contract for GUID and numeric IDs: use GetEntityId<TEntity>(id) or GetEntityId(id, new EntityTypeId(entityType, expectedAppId)), including nullable forms. The low-level GetEntityId(Guid, bool validate = true) helper checks parsing validity only, like ValidateId(). SharedKernel does not read application configuration; Utils supplies configured expectations and EF repositories supply the target entity's declared identity.

All domain GUID helpers and repository single/batch/enumerable GUID helpers accept an optional final format argument. It reaches the injected parser; omission uses its configured default. For example, entity.GetEntityId<UserEntity>(guid, SourceKnownEntityIdFormat.Plain) and repository.GetEntityIds(guids, format: SourceKnownEntityIdFormat.Auto). Undefined formats are rejected for null inputs and empty batches too. Numeric generation and conversions retain their existing behavior.

Secure ↔ Plain Conversion

Entities, repositories and the Utils utility expose ToSecure and ToPlain. Conversion validates the ID and is idempotent: an ID already in the requested form is returned unchanged. Entity conversion requires wired ID operations.

The following alternatives assume the named entity, repository or utility is available:

var secureFromEntity = userInstance.ToSecure(entityId);
var plainFromEntity = userInstance.ToPlain(secureFromEntity);

var secureFromRepository = userRepository.ToSecure(entityId);
var plainFromRepository = userRepository.ToPlain(secureFromRepository);

var secureFromUtility = sourceKnownEntityIdUtils.ToSecure(entityId);
var plainFromUtility = sourceKnownEntityIdUtils.ToPlain(secureFromUtility);

SourceKnownRepository

ISourceKnownRepository<TEntity> defines queries, mutations, identity conversion and pagination for AggregateRoot entities. EntityFramework supplies the default implementation. Subclasses own entity updates, additional filters and query includes.

Use IDomainService for pure business rules shared by domain objects. Pass the input values or aggregates into the rule. Keep persistence and orchestration in Application services. Register implementations of both IDomainService and ISourceKnownService<TEntity> as transient.

ISourceKnownService contracts in DRN.Framework.SharedKernel.Domain provide progressive service abstractions for AggregateRoot entities:

  • ISourceKnownService<TEntity> exposes read-only ISourceKnownRepository<TEntity> Repository.
  • ISourceKnownService<TEntity, TResponse> extends ISourceKnownService<TEntity> with Task<TResponse> CreateResponseAsync(TEntity entity, CancellationToken cancellationToken = default) and Task<TResponse[]> CreateResponsesAsync(IReadOnlyList<TEntity> entities, CancellationToken cancellationToken = default).
  • ISourceKnownService<TEntity, TResponse, in TCreateRequest> extends ISourceKnownService<TEntity, TResponse> with Task<TEntity> CreateEntityAsync(TCreateRequest request, CancellationToken cancellationToken = default).

Derive from SourceKnownService<TEntity>, SourceKnownService<TEntity, TResponse>, or SourceKnownService<TEntity, TResponse, TCreateRequest> to implement these contracts with a constructor-supplied repository. Their public CreateResponseAsync, CreateResponsesAsync, and CreateEntityAsync methods enforce null-argument checks, cancellation, empty-batch short-circuiting, non-null results, and one-to-one batch counts before delegating to protected CreateResponseCoreAsync, virtual CreateResponsesCoreAsync (override to batch asynchronous enrichment queries), and CreateEntityCoreAsync hooks.

Contract from SourceKnownRepository.cs, grouped by operation:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using DRN.Framework.SharedKernel.Domain;
using DRN.Framework.SharedKernel.Domain.Pagination;
using DRN.Framework.SharedKernel.Domain.Repository;

public interface ISourceKnownRepository<TEntity> where TEntity : AggregateRoot
{
    RepositorySettings<TEntity> Settings { get; set; }
    CancellationToken CancellationToken { get; }
    void CancelWhen(CancellationToken token);
    void CancelChanges();
    Task<int> SaveChangesAsync();

    // Predicates & Counts
    Task<bool> AllAsync(Expression<Func<TEntity, bool>> predicate);
    Task<bool> AnyAsync(Expression<Func<TEntity, bool>>? predicate = null);
    Task<long> CountAsync(Expression<Func<TEntity, bool>>? predicate = null);
    
    // Identity Conversion & Validation
    SourceKnownEntityId GetEntityId(Guid id, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    SourceKnownEntityId? GetEntityId(Guid? id, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    SourceKnownEntityId GetEntityId<TOtherEntity>(Guid id, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    SourceKnownEntityId? GetEntityId<TOtherEntity>(Guid? id, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    SourceKnownEntityId[] GetEntityIds(IReadOnlyCollection<Guid> ids, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    SourceKnownEntityId?[] GetEntityIds(IReadOnlyCollection<Guid?> ids, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    SourceKnownEntityId[] GetEntityIds<TOtherEntity>(IReadOnlyCollection<Guid> ids, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    SourceKnownEntityId?[] GetEntityIds<TOtherEntity>(IReadOnlyCollection<Guid?> ids, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    IEnumerable<SourceKnownEntityId> GetEntityIdsAsEnumerable(IEnumerable<Guid> ids, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    IEnumerable<SourceKnownEntityId?> GetEntityIdsAsEnumerable(IEnumerable<Guid?> ids, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    IEnumerable<SourceKnownEntityId> GetEntityIdsAsEnumerable<TOtherEntity>(IEnumerable<Guid> ids, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    IEnumerable<SourceKnownEntityId?> GetEntityIdsAsEnumerable<TOtherEntity>(IEnumerable<Guid?> ids, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault) where TOtherEntity : SourceKnownEntity;
    SourceKnownEntityId ToSecure(SourceKnownEntityId id);
    SourceKnownEntityId ToPlain(SourceKnownEntityId id);
    
    // Data Access
    Task<TEntity[]> GetAllAsync();
    Task<TEntity> GetAsync(Guid id, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    Task<TEntity> GetAsync(SourceKnownEntityId id);
    Task<TEntity?> GetOrDefaultAsync(Guid id, bool validate = true, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    Task<TEntity?> GetOrDefaultAsync(SourceKnownEntityId id, bool validate = true);
    
    // Batch Retrieval
    Task<TEntity[]> GetAsync(IReadOnlyCollection<Guid> ids, SourceKnownEntityIdFormat format = SourceKnownEntityIdFormat.ConfiguredDefault);
    Task<TEntity[]> GetAsync(IReadOnlyCollection<SourceKnownEntityId> ids);
    // Modification
    void Add(params IReadOnlyCollection<TEntity> entities);
    void Remove(params IReadOnlyCollection<TEntity> entities);
    Task<int> CreateAsync(params IReadOnlyCollection<TEntity> entities);
    Task<int> DeleteAsync(params IReadOnlyCollection<TEntity> entities);
    Task<int> DeleteAsync(params IReadOnlyCollection<Guid> ids);
    Task<int> DeleteAsync(IReadOnlyCollection<Guid> ids, SourceKnownEntityIdFormat format);
    Task<int> DeleteAsync(params IReadOnlyCollection<SourceKnownEntityId> ids);

    // Pagination
    Task<PaginationResultModel<TEntity>> PaginateAsync(PaginationRequest request, EntityCreatedFilter? filter = null);
    Task<PaginationResultModel<TEntity>> PaginateAsync(
        PaginationResultInfo? resultInfo = null, long jumpTo = 1, int pageSize = -1, int maxSize = -1,
        PageSortDirection direction = PageSortDirection.None, long totalCount = -1, bool updateTotalCount = false);
    IAsyncEnumerable<PaginationResultModel<TEntity>> PaginateAllAsync(PaginationRequest request, EntityCreatedFilter? filter = null);
}

GetAllAsync() returns all matching entities in a single query. This should be used only when the result set is guaranteed to be small or for specific maintenance tasks. Avoid in public-facing APIs.

Settings and Cancellation

RepositorySettings<TEntity> provides IgnoreAutoIncludes, AsNoTracking, ScopeKey, and named predicate filters through AddFilter, RemoveFilter, and ClearFilters. Both boolean settings default to false. See RepositorySettings.cs.

  • A null ScopeKey uses the root cancellation scope. A configured key selects a child scope shared by repositories using that key.
  • CancellationToken exposes the effective scope token. CancelChanges() cancels that scope, and CancelWhen(token) links a lifetime token to it.
  • Cancellation lasts for the scope's lifetime. With a null key, it affects root-linked operations too.
  • For a single operation, create a local linked token source and pass its token to an operation that accepts it. Do not merge an operation-only token through CancelWhen.

CancellationScopeKey lives in DRN.Framework.SharedKernel.Cancellation. Create keys through its For(...) factories. See the key contract and the EntityFramework repository.

Filtering

EntityCreatedFilter supplies After, Before, Between, and Outside factories. Each defaults to inclusive: true. In the default implementation, inclusive boundaries include the full 250ms ID tick; exclusive boundaries exclude it. Between and Outside normalize reversed endpoints.

With a repository and pagination request in scope:

// Example: Get records created in the last 7 days
var filter = EntityCreatedFilter.After(DateTimeOffset.UtcNow.AddDays(-7));
var result = await repository.PaginateAsync(request, filter);

See EntityCreatedFilter.cs and EntityDateTimeUtils.cs.


Pagination

Pagination uses first/last entity IDs as cursors for forward, backward and refresh requests. It does not provide a database snapshot across requests.

Refresh results detect a next page from an extra fetched row even when the total count is unknown. JSON null values for PaginationRequest.PageSize and PageCursor use the default page size and initial cursor.

Setting or operation Behavior
PaginationRequest.From() Starts at page 1, size 10, maximum 100, ascending order
Changed size, effective maximum or direction Resets to page 1 with a fresh cursor
Omitted settings during reset Retains the previous size, maximum and direction
Maximum size Capped at 1,000 before comparison; repeating an above-threshold limit preserves navigation
From(resultInfo, jumpTo: ...) Limits movement to ten pages in the requested direction; 100 to 1 targets 90, and 1 to 100 targets 11
RequestNextPage(), RequestPreviousPage(), RequestRefresh() Creates navigation requests from result metadata
RequestPage(n) Creates a direct page request; does not apply From's ten-page clamp
TotalCount, UpdateTotalCount Carries a known count or requests recalculation; -1 means unspecified
PaginateAllAsync Streams pages as IAsyncEnumerable<PaginationResultModel<TEntity>>

The three-argument PageSize constructor can override the maximum threshold for in-process requests. That override is not serializable. See PaginationRequest.cs, PageSize.cs, and PaginationResultBase.cs.

API Integration

For flat first-page input, bind PaginationOptions from a query or JSON body and convert it with PaginationRequest.DefaultWith(options). Set updateTotalCount to request a server-side count. JSON enum values follow the application's serializer configuration. Use the returned metadata for continuation requests.

PaginationRequest supports query-string model binding. This controller uses the quickstart's UserEntity and maps to an explicit Contract UserResponse:

using System;
using System.Threading.Tasks;
using DRN.Framework.SharedKernel.Domain.Pagination;
using DRN.Framework.SharedKernel.Domain.Repository;
using Microsoft.AspNetCore.Mvc;

public sealed class UserResponse
{
    public Guid Id { get; init; }
    public DateTimeOffset CreatedAt { get; init; }
    public DateTimeOffset ModifiedAt { get; init; }
}

[ApiController]
[Route("users")]
public class UsersController(ISourceKnownRepository<UserEntity> repository) : ControllerBase
{
    [HttpGet]
    public async Task<PaginationResultModel<UserResponse>> GetAsync([FromQuery] PaginationRequest request)
    {
        var result = await repository.PaginateAsync(request);
        return result.ToModel(user => new UserResponse
        {
            Id = user.EntityId,
            CreatedAt = user.CreatedAt,
            ModifiedAt = user.ModifiedAt
        });
    }
}

Usage

// Inside a service method with repository in scope.
var request = PaginationRequest.DefaultWith(size: 20, direction: PageSortDirection.Descending);
var result = await repository.PaginateAsync(request);

if (result.Info.HasNext)
{
    var nextRequest = result.Info.RequestNextPage();
    var nextPage = await repository.PaginateAsync(nextRequest);
}

Exceptions

ExceptionFor creates DrnException subclasses with Status and Category. DRN Hosting's HttpScopeMiddleware maps the status to an HTTP response and aborts invalid status values. SharedKernel alone does not handle HTTP requests.

Factory Method Exception Type HTTP Status
ExceptionFor.Validation(msg) ValidationException 400
ExceptionFor.Unauthorized(msg) UnauthorizedException 401
ExceptionFor.Forbidden(msg) ForbiddenException 403
ExceptionFor.NotFound(msg) NotFoundException 404
ExceptionFor.Conflict(msg) ConflictException 409
ExceptionFor.Expired(msg) ExpiredException 410
ExceptionFor.UnprocessableEntity(msg) UnprocessableEntityException 422
ExceptionFor.Configuration(msg) ConfigurationException 500
ExceptionFor.Jackpot(msg) JackpotException 500
ExceptionFor.MaliciousRequest(msg) MaliciousRequestException Abort

Every factory accepts string message, optional Exception? exception = null, and optional string? category = "default". The base exception defaults to status 500 and category DrnException.DefaultCategory ("default"). It also exposes a string-keyed Data dictionary. MaliciousRequestException.Status is short.MaxValue, the abort sentinel used by Hosting.

using DRN.Framework.SharedKernel;

throw ExceptionFor.NotFound("User not found", category: "Users");

For custom exceptions, prefer an existing semantic base when it fits:

using DRN.Framework.SharedKernel;

public class OrderAlreadyShippedException(string message)
    : ConflictException(message); // Inherits Status = 409.

public class ServiceUnavailableException(string message)
    : DrnException(message, null, null, 503); // Explicit status when no existing base fits.

public class UnexpectedOrderException(string message)
    : System.Exception(message); // Unmapped exception: Hosting defaults to 500.

Direct DrnException subclasses also default to 500 when status is omitted. For eligible API/HTMX responses, Hosting infers the standard problem type from status, not the class name, message, or Category. Custom types are optional and do not change status. See Hosting mappings, overrides, and special cases.

See Exceptions.cs and HttpScopeMiddleware.cs.


JsonConventions

JsonConventions.DefaultOptions centralizes System.Text.Json settings. Initializing these conventions changes serializer defaults process-wide, including calls that do not pass explicit options. Utils convention setup and DrnTestContext apply these defaults. Hosting also configures HTTP JSON and MVC options.

Setting Value
New options JsonSerializerDefaults.Web
Property names camelCase, case-insensitive reading
Enums JsonStringEnumConverter
Trailing commas Allowed
Number handling AllowReadingFromString
Maximum depth 32
long and long? JSON numbers within -9,007,199,254,740,991..9,007,199,254,740,991; strings outside that range

Int64ToStringConverter and Int64NullableToStringConverter accept numeric tokens and integer strings. The nullable converter preserves null. SetJsonDefaults(options) updates supplied mutable options or creates new options when omitted. SetHtmlSafeWebJsonDefaults(options) also sets JavaScriptEncoder.Default; Hosting uses it for MVC.

JsonStringEnumConverter uses its default allowIntegerValues: true behavior and accepts numeric 0 and undefined integer enum values. Operations must validate allowed enum values explicitly.

using System.Text.Json;
using DRN.Framework.SharedKernel.Json;

var json = JsonSerializer.Serialize(new { Count = long.MaxValue }, JsonConventions.DefaultOptions);
// {"count":"9223372036854775807"}

See JsonConventions.cs and IntegerSafeIntervalForJs.cs.


Attributes

[Sensitive] and [Personal]

Opt a class, struct or property into diagnostic redaction. [Sensitive] uses DataClassifications.Sensitive, and [Personal] uses DataClassifications.Personal. Both derive from Microsoft's DataClassificationAttribute under the DRN.Classification taxonomy and may themselves be inherited by company attributes. Fields may carry classification for other consumers but are omitted by object capture. Derived Sensitive attributes must remain positive. Scoped logs read classified getters once at capture and redact snapshot output. Direct sanitizer calls skip classified getters. Positive classifications and [IgnoreLog] on mapped interface properties protect concrete and nested captures too. [IgnoreLog] takes precedence during capture, but never satisfies classification analysis. Direct [Sensitive(false)] exempts one property from built-in name rules, with optional Justification. Positive classification and configured protection still win. Interface exemptions do not waive concrete property name rules. Binding, business serialization, and storage are unchanged. See classification examples and diagnostic policy.

[IgnoreLog]

Marks classes, structs, properties or fields for exclusion by logging code that honors the attribute. IgnoredLog(object?) checks the runtime type and returns false for null. IgnoredLog(PropertyInfo) also ignores properties typed as object or carrying an ignored property type. See IgnoreLogAttribute.cs.

[SecureKey]

Validates string properties, fields or parameters. Defaults require 16 to 256 characters, uppercase, lowercase, a digit and a special character. The allowed set contains ASCII and Turkish letters, digits, space, and !*()-_; space counts as special. Sequential and repeated-character limits are configurable through MaxSequentialChars (4) and MaxRepeatedChars (3). Null values fail validation. See SecureKeyAttribute.cs for the exact character checks.

[DomainOnly]

Marks a Domain-declared enum as domain-internal (DRNENUM001 through DRNENUM003). Root byte identity enums referenced by a local EntityTypeAttribute subclass remain valid at the Domain root. See enum conventions and DomainOnlyAttribute.cs.

[AllowZero]

Opts an enum with a named 0 member into zero-value declarations at compile time (DRNENUM004, DRNENUM005). See enum conventions and AllowZeroAttribute.cs.


Shared Extensions

SharedKernel owns low-level extensions needed without higher-layer dependencies.

using DRN.Framework.SharedKernel.Extensions;

var schema = "OrderHistory".ToSnakeCase();     // order_history
var typeName = "sample hosted".ToPascalCase(); // SampleHosted

var root = "/data/app";
var file = root.GetPathWithinDirectory("exports", "orders.json");

GetPathWithinDirectory() resolves a full path, rejects paths outside the root, and rejects symbolic links or reparse points in child components below that root. Use it for file-serving, manifest, upload and app-data child paths. It checks the path at resolution time; it does not lock the filesystem against later changes. IsPathWithinDirectory() checks lexical containment only and does not resolve symbolic links.

See StringExtensions.cs and PathExtensions.cs.


AppConstants

AppConstants is in DRN.Framework.SharedKernel. Values are initialized once from the process, entry assembly, environment and local network:

Property Value
int ProcessId Environment.ProcessId
Guid AppInstanceId A new GUID for this process initialization
string EntryAssemblyName Entry assembly name, or "Entry Assembly Not Found"
string EntryAssemblyNameNormalized Entry assembly name converted with ToPascalCase()
string EntryAssemblyFullName Full entry assembly name, or "Entry Assembly Not Found"
string LocalAppDataPath Configured data path or application-specific local data directory
string TempPath Application-specific temp directory from the fallback order below
string LocalIpAddress Local IPv4 address, falling back to loopback

LocalAppDataPathEnvVariable is DrnAppDataSettings__DataPath. TempPathEnvVariable is DrnAppDataSettings__TempPath. These are process environment overrides, resolved before DRN configuration.

TempPath appends EntryAssemblyNameNormalized in this order:

  1. DrnAppDataSettings__TempPath/<EntryAssemblyNameNormalized>
  2. DrnAppDataSettings__DataPath/Temp/<EntryAssemblyNameNormalized>
  3. <LocalApplicationData>/Temp/<EntryAssemblyNameNormalized>

LocalAppDataPath uses DrnAppDataSettings__DataPath as configured, otherwise <LocalApplicationData>/<EntryAssemblyNameNormalized>. Path resolution can return an empty string when no usable root is available. IAppData in Utils owns directory creation, temp cleanup, test temp preservation and safe child paths.

See AppConstants.cs and AppData.cs.


Global Usings

Suggested consumer usings for projects that work heavily with SharedKernel types:

global using DRN.Framework.SharedKernel.Domain;
global using DRN.Framework.SharedKernel.Domain.Pagination;
global using DRN.Framework.SharedKernel.Domain.Repository;
global using DRN.Framework.SharedKernel;
global using DRN.Framework.SharedKernel.Extensions;
global using DRN.Framework.SharedKernel.Json;

For complete examples, see Sample.Hosted.


Documented with the assistance of DiSC OS


Semper Progressivus: Always Progressive

Commit Info

Author: Duran Serkan KILIÇ
Date: 2026-11-29 15:19:04 +0300
Hash: 7566fdddaa8825625ad08e59a85bab1a354bbd48

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DRN.Framework.SharedKernel:

Package Downloads
DRN.Framework.Utils

DRN.Framework.Utils package contains common codes for other DRN.Framework packages, projects developed with DRN.Framework. ## Commit Info Author: Duran Serkan Date: 2026-12-02 22:58:02 +0300 Hash: 7e7c6ede08770d46bcb0b4428cc52bd28e82e9c3

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.11.0-preview009 51 12/2/2026
0.11.0-preview008 110 11/30/2026
0.11.0-preview007 125 11/29/2026
0.11.0-preview006 121 11/29/2026
0.11.0-preview005 121 11/29/2026
0.11.0-preview004 118 11/28/2026
0.11.0-preview003 127 11/26/2026
0.11.0-preview002 123 11/19/2026
0.11.0-preview001 116 11/12/2026
0.10.1-preview008 131 11/8/2026
0.10.1-preview007 133 11/4/2026
0.10.1-preview006 159 10/27/2026
0.10.1-preview005 144 10/25/2026
0.10.1-preview004 195 10/14/2026
0.10.1-preview003 150 10/4/2026
0.10.1-preview002 136 10/4/2026
0.10.1-preview001 138 10/4/2026
0.10.0 176 9/20/2026
0.10.0-preview004 141 9/19/2026
0.10.0-preview003 142 9/13/2026
Loading failed

## Version 0.11.0

### Security

*   **JSON integer errors**: Invalid `long` and `long?` values produce a conversion error that omits the submitted value.

### Breaking Changes

*   **Target framework**: Requires .NET 11. Analyzer and code-fix assemblies target .NET 10 for IDE host compatibility and require Roslyn 5.12 APIs.
*   **Diagnostic IDs**: Replace `DRN0001` through `DRN0014` with `DRNENTITY001` through `DRNENTITY014` (keeping the same numbers) in `.editorconfig`, `NoWarn`, `WarningsAsErrors`, `#pragma warning`, and `SuppressMessage`.
*   **Entity type declarations**: `DRNENTITY008` now requires a domain attribute with a byte-backed enum parameter instead of direct `[EntityType<TApp>(n)]`, `[TestEntityType(n)]`, or raw-byte wrappers. Assign each enum member its existing byte value, keep the same `TApp` partition to preserve stored IDs, and rebuild referenced domain assemblies that still use byte-based annotations.
*   **Entity `ToDto()` contract**: Added `public abstract Dto ToDto()` on `SourceKnownEntity`. Override `ToDto()` covariantly on every concrete entity to return its Contract DTO via `new(this)`.
*   **Partition producers**: `DRNENTITY006` and `DRNENTITY007` now also check concrete `IAppId` implementations in projects without entities. Publish a constant value from 0 through 127 and return it from `IAppId.AppId`.
*   **Data classification analyzers**: `DRNCLASSIFICATION001` through `DRNCLASSIFICATION012` run transitively on public readable instance properties, anonymous projections, dictionary captures, `IScopedLog`, and `ILogger` calls. Annotate matching properties with `[Personal]`, `[Sensitive]`, or `[Sensitive(false)]`, move matching anonymous properties to named annotated models, and classify dictionary keys or redact sensitive logger values. See the [diagnostic guide](https://github.com/duranserkan/DRN-Project/blob/master/DRN.Framework.Utils/Logging/Diagnostics/README.md).
*   **Application convention analyzers**: Convention rules (`DRNARCHITECTURE*`, `DRNCONVENTIONINPUT*`, `DRNCONVENTIONEXCEPTION*`, `DRNDTO*`, `DRNENUM*`, `DRNOWNERSHIP*`, `DRNSTRUCTURE*`, `DRNPERSISTENCE*`, `DRNREPOSITORY*`, `DRNDEPENDENCYINJECTION*`) activate by default as warnings on `<organization>.<layer>[.<module>]` projects with matching `RootNamespace` values and fail `TreatWarningsAsErrors` builds. Place top-level concrete Domain entities directly in their stem folder below their owner, place contexts and options in `Databases/<owner>/` with flat `Configurations/`, `Repositories/`, and `Migrations/` subfolders, mark concrete Domain services with `IDomainService` (`DRNARCHITECTURE007`/`008`), register `IDomainService` and `ISourceKnownService<TEntity>` implementations as transient (`DRNDEPENDENCYINJECTION004`), and declare Source-Known controller HTTP models as explicit Contract `*Response` and `*Request` types (`DRNDTO006`). Configure `.editorconfig` severities or narrow `DrnConventionException` items for intentional exceptions. See `CONVENTIONS.md` and `CONVENTION-DIAGNOSTICS.md`.

### New Features

*   **Subdomain aliases**: Declare `DrnSubdomainAlias` once across projects. `DRNSTRUCTURE009` warns on aliases in the subdomain segment of Contract and Domain types, Application services, Infra persistence and Hosted controllers. DTO, service, repository pair and EF configuration refactorings skip destinations that use an alias. Chained or cyclic aliases block generation until each alias points directly to its canonical subdomain.
*   **Contract message placement**: `DRNDTO004` checks entity-owned requests and responses against their DTO's folder and namespace, including action-first names. Declare exact DTO owners or shared messages with `DrnContractMessage` in the Contract project.
*   **Domain contracts**: `DRNARCHITECTURE006` requires each Domain project to declare at least one direct `ProjectReference` to a recognized Contract project. Domain projects may also consume Contract NuGet packages.
*   **SourceKnown application conventions**: Added project-role dependency, `<organization>.<layer>[.<module>]` identity and module ownership (`<DrnDomainLayout>`, `<DrnDomain>`, `[SourceKnownSubdomain]`), entity and `Databases/<owner>/` persistence folder structure, domain service purity and marker (`DRNARCHITECTURE007`/`008`), persistence (`IDrnContext`, aggregate `DbSet`s, custom context options), repository, DI module, lifetime binding, and transient service (`DRNDEPENDENCYINJECTION004`) diagnostics, DTO and public-contract (`*Request`/`*Response`, nested DTO and persistence graphs, controller model arguments, and LINQ projection classification) diagnostics, and enum (`[DomainOnly]`, `[AllowZero]`) diagnostics, plus guarded code fixes, transient repository-method forwarding refactorings under `Services/<owner>/`, `Databases/<owner>/` repository/configuration refactorings with producer-metadata validation, and aggregate review plans. `DRNDTO003` follows collection writes, loop elements, nested tuple patterns, forwarding getters, and selector branch conditions to the response property they affect. The rule uses the selected getter when the concrete receiver is known, checks captured values and writes at known query enumeration sites, and follows null-conditional query returns. See `CONVENTIONS.md` and `SCAFFOLDING.md`.
*   **Domain and Source-Known services**: Added `IDomainService` for pure, transient domain services alongside `ISourceKnownService<TEntity>`, `ISourceKnownService<TEntity, TResponse>`, `ISourceKnownService<TEntity, TResponse, in TCreateRequest>`, and matching `SourceKnownService` abstract bases enforcing argument, cancellation, and projection invariants around protected `CreateResponseCoreAsync`, virtual batched `CreateResponsesCoreAsync`, and `CreateEntityCoreAsync` hooks.
*   **Source-Known controller authorization**: Added `DRNAUTHORIZATION001`, requiring explicit nonblank named `[Authorize(Policy = "...")]` policies on exposed Source-Known controller actions and rejecting `[AllowAnonymous]`.
*   **Data classification and exemptions**: Added inheritable `[Sensitive]` and `[Personal]` attributes, `[Sensitive(false)]` false-positive opt-outs, project `data-classification-rules.json` (and `diagnostic-rules.json`) catalogs, `DiagnosticNameExemption` comments, and classification code fixes.
*   **Pagination options**: Added `PaginationOptions` and `PaginationRequest.DefaultWith(options)` for flat first-page query or JSON binding.

### Bug Fixes

*   **Entity diagnostics**: `DRNENTITY009` and `DRNENTITY010` now check converted constants passed through nullable numeric casts. `DRNENTITY013` reports an invalid repository type initializer once. `DRNENTITY006` verifies `IAppId.AppId` getters against published constants when source is available, and `DRNENTITY002` checks collisions across transitive project references while skipping `System.*`, `Microsoft.*`, and external framework dependencies. Incomplete primary-constructor base lists no longer cause analyzer failures on derived entity attributes.
*   **Packaged analyzer loading**: Duplicate packaged analyzer entries are removed before compilation.
*   **Pagination**: Refresh results detect a next page from an extra fetched row without a known total or caller hint. Null JSON `PageSize` and `PageCursor` members now use defaults instead of throwing.
*   **Path containment**: `GetPathWithinDirectory()` accepts missing child files and directories while checking existing ancestors for symbolic links.

---

Documented with the assistance of [DiSC OS](https://github.com/duranserkan/DRN-Project/blob/develop/.agent/rules/DiSCOS.md)

---
**Semper Progressivus: Always Progressive**