Generator Changes at 9/27/2025 10:36:00 AM

This commit is contained in:
generator
2025-09-27 10:36:00 +03:30
parent 15a7933a7a
commit 0e32dc9359
220 changed files with 7313 additions and 0 deletions

View File

@@ -0,0 +1,101 @@
using System.Diagnostics;
using System.Reflection;
using FrontOffice.BFF.Application.Common.Interfaces;
using Grpc.Core;
using System.Net.Http;
using Grpc.Net.ClientFactory;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Extensions.DependencyInjection;
public static class ConfigureGrpcServices
{
public static IServiceCollection BatchRegisterGrpcClients(this IServiceCollection services,
IConfiguration configuration)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
var grpcClients = assemblies
.Where(x =>
x.FullName != null &&
x.FullName.Contains("Microservice.Protobuf") &&
x.GetTypes().Any(type => type.BaseType != null && type.BaseType.Name == "ClientBase`1" && type.BaseType.Namespace == "Grpc.Core")
)
.SelectMany(x => x
.GetTypes()
.Where(type => type.BaseType != null && type.BaseType.Name == "ClientBase`1" && type.BaseType.Namespace == "Grpc.Core").ToList()
).ToList();
// get configuration as dictionary
var clientAddress = configuration.GetSection("GrpcChannelOptions")
.GetChildren().ToDictionary(x => x.Key, x => x.Value);
// get register method
var method = typeof(GrpcClientServiceExtensions).GetMethod("AddGrpcClient",
new[] { typeof(IServiceCollection), typeof(string), typeof(Action<GrpcClientFactoryOptions>) });
var httpHandler = new HttpClientHandler();
//TODO: چک شود
// Return `true` to allow certificates that are untrusted/invalid
httpHandler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
// register clients
foreach (var (key, address) in clientAddress)
{
var msName = key.Replace("MSAddress", "");
// loop over clients
foreach (var grpcClient in grpcClients.Where(t =>
t.AssemblyQualifiedName != null &&
t.AssemblyQualifiedName.StartsWith($"{msName}Microservice"))
.ToList())
{
// make generic method with parameter
var generic = method?.MakeGenericMethod(grpcClient);
Console.WriteLine($"Registering {grpcClient.Name} of {msName} to {address}");
//if (grpcClient.Name == "PublicMessageContractClient")
// continue;
// invoke method with parameters
var callResult = generic?.Invoke(null,
new object[]
{
services,$"{grpcClient.Namespace}",(GrpcClientFactoryOptions o) => { o.Address = new Uri(address); }
});
if (callResult == null)
{
Console.WriteLine($"Error registering {grpcClient.Name} of {msName} to {address}");
continue;
}
((IHttpClientBuilder)callResult)
.AddCallCredentials(CallCredentials)
.ConfigureChannel(o =>
{
o.HttpHandler = httpHandler;
o.UnsafeUseInsecureChannelCallCredentials = true;
o.MaxReceiveMessageSize = 1000 * 1024 * 1024; // 1 GB
o.MaxSendMessageSize = 1000 * 1024 * 1024; // 1 GB
});
}
}
return services;
}
public static IServiceCollection AddInfrastructureGrpcServices(this IServiceCollection services,
IConfiguration configuration)
{
services.BatchRegisterGrpcClients(configuration);
return services;
}
private static async Task CallCredentials(AuthInterceptorContext context, Metadata metadata,
IServiceProvider serviceProvider)
{
var provider = serviceProvider.GetRequiredService<ITokenProvider>();
var token = await provider.GetTokenAsync();
metadata.Add("Authorization", $"Bearer {token}");
}
}

View File

@@ -0,0 +1,77 @@
using System.Diagnostics;
using FrontOffice.BFF.Application.Common.Interfaces;
using FrontOffice.BFF.Infrastructure.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Extensions.DependencyInjection;
public static class ConfigureServices
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IApplicationContractContext, ApplicationContractContext>();
services.AddInfrastructureGrpcServices(configuration);
#region AddAuthentication
var message = "";
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwtBearerOptions =>
{
jwtBearerOptions.Authority = configuration["Authentication:Authority"];
jwtBearerOptions.Audience = configuration["Authentication:Audience"];
jwtBearerOptions.TokenValidationParameters.ValidateAudience = false;
jwtBearerOptions.TokenValidationParameters.ValidateIssuer = true;
jwtBearerOptions.TokenValidationParameters.ValidateIssuerSigningKey = false;
try
{
jwtBearerOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
message += "From OnAuthenticationFailed:\n";
message += ctx.Exception.Message;
return Task.CompletedTask;
},
OnChallenge = ctx =>
{
message += "From OnChallenge:\n";
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
ctx.Response.ContentType = "text/plain";
return ctx.Response.WriteAsync(message);
},
OnMessageReceived = ctx =>
{
message = "From OnMessageReceived:\n";
ctx.Request.Headers.TryGetValue("Authorization", out var BearerToken);
if (BearerToken.Count == 0)
BearerToken = "no Bearer token sent\n";
message += "Authorization Header sent: " + BearerToken + "\n";
return Task.CompletedTask;
},
OnTokenValidated = ctx =>
{
Debug.WriteLine("token: " + ctx.SecurityToken.ToString());
return Task.CompletedTask;
}
};
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
});
services.AddAuthorization();
#endregion
return services;
}
}

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.54.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FrontOffice.BFF.Application\FrontOffice.BFF.Application.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,5 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Text;
global using System.Threading.Tasks;

View File

@@ -0,0 +1,36 @@
using FrontOffice.BFF.Application.Common.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace FrontOffice.BFF.Infrastructure.Services;
public class ApplicationContractContext : IApplicationContractContext
{
#region members
private readonly IServiceProvider _serviceProvider;
#endregion
#region utilities
private T GetService<T>() where T : Grpc.Core.ClientBase<T>
{
return _serviceProvider.GetService<T>() ??
throw new Exception($"requested service not registered: {typeof(T).FullName}");
}
#endregion
public ApplicationContractContext(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
#region FM
//public FileLogContract.FileLogContractClient FileManagements => GetService<FileLogContract.FileLogContractClient>();
#endregion
}