<Project Sdk="Microsoft.NET.Sdk.Web">
 
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  
</Project>

<Project Sdk="Microsoft.NET.Sdk.Web">
 
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
    <UseBlazorWebAssembly>true</UseBlazorWebAssembly>
  </PropertyGroup>
  
</Project>  

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="5.0.0-preview.8.*" />
    <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0-preview.8.*" />
    <PackageReference Include="System.Net.Http.Json" Version="5.0.0-preview.8.*" />
  </ItemGroup>

app.UseEndpoints(endpoints =>
{
        endpoints.MapGet("/countries", async context =>
        {
               var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>();
 
               var countries = await countryService.Get();
 
               await context.Response.WriteAsJsonAsync(countries);
        }).RequireAuthorization();
});

app.UseEndpoints(endpoints =>
{
        endpoints.MapGet("/countries", async context =>
        {
               var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>();
 
               var countries = await countryService.Get();
 
               await context.Response.WriteAsJsonAsync(countries);
        }).AllowAnonymous();
});

using System;
namespace CustomAuthorizationFailureResponse.Authorization
{
    public class SampleAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
    {
        private readonly IAuthorizationMiddlewareResultHandler _handler;
 
        public SampleAuthorizationMiddlewareResultHandler(IAuthorizationMiddlewareResultHandler handler)
        {
            _handler = handler ?? throw new ArgumentNullException(nameof(handler));
        }
 
        public async Task HandleAsync(
            RequestDelegate requestDelegate,
            HttpContext httpContext,
            AuthorizationPolicy authorizationPolicy,
            PolicyAuthorizationResult policyAuthorizationResult)
        {
            // if the authorization was forbidden, let's use custom logic to handle that.
            if (policyAuthorizationResult.Forbidden && policyAuthorizationResult.AuthorizationFailure != null)
            {
                // as an example, let's return 404 if specific requirement has failed
                if (policyAuthorizationResult.AuthorizationFailure.FailedRequirements.Any(requirement => requirement is SampleRequirement))
                {
                    httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    await httpContext.Response.WriteAsync(Startup.CustomForbiddenMessage);
 
                    // return right away as the default implementation would overwrite the status code
                    return;
                }
                else if (policyAuthorizationResult.AuthorizationFailure.FailedRequirements.Any(requirement => requirement is SampleWithCustomMessageRequirement))
                {
                    // if other requirements failed, let's just use a custom message
                    // but we have to use OnStarting callback because the default handlers will want to modify i.e. status code of the response
                    // and modifications of the response are not allowed once the writing has started
                    var message = Startup.CustomForbiddenMessage;
 
                    httpContext.Response.OnStarting(() => httpContext.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(message)).AsTask());
                }
            }
 
            await _handler.HandleAsync(requestDelegate, httpContext, authorizationPolicy, policyAuthorizationResult);
        }
    }
}

public class CustomFilter : IHubFilter
{
    public async ValueTask<object> InvokeMethodAsync(
        HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object>> next)
    {
        Console.WriteLine($"Calling hub method '{invocationContext.HubMethodName}'");
        try
        {
            return await next(invocationContext);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception calling '{invocationContext.HubMethodName}'");
            throw ex;
        }
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR(options =>
    {
        options.AddFilter<CustomFilter>();
    });
 
    services.AddSingleton<CustomFilter>();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureKestrel(options =>
    {
        options.Limits.Http2.KeepAlivePingInterval = TimeSpan.FromSeconds(10);
        options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(1);
    });
    webBuilder.UseStartup<Startup>();
});

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureKestrel(options =>
    {
        options.RequestHeaderEncodingSelector = encoding =>
        {
            switch (encoding)
            {
                case "Host":
                    return System.Text.Encoding.Latin1;
                default:
                    return System.Text.Encoding.UTF8;
            }
        };
    });
    webBuilder.UseStartup<Startup>();
});

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
    logging.AddJsonConsole(options =>
    {
        options.JsonWriterOptions = new JsonWriterOptions() { Indented = true };
    });
})
.ConfigureWebHostDefaults(webBuilder =>
{
     webBuilder.UseStartup<Startup>();
});

{
  "EventId": 0,
  "LogLevel": "Information",
  "Category": "Microsoft.Hosting.Lifetime",
  "Message": "Now listening on: https://localhost:5001",
  "State": {
    "Message": "Now listening on: https://localhost:5001",
    "address": "https://localhost:5001",
    "{OriginalFormat}": "Now listening on: {address}"
  }
}

@inject LazyAssemblyLoader LazyAssemblyLoader
 
@code {
    var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll" });
}

@using System.Reflection
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader
 
<Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="lazyLoadedAssemblies" OnNavigateAsync="@OnNavigateAsync">
    <Navigating>
        <div>
            <p>Loading the requested page...</p>
        </div>
    </Navigating>
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="typeof(MainLayout)">
            <p>Sorry, there is nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
 
@code {
    private List<Assembly> lazyLoadedAssemblies = 
        new List<Assembly>();
 
    private async Task OnNavigateAsync(NavigationContext args)
    {
        if (args.Path.EndsWith("/page1"))
        {
            var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll"  });
            lazyLoadedAssemblies.AddRange(assemblies);
        }
    }
}

