Skip to content

Commit

Permalink
Use TypedResults in web sample (#49)
Browse files Browse the repository at this point in the history
* Use TypedResults in web sample
Suppressed info messages in Benchmarks
* Update README.md
  • Loading branch information
DamianEdwards committed Jun 22, 2023
1 parent 81b5c92 commit d68bd95
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 9 deletions.
51 changes: 49 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,60 @@ Install the library from [NuGet](https://www.nuget.org/packages/MiniValidation):
### ASP.NET Core 6+ Projects
If installing into an ASP.NET Core 6+ project, consider using the [MinimalApis.Extensions](https://www.nuget.org/packages/MinimalApis.Extensions) package instead, which adds extensions specific to ASP.NET Core, including a validation endpoint filter for .NET 7 apps:
``` console
dotnet add package MinimalApis.Extensions --prerelease
dotnet add package MinimalApis.Extensions
```

## Example usage

### Validate an object

```csharp
var widget = new Widget { Name = "" };

var isValid = MiniValidator.TryValidate(widget, out var errors);

class Widget
{
[Required, MinLength(3)]
public string Name { get; set; }

public override string ToString() => Name;
}
```

### Use services from validators

```csharp
var widget = new Widget { Name = "" };

var isValid = MiniValidator.TryValidate(widget, serviceProvider, out var errors);

class Widget : IValidatableObject
{
[Required, MinLength(3)]
public string Name { get; set; }

public override string ToString() => Name;

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var disallowedNamesService = validationContext.GetService(typeof(IDisallowedNamesService)) as IDisallowedNamesService;

if (disallowedNamesService is null)
{
throw new InvalidOperationException($"Validation of {nameof(Widget)} requires an {nameof(IDisallowedNamesService)} instance.");
}

if (disallowedNamesService.IsDisallowedName(Name))
{
yield return new($"Cannot name a widget '{Name}'.", new[] { nameof(Name) });
}
}
}
```

### Console app

```csharp
using System.ComponentModel.DataAnnotations;
using MiniValidation;
Expand Down Expand Up @@ -146,5 +194,4 @@ class WidgetWithCustomValidation : Widget, IValidatableObject
}
}
}

```
13 changes: 7 additions & 6 deletions samples/Samples.Web/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http.HttpResults;
using MiniValidation;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -22,15 +23,15 @@
app.MapGet("/widgets/{name}", (string name) =>
new Widget { Name = name });

app.MapPost("/widgets", (Widget widget) =>
app.MapPost("/widgets", Results<ValidationProblem, Created<Widget>> (Widget widget) =>
!MiniValidator.TryValidate(widget, out var errors)
? Results.ValidationProblem(errors)
: Results.Created($"/widgets/{widget.Name}", widget));
? TypedResults.ValidationProblem(errors)
: TypedResults.Created($"/widgets/{widget.Name}", widget));

app.MapPost("/widgets/custom-validation", (WidgetWithCustomValidation widget) =>
app.MapPost("/widgets/custom-validation", Results<ValidationProblem, Created<WidgetWithCustomValidation>> (WidgetWithCustomValidation widget) =>
!MiniValidator.TryValidate(widget, out var errors)
? Results.ValidationProblem(errors)
: Results.Created($"/widgets/{widget.Name}", widget));
? TypedResults.ValidationProblem(errors)
: TypedResults.Created($"/widgets/{widget.Name}", widget));

app.Run();

Expand Down
6 changes: 5 additions & 1 deletion tests/MiniValidation.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@

BenchmarkRunner.Run<Benchmarks>();

#pragma warning disable CA1050 // Declare types in namespaces
//[SimpleJob(RuntimeMoniker.Net472)]
//[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.Net70, baseline: true)]
[MemoryDiagnoser]
public class Benchmarks
{
[GlobalSetup]
#pragma warning disable CA1822 // Mark members as static
public void Initialize()
{
// Prime the internal type cache of MiniValidator
Expand Down Expand Up @@ -65,6 +67,7 @@ public void Initialize()
var isValid = MiniValidator.TryValidate(target, out var errors);
return (isValid, errors);
}
#pragma warning restore CA1822 // Mark members as static
}

public class BenchmarkTypes
Expand Down Expand Up @@ -100,4 +103,5 @@ public class Tag
[Required]
public string Name { get; set; } = default!;
}
}
}
#pragma warning restore CA1050 // Declare types in namespaces

0 comments on commit d68bd95

Please sign in to comment.