Siemens.AspNet.CodeRules.Contracts 7.7.3

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

Siemens.AspNet.CodeRules.Contracts

Write a convention once, as code. Every finding says what, where, why and how to fix it.

Everything a code rule author needs, and nothing else: the rule interfaces, the Finding, the analysis contexts and the rule pack contract. A rule pack (a library with your team's rules) references only this package, never the engine or a test framework, so the same rules run in MSTest, xUnit, NUnit and the coderules CLI.

public sealed class ClassNamesMustNotEndWithManager : ICodeRule
{
    public string Id => "NAMING_001";
    public string Title => "Class names must not end with 'Manager'";
    public string Why => "'Manager' says nothing about the responsibility of a class.";
    public string HowToFix => "Name the class after what it does, e.g. 'OrderManager' to 'OrderProcessor'.";

    public IEnumerable<Finding> Evaluate(CodeContext context)
    {
        return from type in context.ProductionTrees.Classes
               where type.Name.EndsWith("Manager", StringComparison.Ordinal)
               select new Finding
               {
                   What = type.FullyQualifiedName,
                   Where = type.Location
               };
    }
}

Installation

dotnet add package Siemens.AspNet.CodeRules.Contracts

To run rules, add one of the hosts to a test project (or use the CLI):

Package Runs the rules as
Siemens.AspNet.CodeRules.MSTest one generated MSTest test per rule
Siemens.AspNet.CodeRules.XUnit one generated xUnit v3 test per rule
Siemens.AspNet.CodeRules.NUnit one generated NUnit test per rule
Siemens.AspNet.CodeRules.Cli coderules run from the console, human or JSON output

A rule

A rule is a stateless class that describes a convention and evaluates one context:

Interface Evaluates Default group
ICodeRule CodeContext: the parsed C# code of the solution Code
ISolutionRule SolutionContext: projects, csproj content, package references, files Solution
IRule<TContext> your own context (see below) from the context

Required members

Member Meaning
Id stable, unique ID matching ^[A-Z][A-Z0-9_]*$, e.g. ARCH_001. Never reuse or rename it.
Title short title, shown in failures and rule lists
Why the decision behind the convention, like an ADR: why we do it and what goes wrong otherwise. Shown with every violation.
HowToFix how to fix a violation. A finding can override it.

Optional members (all have defaults)

Member Default Meaning
Tags [] extra tags, e.g. Naming; become categories in the test hosts and filters in the CLI (--tag)
DefaultSeverity Error severity of findings that do not set their own (Info, Warning, Error)
DocumentationUrl null absolute link to the documentation of the convention
ReadMoreUrl null absolute link to background reading
SkipReason null non-null: not evaluated, reported as skipped with this reason (a constant, so the generators show the test as ignored)
Deprecated null non-null: still runs, the output shows this hint, e.g. "Use ARCH_010"
AllowSuppression true false: a finding cannot be accepted in the code ([SuppressMessage], #pragma warning disable); scoped skips in the setup do not apply either

The finding

A Finding is one violation: what is affected and where. Why and how to fix it live on the rule.

new Finding
{
    What = property.FullyQualifiedName,        // required: the affected element
    Where = property.Location,                  // implicit from a Solution Parser CodeLocation or a FileInfo
    Current = property.SourceCode,              // the offending snippet as it is now
    ShouldBe = property.SourceCode.Replace("set;", "init;", StringComparison.Ordinal),
    HowToFix = "Use 'init' instead of 'set'.", // optional: overrides the rule's HowToFix
    Severity = Severity.Warning,                // optional: overrides the rule's DefaultSeverity
    Details = [("Record", record.Name), ("Other setters", otherSetters)]
};
  • Where is a SourceLocation with one based lines and columns. Where = project.FileInfo marks a whole file (e.g. a csproj); null is fine for solution wide findings.
  • Current / ShouldBe are shown as - / + lines, so a reader (or an AI agent) sees the exact fix.
  • Details are extra Key: value lines in the given order. Lists are joined, numbers and dates use the invariant culture, null values are left out. Same shape as the key/value extensions of the SDK's ProblemDetails exceptions.

The contexts

Contexts are read-only, created once per engine run and shared by all rules, so rules are cheap and run in parallel.

CodeContext

The parsed C# code (Solution Parser), split into production and test code:

Member Content
ProductionTrees C# files of the production projects
TestTrees C# files of the unit test projects
AllTrees both; the full Solution Parser model (AllTrees.MembersWithBody, ProductionTrees.Methods, ...)
Classes, Records, Interfaces, Enums, Structs shortcuts over AllTrees, nested types included

SolutionContext

The solution itself, for rules about projects, packages, solution items and non-C# files:

public sealed class ProjectsMustHaveAReadme : ISolutionRule
{
    public string Id => "SLN_001";
    public string Title => "Every production project has a README.md";
    public string Why => "A package without a README is a black box on the feed and in the IDE.";
    public string HowToFix => "Add a README.md next to the csproj and pack it with PackageReadmeFile.";

    public IEnumerable<Finding> Evaluate(SolutionContext context)
    {
        return from project in context.Solution.ProductionProjects
               where !File.Exists(Path.Combine(project.FileInfo.DirectoryName!, "README.md"))
               select new Finding { What = project.FileInfo.Name, Where = project.FileInfo };
    }
}

Your own context

When many rules need the same derived model (controllers, endpoints, handlers, ...), compute it once in a context. A context with exactly one public constructor that takes other contexts is created by the engine without any registration:

public sealed class ControllerContext(CodeContext code) : IRuleContext
{
    public static string? Group => "Controllers";   // optional: the group of all rules on this context

    public ImmutableList<Class> Controllers { get; } =
        [.. code.ProductionTrees.Classes.Where(c => c.Name.EndsWith("Controller", StringComparison.Ordinal))];
}

public sealed class ControllersMustBeSealed : IRule<ControllerContext> { /* ... */ }

The group of a rule (the generated test class, the Group of a failure) is, in this order: a custom rule interface, the context's Group, the namespace of the rule, the context's type name without Context.


Rule packs

A pack decides which of its rules a consumer gets:

public sealed class NamingRulePack : ICodeRulePack
{
    public void Register(ICodeRuleRegistry rules)
    {
        rules.Add<ClassNamesMustNotEndWithManager>()
             .Add<EnumNamesMustNotEndWithEnum>();
    }
}

A consumer registers it with AddRulePack<NamingRulePack>(), or takes every public rule with AddRulesFrom(typeof(NamingRulePack).Assembly) (see Siemens.AspNet.CodeRules.Engine). Rules can stay internal when only the pack registers them.

Descriptor source generator (included)

This package ships a source generator (analyzers/dotnet/cs) that writes [assembly: CodeRuleDescriptor(...)] for every rule of your pack at build time. The test adapters of a consumer read it, so a rule from a compiled pack gets the same generated test (ID, title, tags) as a rule in source. You reference nothing extra.


Rules for rules

  • Stateless: Evaluate must not keep state between calls; contexts are shared and read-only.
  • Host independent: a rule runs in a test host and in the CLI. Find paths from the solution or the files, never from AppContext.BaseDirectory or the current directory.
  • Findings, not exceptions: a rule that throws is reported as an error of the rule, never as a pass.

License

Copyright (c) Siemens AG. See LICENSE.md in the package.

Product 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. 
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 Siemens.AspNet.CodeRules.Contracts:

Package Downloads
Siemens.AspNet.CodeRules.Engine

The code rule engine: registers rules with AddCodeRuleEngine, parses the solution once, runs the rules and reports findings (human or AI JSON). Includes ICodeRuleSetup for test projects and RuleTester for unit tests of single rules.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
7.7.4 39 11/14/2026
7.7.3 48 11/13/2026
7.7.2 48 11/13/2026
7.7.1 40 11/12/2026
7.7.0 51 11/12/2026

## Next

First release. Everything a code rule author needs; a rule pack references only this package.

- Rule interfaces: `ICodeRule` (parsed C# code), `ISolutionRule` (projects, csproj, packages, files) and `IRule<TContext>` for own analysis contexts that the engine builds once per run.
- Every rule describes its convention with `Id`, `Title`, `Why` and `HowToFix`; optional `Tags`, `DefaultSeverity`, `DocumentationUrl`, `ReadMoreUrl`, `SkipReason`, `Deprecated` and `AllowSuppression`.
- `Finding` with `What`, `Where`, `Current`/`ShouldBe` (shown as `-`/`+` lines), an optional `HowToFix` and `Severity` override and ordered `Details`.
- `CodeContext` (production and test trees of the Solution Parser) and `SolutionContext`.
- `ICodeRulePack` / `ICodeRuleRegistry`: a pack decides which of its rules a consumer gets.
- Ships the descriptor source generator: compiled rule packs get the same generated tests (ID, title, tags) as rules in source.