Opinion about blazor:
<InputRadioGroup @bind-Value="survey.OpinionAboutBlazor">
    @foreach (var opinion in opinions)
    {
        <div class="form-check">
            <InputRadio class="form-check-input" id="@opinion.id" Value="@opinion.id" />
            <label class="form-check-label" for="@opinion.id">@opinion.label</label>
        </div>
    }
</InputRadioGroup>

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput" />

@if (unreadNotificationsCount > 0)
{
    var title = $"Notifications ({unreadNotificationsCount})";
    <Title Value="title"></Title>
    <Link rel="icon" href="icon-unread.ico" />
}

public class Animal
{
    public int Id { get; set; }
    public string Species { get; set; }
}
 
public class Pet : Animal
{
    public string Name { get; set; }
}
 
public class Cat : Pet
{
    public string EducationLevel { get; set; }
}
 
public class Dog : Pet
{
    public string FavoriteToy { get; set; }
}

CREATE TABLE [Animals] (
    [Id] INT NOT NULL IDENTITY,
    [Species] NVARCHAR(MAX) NULL,
    [Discriminator] NVARCHAR(MAX) NOT NULL,
    [Name] NVARCHAR(MAX) NULL,
    [EducationLevel] NVARCHAR(MAX) NULL,
    [FavoriteToy] NVARCHAR(MAX) NULL,
    CONSTRAINT [PK_Animals] PRIMARY KEY ([Id]));

CREATE TABLE [Animals] (
    [Id] int NOT NULL IDENTITY,
    [Species] NVARCHAR(MAX) NULL,
    CONSTRAINT [PK_Animals] PRIMARY KEY ([Id])
);
 
CREATE TABLE [Pets] (
    [Id] int NOT NULL,
    [Name] NVARCHAR(MAX) NULL,
    CONSTRAINT [PK_Pets] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Pets_Animals_Id] FOREIGN KEY ([Id]) REFERENCES [Animals] ([Id]) ON DELETE NO ACTION
);
 
CREATE TABLE [Cats] (
    [Id] int NOT NULL,
    [EducationLevel] NVARCHAR(MAX) NULL,
    CONSTRAINT [PK_Cats] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Cats_Animals_Id] FOREIGN KEY ([Id]) REFERENCES [Animals] ([Id]) ON DELETE NO ACTION,
    CONSTRAINT [FK_Cats_Pets_Id] FOREIGN KEY ([Id]) REFERENCES [Pets] ([Id]) ON DELETE NO ACTION
);
 
CREATE TABLE [Dogs] (
    [Id] int NOT NULL,
    [FavoriteToy] NVARCHAR(MAX) NULL,
    CONSTRAINT [PK_Dogs] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Dogs_Animals_Id] FOREIGN KEY ([Id]) REFERENCES [Animals] ([Id]) ON DELETE NO ACTION,
    CONSTRAINT [FK_Dogs_Pets_Id] FOREIGN KEY ([Id]) REFERENCES [Pets] ([Id]) ON DELETE NO ACTION
);

[Table("Animals")]
public class Animal
{
    public int Id { get; set; }
    public string Species { get; set; }
}
 
[Table("Pets")]
public class Pet : Animal
{
    public string Name { get; set; }
}

[Table("Cats")]
public class Cat : Pet
{
    public string EducationLevel { get; set; }
}
 
[Table("Dogs")]
public class Dog : Pet
{
    public string FavoriteToy { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Animal>().ToTable("Animals");
    modelBuilder.Entity<Pet>().ToTable("Pets");
    modelBuilder.Entity<Cat>().ToTable("Cats");
    modelBuilder.Entity<Dog>().ToTable("Dogs");
}

CREATE FUNCTION GetReports(@employeeId INT)
RETURNS @reports TABLE
(
	Name NVARCHAR (50) NOT NULL,
	IsDeveloper BIT NOT NULL
)
AS
BEGIN
	WITH cteEmployees AS
	(
		SELECT Id, Name, ManagerId, IsDeveloper
		FROM Employees
		WHERE Id = @employeeId
		UNION ALL
		SELECT e.Id, e.Name, e.ManagerId, e.IsDeveloper
		FROM Employees e
		INNER JOIN cteEmployees cteEmp ON cteEmp.Id = e.ManagerId
	)
	INSERT INTO @reports
	SELECT Name, IsDeveloper
	FROM cteEmployees
	WHERE Id != @employeeId
 
	RETURN
END

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeveloper { get; set; }
 
    public int? ManagerId { get; set; }
    public virtual Employee Manager { get; set; }
}
 
public class Report
{
    public string Name { get; set; }
    public bool IsDeveloper { get; set; }
}

modelBuilder.Entity<Employee>();
modelBuilder.Entity(typeof(Report)).HasNoKey();

var query = from employee in context.Employees
from report in context.GetReports(e.Id)
where report.IsDeveloper == true
select new
{
    ManagerName = employee.Name,
    EmployeeName = report.Name,
});

public class MyRepository
{
    private readonly IDbContextFactory<MyDbContext> _contextFactory;
 
    public MyRepository(IDbContextFactory<MyDbContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }
}