Skip to main content

Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator by Microsoft

Nuget / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator

Microsoft.Extensions.Options

Author: Microsoft

NuGet: https://www.nuget.org/packages/Microsoft.Extensions.Options

You can find more details at https://learn.microsoft.com/en-us/dotnet/core/extensions/options-validation-generator

Source : https://github.com/dotnet/runtime

Original Readme

note

.NET Runtime

Build Status Help Wanted Gitter Discord

This repo contains the code to build the .NET runtime, libraries and shared host (dotnet) installers for all supported platforms, as well as the sources to .NET runtime and libraries.

What is .NET?

Official Starting Page: https://dotnet.microsoft.com

How can I contribute?

We welcome contributions! Many people all over the world have helped make this project better.

Reporting security issues and security bugs

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) secure@microsoft.com. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter. You can also find these instructions in this repo's Security doc.

Also see info about related Microsoft .NET Core and ASP.NET Core Bug Bounty Program.

Filing issues

This repo should contain issues that are tied to the runtime, the class libraries and frameworks, the installation of the dotnet binary (sometimes known as the muxer) and the installation of the .NET runtime and libraries.

For other issues, please file them to their appropriate sibling repos. We have links to many of them on our new issue page.

.NET Foundation

.NET Runtime is a .NET Foundation project.

There are many .NET related projects on GitHub.

  • .NET home repo - links to 100s of .NET projects, from Microsoft and the community.
  • ASP.NET Core home - the best place to start learning about ASP.NET Core.

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the .NET Foundation Code of Conduct.

General .NET OSS discussions: .NET Foundation Discussions

License

.NET (including the runtime repo) is licensed under the MIT license.

About

note

Generating the validation for data annotations on options classes.

How to use

Example ( source csproj, source files )

This is the CSharp Project that references Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX


// <auto-generated/>
#nullable enable
#pragma warning disable CS1591 // Compensate for https://github.com/dotnet/roslyn/issues/54103
namespace DemoValidatorObj
{
partial class ValidatorForMyApp
{
/// <summary>
/// Validates a specific named options instance (or all when <paramref name="name"/> is <see langword="null" />).
/// </summary>
/// <param name="name">The name of the options instance being validated.</param>
/// <param name="options">The options instance.</param>
/// <returns>Validation result.</returns>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
[System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode",
Justification = "The created ValidationContext object is used in a way that never call reflection")]
public global::Microsoft.Extensions.Options.ValidateOptionsResult Validate(string? name, global::DemoValidatorObj.MyAppOptions options)
{
global::Microsoft.Extensions.Options.ValidateOptionsResultBuilder? builder = null;
var context = new global::System.ComponentModel.DataAnnotations.ValidationContext(options);
var validationResults = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationResult>();
var validationAttributes = new global::System.Collections.Generic.List<global::System.ComponentModel.DataAnnotations.ValidationAttribute>(2);

context.MemberName = "AppDisplayName";
context.DisplayName = string.IsNullOrEmpty(name) ? "MyAppOptions.AppDisplayName" : $"{name}.AppDisplayName";
validationAttributes.Add(global::__OptionValidationStaticInstances.__Attributes.A1);
validationAttributes.Add(global::__OptionValidationStaticInstances.__Attributes.A2);
if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateValue(options.AppDisplayName, context, validationResults, validationAttributes))
{
(builder ??= new()).AddResults(validationResults);
}

return builder is null ? global::Microsoft.Extensions.Options.ValidateOptionsResult.Success : builder.Build();
}
}
}
namespace __OptionValidationStaticInstances
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
file static class __Attributes
{
internal static readonly global::System.ComponentModel.DataAnnotations.RequiredAttribute A1 = new global::System.ComponentModel.DataAnnotations.RequiredAttribute();

internal static readonly __OptionValidationGeneratedAttributes.__SourceGen__MinLengthAttribute A2 = new __OptionValidationGeneratedAttributes.__SourceGen__MinLengthAttribute(
(int)3);
}
}
namespace __OptionValidationStaticInstances
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
file static class __Validators
{
}
}
namespace __OptionValidationGeneratedAttributes
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Options.SourceGeneration", "8.0.9.3103")]
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter, AllowMultiple = false)]
file class __SourceGen__MinLengthAttribute : global::System.ComponentModel.DataAnnotations.ValidationAttribute
{
private static string DefaultErrorMessageString => "The field {0} must be a string or array type with a minimum length of '{1}'.";

public __SourceGen__MinLengthAttribute(int length) : base(() => DefaultErrorMessageString) { Length = length; }
public int Length { get; }
public override bool IsValid(object? value)
{
if (Length < -1)
{
throw new global::System.InvalidOperationException("MinLengthAttribute must have a Length value that is zero or greater.");
}
if (value == null)
{
return true;
}

int length;
if (value is string stringValue)
{
length = stringValue.Length;
}
else if (value is System.Collections.ICollection collectionValue)
{
length = collectionValue.Count;
}
else
{
throw new global::System.InvalidCastException($"The field of type {value.GetType()} must be a string, array, or ICollection type.");
}

return length >= Length;
}
public override string FormatErrorMessage(string name) => string.Format(global::System.Globalization.CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
}
}

Usefull

Download Example (.NET C# )

Share Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Microsoft.Extensions.Options.Generators.OptionsValidatorGenerator

In the same category (EnhancementClass) - 27 other generators

ApparatusAOT

AspectGenerator

CommonCodeGenerator

CopyTo

DudNet

Enhanced.GetTypes

FastGenericNew

GeneratorEquals

HsuSgSync

Immutype

Ling.Audit

Lombok.NET

M31.FluentAPI

MemoryPack

Meziantou.Polyfill

Microsoft.Extensions.Logging

Microsoft.Interop.JavaScript.JSImportGenerator

OptionToStringGenerator

QueryStringGenerator

RSCG_Decorator

RSCG_UtilityTypes

StaticReflection

SyncMethodGenerator

System.Runtime.InteropServices

System.Text.RegularExpressions

TelemetryLogging

ThisClass