Initial version

This commit is contained in:
2026-06-09 22:27:38 +02:00
parent 5afbf3b01c
commit 5ff2ac8941
57 changed files with 2343 additions and 98 deletions
+5 -55
View File
@@ -1,8 +1,7 @@
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@@ -30,6 +29,7 @@ x86/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
@@ -83,8 +83,6 @@ StyleCopReport.xml
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
@@ -93,7 +91,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@@ -297,17 +294,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@@ -364,9 +350,6 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
@@ -378,39 +361,6 @@ MigrationBackup/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
/Api/appsettings.Development.json
/README.md
/README.md
@@ -0,0 +1,12 @@
using System.Text.Json;
namespace EonaCat.gRPC.Api.Converters;
public class TrimStringConverter : System.Text.Json.Serialization.JsonConverter<string>
{
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> reader.GetString()?.Trim();
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
}
+30
View File
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="EonaCat.LogStack" Version="0.0.8" />
<PackageReference Include="Grpc.AspNetCore" Version="2.80.0" />
<PackageReference Include="Grpc.AspNetCore.Server.Reflection" Version="2.80.0" />
<PackageReference Include="Grpc.Core" Version="2.46.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Grpc.Swagger" Version="0.10.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.19.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.gRPC.Proto\EonaCat.gRPC.Proto.csproj" />
<ProjectReference Include="..\EonaCat.gRPC.Service\EonaCat.gRPC.Service.csproj" />
</ItemGroup>
</Project>
+11
View File
@@ -0,0 +1,11 @@
global using EonaCat.gRPC.Api.Helpers;
global using EonaCat.gRPC.Api.Middleware.Interceptors;
global using EonaCat.gRPC.Api.Services;
global using Grpc.Core;
global using Grpc.Core.Interceptors;
global using Microsoft.Data.SqlClient;
global using Microsoft.OpenApi.Models;
global using EonaCat.gRPC.Core.Entities;
global using EonaCat.gRPC.Core.Interfaces.Repositories;
global using Microsoft.EntityFrameworkCore;
global using EonaCat.Json;
+9
View File
@@ -0,0 +1,9 @@
namespace EonaCat.gRPC.Api.Helpers;
public class AppSettings
{
public string Secret { get; set; } = null!;
public int Validity { get; set; }
public string Issuer { get; set; } = null!;
public string Audience { get; set; } = null!;
}
@@ -0,0 +1,10 @@
namespace EonaCat.gRPC.Api.Helpers
{
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
}
+34
View File
@@ -0,0 +1,34 @@
namespace EonaCat.gRPC.Api.Helpers;
public static class CustomMapper
{
/// <summary>
/// Proto to Entity/DTO And Reverse
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TDestination"></typeparam>
/// <param name="src"></param>
/// <returns>TDestination</returns>
public static TDestination Map<TSource, TDestination>(TSource src) where TDestination : new()
{
try
{
var tDest = (TDestination)Activator.CreateInstance(typeof(TDestination))!;
if (src == null)
return tDest;
var srcClassType = src.GetType();
var srcProperties = srcClassType.GetProperties();
foreach (var srcProperty in srcProperties)
{
var destPropertyInfo = tDest.GetType().GetProperty(srcProperty.Name);
if (srcProperty.GetType() == destPropertyInfo?.GetType())
destPropertyInfo.SetValue(tDest, srcProperty.GetValue(src, null), null);
}
return tDest;
}
catch (Exception e)
{
throw new Exception($"Unsupported mapping.\n{e.Message}");
}
}
}
@@ -0,0 +1,54 @@
using ProtoBuf.Grpc;
namespace EonaCat.gRPC.Api.Helpers;
public static class ExceptionHelpers
{
public static RpcException Handle<T>(this Exception exception, ServerCallContext context, ILogger<T> logger, Guid correlationId) =>
exception switch
{
TimeoutException timeoutException => HandleTimeoutException(timeoutException, context, logger, correlationId),
SqlException sqlException => HandleSqlException(sqlException, context, logger, correlationId),
RpcException rpcException => HandleRpcException(rpcException, logger, correlationId),
_ => HandleDefault(exception, context, logger, correlationId)
};
private static RpcException HandleTimeoutException<T>(TimeoutException exception, ServerCallContext context, ILogger<T> logger, Guid correlationId)
{
logger.LogError(exception, $"CorrelationId: {correlationId} - A timeout occurred");
var status = new Status(StatusCode.Internal, "An external resource did not answer within the time limit");
return new RpcException(status, CreateTrailers(correlationId));
}
private static RpcException HandleSqlException<T>(SqlException exception, ServerCallContext context, ILogger<T> logger, Guid correlationId)
{
logger.LogError(exception, $"CorrelationId: {correlationId} - An SQL error occurred");
Status status;
if (exception.Number == -2)
status = new Status(StatusCode.DeadlineExceeded, "SQL timeout");
else
status = new Status(StatusCode.Internal, "SQL error");
return new RpcException(status, CreateTrailers(correlationId));
}
private static RpcException HandleRpcException<T>(RpcException exception, ILogger<T> logger, Guid correlationId)
{
logger.LogError(exception, $"CorrelationId: {correlationId} - An error occurred");
//var trailers = exception.Trailers;
//var d = CreateTrailers(correlationId);
//trailers.Add(d[0]);
return new RpcException(new Status(exception.StatusCode, exception.Message), CreateTrailers(correlationId));
}
private static RpcException HandleDefault<T>(Exception exception, ServerCallContext context, ILogger<T> logger, Guid correlationId)
{
logger.LogError(exception, $"CorrelationId: {correlationId} - An error occurred");
return new RpcException(new Status(StatusCode.Internal, exception.Message), CreateTrailers(correlationId));
}
private static Metadata CreateTrailers(Guid correlationId)
{
var trailers = new Metadata { { "CorrelationId", correlationId.ToString() } };
return trailers;
}
}
+104
View File
@@ -0,0 +1,104 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using EonaCat.gRPC.Core.Interfaces.Services;
using EonaCat.gRPC.Repository;
using EonaCat.gRPC.Repository.Base;
using EonaCat.gRPC.Repository.DatabaseContext;
using EonaCat.gRPC.Service;
using System.Text;
using EonaCat.LogStack.Extensions;
using EonaCat.Mapper;
namespace EonaCat.gRPC.Api.Helpers;
public static class Extension
{
public static void AddInfrastructureServices(this WebApplicationBuilder builder)
{
RegisterSwagger(builder);
RegisterLogger(builder);
RegisterDatabaseContext(builder);
RegisterAuthentication(builder);
}
public static void AddBusinessServices(this WebApplicationBuilder builder)
{
RegisterRepositoryDependencies(builder.Services);
RegisterServiceDependencies(builder);
}
public static void RegisterServiceDependencies(WebApplicationBuilder builder)
{
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("Jwt"));
builder.Services.AddTransient<IUserService, UserService>();
}
private static void RegisterRepositoryDependencies(IServiceCollection services)
{
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
services.AddScoped<IUserRepository, UserRepository>();
}
private static void RegisterAuthentication(WebApplicationBuilder builder)
{
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration.GetSection("Jwt").GetSection("Secret").Value)),
ValidateIssuer = false,
ValidateAudience = false,
};
});
}
private static void RegisterDatabaseContext(WebApplicationBuilder builder)
{
builder.Services.AddDbContext<AppDbContext>((provider, options) =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
}
private static void RegisterLogger(WebApplicationBuilder builder)
{
builder.AddEonaCatLogging((x) => x
.AddFlow(new LogStack.Flows.ConsoleFlow())
.AddFlow(new LogStack.Flows.FileFlow("./logs")));
}
private static void RegisterSwagger(WebApplicationBuilder builder)
{
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "EonaCat gRPC API",
Version = "v1",
Description = "EonaCat gRPC API"
});
});
}
public static void AppUseSwagger(this WebApplication app)
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "EonaCat gRPC API");
options.RoutePrefix = string.Empty;
});
}
public static void MapGrpcServices(this WebApplication app)
{
app.MapGrpcService<UserHandler>();
app.MapGrpcService<AuthenticationHandler>();
}
}
@@ -0,0 +1,40 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using EonaCat.gRPC.Proto;
namespace EonaCat.gRPC.Api.Helpers;
public static class JwtAuthenticationManager
{
public static AuthenticationResponse Authenticate(IOptions<AppSettings> appSettings, AuthenticationRequest authenticationRequest)
{
// Implement DbCheck ----
if (authenticationRequest.UserName != "admin" || authenticationRequest.Password != "admin")
throw new RpcException(new Status(StatusCode.Unauthenticated, "Invalid ProtoUserResponse Credentials"));
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var tokenKey = Encoding.ASCII.GetBytes(appSettings.Value.Secret);
var tokenExpiryDateTime = DateTime.UtcNow.AddMinutes(appSettings.Value.Validity);
var securityTokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new List<Claim>
{
new(ClaimTypes.Name, authenticationRequest.UserName),
new(ClaimTypes.Role, "Administrator")
}),
Expires = tokenExpiryDateTime,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature)
};
var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
var token = jwtSecurityTokenHandler.WriteToken(securityToken);
return new AuthenticationResponse
{
AccessToken = token,
ExpiresIn = (int)tokenExpiryDateTime.Subtract(DateTime.UtcNow).TotalSeconds
};
}
}
@@ -0,0 +1,34 @@
using EonaCat.Json.Converters;
using EonaCat.Json.Serialization;
using System.Reflection;
namespace EonaCat.gRPC.Api.Helpers;
public class TimeStampContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType == typeof(Google.Protobuf.WellKnownTypes.Timestamp))
{
property.Converter = new TimeStampConverter();
}
return property;
}
}
public class TimeStampConverter : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var date = DateTime.Parse(reader.Value?.ToString());
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
return Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(date);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((Google.Protobuf.WellKnownTypes.Timestamp)value).ToString());
}
}
@@ -0,0 +1,78 @@
using EonaCat.gRPC.Api.Helpers;
namespace EonaCat.gRPC.Api.Middleware.Interceptors;
public class ExceptionInterceptor : Interceptor
{
private readonly ILogger<ExceptionInterceptor> _logger;
private readonly Guid _correlationId;
public ExceptionInterceptor(ILogger<ExceptionInterceptor> logger)
{
_logger = logger;
_correlationId = Guid.NewGuid();
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
try
{
return await continuation(request, context);
}
catch (Exception e)
{
throw e.Handle(context, _logger, _correlationId);
}
}
public override async Task<TResponse> ClientStreamingServerHandler<TRequest, TResponse>(
IAsyncStreamReader<TRequest> requestStream,
ServerCallContext context,
ClientStreamingServerMethod<TRequest, TResponse> continuation)
{
try
{
return await continuation(requestStream, context);
}
catch (Exception e)
{
throw e.Handle(context, _logger, _correlationId);
}
}
public override async Task ServerStreamingServerHandler<TRequest, TResponse>(
TRequest request,
IServerStreamWriter<TResponse> responseStream,
ServerCallContext context,
ServerStreamingServerMethod<TRequest, TResponse> continuation)
{
try
{
await continuation(request, responseStream, context);
}
catch (Exception e)
{
throw e.Handle(context, _logger, _correlationId);
}
}
public override async Task DuplexStreamingServerHandler<TRequest, TResponse>(
IAsyncStreamReader<TRequest> requestStream,
IServerStreamWriter<TResponse> responseStream,
ServerCallContext context,
DuplexStreamingServerMethod<TRequest, TResponse> continuation)
{
try
{
await continuation(requestStream, responseStream, context);
}
catch (Exception e)
{
throw e.Handle(context, _logger, _correlationId);
}
}
}
@@ -0,0 +1,49 @@
namespace EonaCat.gRPC.Api.Middleware.Interceptors;
public class LoggerInterceptor : Interceptor
{
private readonly ILogger<LoggerInterceptor> _logger;
public LoggerInterceptor(ILogger<LoggerInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
LogCall(context);
try
{
return await continuation(request, context);
}
catch (SqlException e)
{
_logger.LogError(e, $"An SQL error occurred when calling {context.Method}");
Status status = e.Number == -2
? new Status(StatusCode.DeadlineExceeded, $"SQL timeout: {e.Message}")
: new Status(StatusCode.Internal, $"SQL error: {e.Message}");
throw new RpcException(status, e.Message);
}
catch (RpcException e)
{
_logger.LogError(e, $"gRPC error when calling {context.Method}: {e.Status.Detail}");
throw;
}
catch (Exception e)
{
_logger.LogError(e, $"An error occurred when calling {context.Method}");
throw new RpcException(Status.DefaultCancelled, e.Message);
}
}
private void LogCall(ServerCallContext context)
{
var httpContext = context.GetHttpContext();
_logger.LogDebug($"Starting call. Request: {httpContext.Request.Path}");
}
}
+48
View File
@@ -0,0 +1,48 @@
using ProtoBuf.Grpc.Server;
using EonaCat.gRPC.Api.Helpers;
using EonaCat.gRPC.Api.Middleware.Interceptors;
using CompressionLevel = System.IO.Compression.CompressionLevel;
var builder = WebApplication.CreateBuilder(args);
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
// Add services to the container.
// Start: gRPC Configurations
builder.Services.AddGrpc(options =>
{
options.Interceptors.Add<LoggerInterceptor>();
options.Interceptors.Add<ExceptionInterceptor>();
});
builder.Services.AddGrpcReflection();
builder.Services.AddGrpc().AddJsonTranscoding();
builder.Services.AddGrpcSwagger();
builder.Services.AddCodeFirstGrpc(config =>
{
config.ResponseCompressionLevel = CompressionLevel.Optimal;
});
//builder.Services.TryAddSingleton(BinderConfiguration.Create(
// binder: new ServiceBinderWithServiceResolutionFromServiceCollection(builder.Services)));
//builder.Services.AddCodeFirstGrpcReflection();
// End: gRPC Configurations
builder.AddInfrastructureServices();
builder.AddBusinessServices();
builder.Services.AddAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.AppUseSwagger();
app.MapGrpcReflectionService();
app.UseAuthentication();
app.UseAuthorization();
app.MapGrpcServices();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();
@@ -0,0 +1,22 @@
{
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5227",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7166;http://localhost:5227",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -0,0 +1,24 @@
using Microsoft.Extensions.Options;
using ProtoBuf.Grpc;
using EonaCat.gRPC.Api.Helpers;
using EonaCat.gRPC.Proto;
namespace EonaCat.gRPC.Api.Services;
public class AuthenticationHandler : IAuthenticationService
{
private readonly IOptions<AppSettings> _appSettings;
public AuthenticationHandler(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings;
}
public Task<AuthenticationResponse> Authenticate(AuthenticationRequest request, CallContext context = default)
{
var authenticationResponse = JwtAuthenticationManager.Authenticate(_appSettings, request);
if (authenticationResponse == null)
throw new RpcException(new Status(StatusCode.Unauthenticated, "Invalid ProtoUserResponse Credentials"));
return Task.FromResult(authenticationResponse);
}
}
+38
View File
@@ -0,0 +1,38 @@
using EonaCat.gRPC.Core.Interfaces.Services;
using EonaCat.gRPC.Proto;
using EonaCat.Mapper;
namespace EonaCat.gRPC.Api.Services;
public class UserHandler : IProtoUserService
{
private readonly IUserService _userService;
public UserHandler(IUserService userService)
{
_userService = userService;
}
public async ValueTask<BaseResponse<string>> Create(UserCreateRequest userCreateRequest)
{
var user = CustomMapper.Map<UserCreateRequest, UserEntity>(userCreateRequest);
var response = await _userService.CreateUser(user);
return BaseResponse<string>.Created(response.ToString());
}
public async Task<BaseResponse<List<UserResponse>?>> GetAsync()
{
var users = await _userService.GetAsync();
var mapped = CustomMapper.Map<List<UserEntity>, List<UserResponse>>(users.ToList());
return BaseResponse<List<UserResponse>?>.Ok(mapped);
}
public async Task<BaseResponse<UserResponse?>> GetByIdAsync(string id)
{
if (string.IsNullOrEmpty(id) || !long.TryParse(id, out _))
return BaseResponse<UserResponse?>.Failed(null, message: "Invalid ID: It is either empty or not a valid long.");
var user = await _userService.GetAsync(Convert.ToInt64(id));
var mapped = CustomMapper.Map<UserEntity, UserResponse>(user);
return BaseResponse<UserResponse>.Ok(mapped);
}
}
@@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=EONACAT_TESTMACHINE;Database=EonaCatgRPC;User ID=sa;Password=mytestpassword;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;User Id=YOUR_USER_ID; Password=YOUR_PASSWORD; Database=YOUR_DATABASE_NAME"
},
"Jwt": {
"Secret": "ertwet3245sgf2342werwergww4352345",
"Issuer": "https://localhost:7166/",
"Audience": "https://localhost:7166/",
"Validity": 30
},
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
}
}
}
+19
View File
@@ -0,0 +1,19 @@
using EonaCat.gRPC.Proto;
namespace EonaCat.gRPC.Client;
public interface ITokenProvider
{
Task<AuthenticationResponse> GetTokenAsync();
}
public class AppTokenProvider : ITokenProvider
{
private AuthenticationResponse _token;
public async Task<AuthenticationResponse> GetTokenAsync()
{
if (_token == null)
_token = new AuthenticationResponse { AccessToken = "test", ExpiresIn = 300 };
return _token;
}
}
+19
View File
@@ -0,0 +1,19 @@
using Grpc.Core;
using ProtoBuf.Grpc.Client;
using EonaCat.gRPC.Proto;
namespace EonaCat.gRPC.Client;
public class AuthService
{
public static async Task Authenticate(CallInvoker invoker)
{
var authenticationClient = invoker.CreateGrpcService<IAuthenticationService>();
var authenticationResponse = await authenticationClient.Authenticate(new AuthenticationRequest
{
UserName = "admin",
Password = "admin"
});
Console.WriteLine($"Received Authentication Response - \nToken: {authenticationResponse.AccessToken}\nExpires In: {authenticationResponse.ExpiresIn}");
}
}
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Interfaces\**" />
<EmbeddedResource Remove="Interfaces\**" />
<None Remove="Interfaces\**" />
</ItemGroup>
<ItemGroup>
<None Remove="Protos\base.proto" />
<None Remove="Protos\user.proto" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="EonaCat.LogStack" Version="0.0.8" />
<PackageReference Include="Grpc.Net.Client" Version="2.80.0" />
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.80.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.gRPC.Proto\EonaCat.gRPC.Proto.csproj" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\base.proto" GrpcServices="Client" />
<Protobuf Include="Protos\user.proto" GrpcServices="Client" />
</ItemGroup>
</Project>
+101
View File
@@ -0,0 +1,101 @@
using Bogus;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using ProtoBuf.Grpc.Client;
using EonaCat.gRPC.Client.Helpers;
using EonaCat.gRPC.Proto;
using EonaCat.LogStack.Logging;
namespace EonaCat.gRPC.Client;
public static class Extension
{
public static async Task ExecutePrograms(CallInvoker callInvoker)
{
while (true)
{
Console.WriteLine("\nEnter 1 to execute Authenticate.\n" +
"Enter 2 to execute Create User With Demo Data\n" +
"Enter 3 to execute User List Async\n" +
"Enter 4 to execute User GetById Async\n" +
"Enter 0 to exit.\n");
var input = Console.ReadLine();
input = input?.Trim(' ', '"', '\'');
if (!int.TryParse(input, out var value) || value is not (0 or 1 or 2 or 3 or 4))
{
ConsoleExtensions.Error("Invalid input. Please enter a valid option (0, 1, 2, 3, or 4).");
continue;
}
if (value == 0)
break;
try
{
switch (value)
{
case 1:
await AuthService.Authenticate(callInvoker);
break;
case 2:
await CreateUser(callInvoker);
break;
case 3:
await UserListAsync(callInvoker);
break;
case 4:
await UserGetByIdAsync(callInvoker);
break;
}
}
catch (Exception e)
{
ConsoleExtensions.Error($"Error: {e.Message}");
}
}
}
public static async Task Authenticate(CallInvoker invoker)
{
var authenticationClient = invoker.CreateGrpcService<IAuthenticationService>();
var authenticationResponse = await authenticationClient.Authenticate(new AuthenticationRequest
{
UserName = "admin",
Password = "admin"
});
ConsoleExtensions.Success($"Received Authentication Response - \nToken: {authenticationResponse.AccessToken}\nExpires In: {authenticationResponse.ExpiresIn}");
}
private static async Task CreateUser(CallInvoker callInvoker)
{
var userClient = callInvoker.CreateGrpcService<IProtoUserService>();
var faker = new Faker();
var userCreateRequest = new UserCreateRequest
{
FirstName = faker.Person.FirstName,
LastName = faker.Person.LastName,
Email = faker.Person.Email
};
var userResponse = await userClient.Create(userCreateRequest);
ConsoleExtensions.PrintResponse(userResponse);
}
private static async Task UserGetByIdAsync(CallInvoker callInvoker)
{
Console.Write("Please Enter an UserId : ");
var userId = Console.ReadLine() ?? string.Empty;
userId = userId.Trim(' ', '"', '\'');
var userClient = callInvoker.CreateGrpcService<IProtoUserService>();
var userResponse = await userClient.GetByIdAsync(userId);
ConsoleExtensions.PrintResponse(userResponse);
}
private static async Task UserListAsync(CallInvoker callInvoker)
{
var userClient = callInvoker.CreateGrpcService<IProtoUserService>();
var userResponse = await userClient.GetAsync();
ConsoleExtensions.PrintResponse(userResponse);
}
}
@@ -0,0 +1,35 @@
using Grpc.Core;
using Grpc.Core.Interceptors;
using EonaCat.gRPC.Proto;
using Microsoft.AspNetCore.Http;
namespace EonaCat.gRPC.Client.Helpers;
public class AuthHeaderInterceptor : Interceptor
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthHeaderInterceptor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context,
AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
var metadata = new Metadata();
//var authResponse = AuthService.Authenticate();
var authResponse = new AuthenticationResponse();
metadata.Add("authorization", $"Bearer {authResponse.AccessToken}");
metadata.Add("expiry", $"{authResponse.ExpiresIn}");
var userIdentity = _httpContextAccessor.HttpContext?.User.Identity;
if (userIdentity is { IsAuthenticated: true, Name: { } })
metadata.Add("User", userIdentity.Name);
var callOptions = context.Options.WithHeaders(metadata);
context = new ClientInterceptorContext<TRequest, TResponse>(context.Method, context.Host, callOptions);
return base.AsyncUnaryCall(request, context, continuation);
}
}
@@ -0,0 +1,70 @@
using EonaCat.gRPC.Proto;
using EonaCat.Json;
namespace EonaCat.gRPC.Client.Helpers;
public static class ConsoleExtensions
{
public static void Success(string data, bool disableNewLine = false)
{
Console.ForegroundColor = ConsoleColor.Green;
if (disableNewLine)
Console.Write(data);
else
Console.WriteLine(data);
Console.ResetColor();
}
public static void Error(string message, bool disableNewLine = false)
{
Console.ForegroundColor = ConsoleColor.Red;
if (disableNewLine)
Console.Write(message);
else
Console.WriteLine(message);
Console.ResetColor();
}
public static void PrintResponse<T>(BaseResponse<T> response, Formatting formatting = Formatting.Indented) where T : class?
{
try
{
if (response.IsSuccess)
{
Success("------ Success Response ------");
if (response.Data != null)
{
Success("Response:");
Success(JsonHelper.ToJson(response, formatting));
foreach (var property in response.Data.GetType().GetProperties())
{
var value = property.GetValue(response.Data);
if (value != null)
{
Success($"{property.Name}: {value}");
}
else
{
Success($"{property.Name}: null");
}
}
}
else
{
Success("No data available in the response.");
}
}
else
{
// Print error response
Error("------ Error Response ------");
Error($"Message: {response.Message}");
}
}
catch (Exception e)
{
// do nothing.
}
}
}
@@ -0,0 +1,70 @@
// enhance-your-grpc-client-logs-with-a-generic-logging-interceptor
// https://anthonygiretti.com/2022/08/08/net-6-enhance-your-grpc-client-logs-with-a-generic-logging-interceptor/
using Grpc.Core;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Logging;
namespace EonaCat.gRPC.Client.Helpers;
public class TracerInterceptor : Interceptor
{
private readonly ILogger<TracerInterceptor> _logger;
public TracerInterceptor(ILoggerFactory logger)
{
_logger = logger.CreateLogger<TracerInterceptor>();
}
public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> context,
AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
where TRequest : class
where TResponse : class
{
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method at {DateTime.UtcNow} UTC from machine {Environment.MachineName}");
var continued = continuation(context);
return continued;
}
public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> context,
AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation)
where TRequest : class
where TResponse : class
{
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method at {DateTime.UtcNow} UTC from machine {Environment.MachineName}");
var continued = continuation(context);
return continued;
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation)
where TRequest : class
where TResponse : class
{
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method. Payload received: {request.GetType()} : {request}");
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method at {DateTime.UtcNow} UTC from machine {Environment.MachineName}");
var continued = continuation(request, context);
return continued;
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
where TRequest : class
where TResponse : class
{
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method. Payload received: {request.GetType()} : {request}");
_logger.LogDebug($"Calling {context.Method.Name} {context.Method.Type} method at {DateTime.UtcNow} UTC from machine {Environment.MachineName}");
var continued = continuation(request, context);
return continued;
}
}
+33
View File
@@ -0,0 +1,33 @@
using Grpc.Core.Interceptors;
using Grpc.Net.Client;
using EonaCat.gRPC.Client.Helpers;
using EonaCat.gRPC.Client;
using EonaCat.LogStack.Logging;
using EonaCat.LogStack.Extensions;
using Microsoft.Extensions.Logging;
Console.WriteLine("Welcome to EonaCat.gRPC Client Application.");
const string serverAddress = "http://localhost:5227";
//var (invoker, channel) = Extension.ConfigureChannel(serverAddress, loggerFactory);
using var channel = GrpcChannel.ForAddress(serverAddress, new GrpcChannelOptions
{
LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
{
builder.AddEonaCatLogging();
builder.SetMinimumLevel(LogLevel.Debug);
})
});
var invoker = channel.Intercept(new TracerInterceptor(Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
{
builder.AddEonaCatLogging();
builder.SetMinimumLevel(LogLevel.Debug);
})));
await Extension.ExecutePrograms(invoker);
Console.ReadKey();
await channel.ShutdownAsync();
+10
View File
@@ -0,0 +1,10 @@
syntax = "proto3";
option csharp_namespace = "GRPC.NET7.Api.Protos";
package base;
message BaseResponse {
bool isSuccess = 1;
string message = 2;
string data = 3;
}
+20
View File
@@ -0,0 +1,20 @@
syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
import "Protos/base.proto";
option csharp_namespace = "GRPC.NET7.Api.Protos";
package user;
service User {
rpc Create(UserCreateRequest) returns (base.BaseResponse) { }
rpc Get(google.protobuf.Empty) returns (base.BaseResponse) { }
}
message UserCreateRequest {
string firstName = 1;
string lastName = 2;
string email = 3;
//google.protobuf.Timestamp dateOfBirth = 4;
string gender = 5;
}
@@ -0,0 +1,8 @@
namespace EonaCat.gRPC.Core.Dtos;
public class BaseResponseDto<T>
{
public bool IsSuccess { get; set; }
public string? Message { get; set; }
public T? Data { get; set; }
}
+10
View File
@@ -0,0 +1,10 @@
using EonaCat.Entities;
namespace EonaCat.gRPC.Core.Entities;
public class BaseEntity : Entity
{
public bool IsDeleted { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
+8
View File
@@ -0,0 +1,8 @@
namespace EonaCat.gRPC.Core.Entities;
public class UserEntity : BaseEntity
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string Email { get; set; } = null!;
}
+11
View File
@@ -0,0 +1,11 @@
namespace EonaCat.gRPC.Core.Enums;
public class AppEnums
{
public enum Gender
{
Male = 0,
Female = 1,
Other = 2
}
}
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Constants\**" />
<Compile Remove="Settings\**" />
<EmbeddedResource Remove="Constants\**" />
<EmbeddedResource Remove="Settings\**" />
<None Remove="Constants\**" />
<None Remove="Settings\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.EFCore" Version="0.0.1" />
<PackageReference Include="EonaCat.Mapper" Version="1.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9" />
</ItemGroup>
</Project>
@@ -0,0 +1,15 @@
using EonaCat.gRPC.Core.Entities;
using EonaCat.Repositories;
namespace EonaCat.gRPC.Core.Interfaces.Repositories;
public interface IBaseRepository<T> : IRepository<T> where T : BaseEntity
{
/// <param name="acceptAllChangesOnSuccess">
/// Indicates whether <see cref="Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AcceptAllChanges" /> is called after
/// the changes have been sent successfully to the database.
/// </param>
Task SaveChangesAsync(bool acceptAllChangesOnSuccess);
Task SaveChangesAsync();
void Save();
}
@@ -0,0 +1,7 @@
using EonaCat.gRPC.Core.Entities;
namespace EonaCat.gRPC.Core.Interfaces.Repositories;
public interface IUserRepository : IBaseRepository<UserEntity>
{
}
@@ -0,0 +1,5 @@
namespace EonaCat.gRPC.Core.Interfaces.Services;
public interface IGreeterService
{
}
@@ -0,0 +1,10 @@
using EonaCat.gRPC.Core.Entities;
namespace EonaCat.gRPC.Core.Interfaces.Services;
public interface IUserService
{
Task<long> CreateUser(UserEntity user);
Task<IEnumerable<UserEntity>> GetAsync();
Task<UserEntity> GetAsync(long id);
}
+36
View File
@@ -0,0 +1,36 @@
using System.Runtime.Serialization;
using System.ServiceModel;
using ProtoBuf.Grpc;
namespace EonaCat.gRPC.Proto
{
public class Authentication
{
}
[ServiceContract]
public interface IAuthenticationService
{
[OperationContract]
Task<AuthenticationResponse> Authenticate(AuthenticationRequest request, CallContext context = default);
}
[DataContract]
public class AuthenticationRequest
{
[DataMember(Order = 1)]
public string UserName { get; set; } = null!;
[DataMember(Order = 2)]
public string Password { get; set; } = null!;
}
[DataContract]
public class AuthenticationResponse
{
[DataMember(Order = 1)]
public string AccessToken { get; set; } = null!;
[DataMember(Order = 2)]
public int ExpiresIn { get; set; }
}
}
+126
View File
@@ -0,0 +1,126 @@
using ProtoBuf;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace EonaCat.gRPC.Proto;
[ProtoContract]
public class BaseResponse<T>
{
[ProtoMember(1)]
public bool IsSuccess { get; set; }
[ProtoMember(2)]
public string? Message { get; set; }
[ProtoMember(3)]
public T? Data { get; set; }
public static BaseResponse<T?> Ok(T? data, string? message = null)
{
return new BaseResponse<T?>
{
IsSuccess = true,
Message = message,
Data = data
};
}
public static BaseResponse<T> Created(T? data, string? message = null)
{
return new BaseResponse<T>
{
IsSuccess = true,
Message = string.IsNullOrEmpty(message)
? ConstructMessage(GetCallingClassName())
: message,
Data = data
};
}
public static BaseResponse<T> Updated(T? data, string? message = null)
{
return new BaseResponse<T>
{
IsSuccess = true,
Message = string.IsNullOrEmpty(message)
? ConstructMessage(GetCallingClassName())
: message,
Data = data
};
}
public static BaseResponse<T> Deleted(T? data, string? message = null)
{
return new BaseResponse<T>
{
IsSuccess = true,
Message = string.IsNullOrEmpty(message)
? ConstructMessage(GetCallingClassName())
: message,
Data = data
};
}
public static BaseResponse<T> Failed(T? data, string? message = null, [CallerMemberName] string actionName = "")
{
return new BaseResponse<T>
{
IsSuccess = false,
Message = string.IsNullOrEmpty(message)
? ConstructMessage(GetCallingClassName(), false, actionName)
: message,
Data = data
};
}
#region Private Methods
private static string ConstructMessage(string callerName, bool isSuccess = true, [CallerMemberName] string actionName = "")
{
var messageStatus = isSuccess ? "Successfully" : "Failed";
try
{
if (callerName.Contains("Service"))
{
var entityName = callerName[..^7];
return $"{entityName} {actionName} {messageStatus}";
}
return $"{actionName} {messageStatus}";
}
catch (Exception)
{
// Ignore the exception...
return $"{actionName} {messageStatus}";
}
}
private static string GetCallingClassName()
{
string fullName;
Type declaringType;
var skipFrames = 2;
try
{
do
{
var method = new StackFrame(skipFrames, false).GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
return method.Name;
}
skipFrames++;
fullName = declaringType.ReflectedType?.Name;
}
while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return fullName;
}
catch (Exception)
{
return string.Empty;
}
}
#endregion
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="protobuf-net.Grpc" Version="1.2.2" />
<PackageReference Include="protobuf-net.Grpc.AspNetCore" Version="1.2.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.gRPC.Core\EonaCat.gRPC.Core.csproj" />
</ItemGroup>
</Project>
+44
View File
@@ -0,0 +1,44 @@
using ProtoBuf;
namespace EonaCat.gRPC.Proto.Helpers;
public static class Utility
{
public static byte[] ProtoSerialize<T>(T record) where T : class
{
if (null == record) return null;
try
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, record);
return stream.ToArray();
}
}
catch
{
// Log error
throw;
}
}
public static T ProtoDeserialize<T>(byte[] data) where T : class
{
if (null == data) return null;
try
{
using (var stream = new MemoryStream(data))
{
return Serializer.Deserialize<T>(stream);
}
}
catch
{
// Log error
throw;
}
}
}
+49
View File
@@ -0,0 +1,49 @@
using System.ServiceModel;
using ProtoBuf;
using EonaCat.gRPC.Core.Entities;
namespace EonaCat.gRPC.Proto;
public class User
{
}
[ServiceContract]
public interface IProtoUserService
{
[OperationContract]
ValueTask<BaseResponse<string>> Create(UserCreateRequest userCreateRequest);
[OperationContract]
Task<BaseResponse<UserResponse?>> GetByIdAsync(string id);
[OperationContract]
Task<BaseResponse<List<UserResponse>?>> GetAsync();
}
[ProtoContract]
public class UserResponse
{
[ProtoMember(1)]
public string Id { get; set; } = null!;
[ProtoMember(2)]
public string? FirstName { get; set; }
[ProtoMember(3)]
public string? LastName { get; set; }
[ProtoMember(4)]
public string Email { get; set; } = null!;
}
[ProtoContract]
public class UserCreateRequest
{
[ProtoMember(1)]
public string? FirstName { get; set; }
[ProtoMember(2)]
public string? LastName { get; set; }
[ProtoMember(3)]
public string? Email { get; set; }
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using EonaCat.gRPC.Core.Entities;
using EonaCat.gRPC.Core.Interfaces.Repositories;
using EonaCat.gRPC.Repository.DatabaseContext;
using EonaCat.EFCore;
namespace EonaCat.gRPC.Repository.Base;
public class BaseRepository<T> : EFRepository<T>, IBaseRepository<T> where T : BaseEntity
{
private readonly AppDbContext _dbContext;
private readonly DbSet<T> _dbSet;
private readonly IQueryable<T?> _queryable;
public BaseRepository(AppDbContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
_queryable = _dbContext.QuerySet<T?>().Where(x => !x!.IsDeleted);
}
public async Task SaveChangesAsync(bool acceptAllChangesOnSuccess)
=> await _dbContext.SaveChangesAsync(acceptAllChangesOnSuccess);
public async Task SaveChangesAsync() => await _dbContext.SaveChangesAsync();
public void Save() => _dbContext.SaveChanges();
public async Task RollbackAsync() => await _dbContext.DisposeAsync();
public void Rollback() => _dbContext.Dispose();
}
@@ -0,0 +1,56 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using EonaCat.gRPC.Core.Entities;
namespace EonaCat.gRPC.Repository.DatabaseContext;
public class AppDbContext : DbContext
{
private readonly ILoggerFactory _loggerFactory = new LoggerFactory();
public AppDbContext(DbContextOptions<AppDbContext> context) : base(context)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_loggerFactory);
optionsBuilder.UseSqlServer().LogTo(Console.WriteLine).EnableDetailedErrors();
base.OnConfiguring(optionsBuilder);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken())
{
UpdateEntryLog();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
UpdateEntryLog();
return base.SaveChangesAsync(cancellationToken);
}
private void UpdateEntryLog()
{
foreach (var entry in ChangeTracker.Entries<BaseEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedAt = DateTime.UtcNow;
entry.Entity.UpdatedAt = DateTime.UtcNow;
break;
case EntityState.Modified:
entry.Entity.UpdatedAt = DateTime.UtcNow;
break;
case EntityState.Deleted:
entry.Entity.UpdatedAt = DateTime.UtcNow;
break;
}
}
}
public DbSet<UserEntity> Users { get; set; } = null!;
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.gRPC.Core\EonaCat.gRPC.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,60 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using EonaCat.gRPC.Repository.DatabaseContext;
#nullable disable
namespace Repository.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221204002240_initial")]
partial class initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Core.Entities.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,39 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Repository.Migrations
{
/// <inheritdoc />
public partial class initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
FirstName = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastName = table.Column<string>(type: "nvarchar(max)", nullable: true),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
@@ -0,0 +1,57 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using EonaCat.gRPC.Repository.DatabaseContext;
#nullable disable
namespace Repository.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Core.Entities.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using EonaCat.gRPC.Core.Entities;
using EonaCat.gRPC.Core.Interfaces.Repositories;
using EonaCat.gRPC.Repository.Base;
using EonaCat.gRPC.Repository.DatabaseContext;
namespace EonaCat.gRPC.Repository;
public class UserRepository : BaseRepository<UserEntity>, IUserRepository
{
public UserRepository(AppDbContext dbContext) : base(dbContext)
{
}
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.gRPC.Repository\EonaCat.gRPC.Repository.csproj" />
</ItemGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
using EonaCat.gRPC.Core.Interfaces.Services;
namespace EonaCat.gRPC.Service;
public class GreeterService : IGreeterService
{
}
+34
View File
@@ -0,0 +1,34 @@
using EonaCat.gRPC.Core.Entities;
using EonaCat.gRPC.Core.Interfaces.Repositories;
using EonaCat.gRPC.Core.Interfaces.Services;
namespace EonaCat.gRPC.Service;
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public async Task<long> CreateUser(UserEntity user)
{
await _userRepository.AddAsync(user);
await _userRepository.SaveChangesAsync();
return user.Id;
}
public async Task<IEnumerable<UserEntity>> GetAsync()
{
var users = await _userRepository.ListAsync();
return users;
}
public async Task<UserEntity> GetAsync(long id)
{
var user = await _userRepository.GetAsync(id);
return user;
}
}
+63
View File
@@ -0,0 +1,63 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33122.133
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.gRPC.Api", "EonaCat.gRPC.Api\EonaCat.gRPC.Api.csproj", "{F876AF99-132B-4FB2-A88D-522B4715A5AF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.gRPC.Core", "EonaCat.gRPC.Core\EonaCat.gRPC.Core.csproj", "{B4A39716-E91F-4019-AB6A-73C1A6F08B25}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.gRPC.Repository", "EonaCat.gRPC.Repository\EonaCat.gRPC.Repository.csproj", "{423DD4EA-786B-48EB-B9CC-6E218F034613}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.gRPC.Service", "EonaCat.gRPC.Service\EonaCat.gRPC.Service.csproj", "{AFA12B1D-5E87-42B5-9394-C64BB5ABDD39}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ClientApp", "ClientApp", "{BF2F41AC-8958-44F3-A35E-21504A1E33C5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.gRPC.Client", "EonaCat.gRPC.Client\EonaCat.gRPC.Client.csproj", "{7A9425D3-DF6F-4864-931B-92A10207B896}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{15CFC875-DB5E-4DF9-9BF7-0AD7709A5157}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.gRPC.Proto", "EonaCat.gRPC.Proto\EonaCat.gRPC.Proto.csproj", "{6D7BBC4C-9BE3-4200-9DDE-426175ADF996}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F876AF99-132B-4FB2-A88D-522B4715A5AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F876AF99-132B-4FB2-A88D-522B4715A5AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F876AF99-132B-4FB2-A88D-522B4715A5AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F876AF99-132B-4FB2-A88D-522B4715A5AF}.Release|Any CPU.Build.0 = Release|Any CPU
{B4A39716-E91F-4019-AB6A-73C1A6F08B25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B4A39716-E91F-4019-AB6A-73C1A6F08B25}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B4A39716-E91F-4019-AB6A-73C1A6F08B25}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B4A39716-E91F-4019-AB6A-73C1A6F08B25}.Release|Any CPU.Build.0 = Release|Any CPU
{423DD4EA-786B-48EB-B9CC-6E218F034613}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{423DD4EA-786B-48EB-B9CC-6E218F034613}.Debug|Any CPU.Build.0 = Debug|Any CPU
{423DD4EA-786B-48EB-B9CC-6E218F034613}.Release|Any CPU.ActiveCfg = Release|Any CPU
{423DD4EA-786B-48EB-B9CC-6E218F034613}.Release|Any CPU.Build.0 = Release|Any CPU
{AFA12B1D-5E87-42B5-9394-C64BB5ABDD39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AFA12B1D-5E87-42B5-9394-C64BB5ABDD39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFA12B1D-5E87-42B5-9394-C64BB5ABDD39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFA12B1D-5E87-42B5-9394-C64BB5ABDD39}.Release|Any CPU.Build.0 = Release|Any CPU
{7A9425D3-DF6F-4864-931B-92A10207B896}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A9425D3-DF6F-4864-931B-92A10207B896}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A9425D3-DF6F-4864-931B-92A10207B896}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A9425D3-DF6F-4864-931B-92A10207B896}.Release|Any CPU.Build.0 = Release|Any CPU
{6D7BBC4C-9BE3-4200-9DDE-426175ADF996}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6D7BBC4C-9BE3-4200-9DDE-426175ADF996}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6D7BBC4C-9BE3-4200-9DDE-426175ADF996}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6D7BBC4C-9BE3-4200-9DDE-426175ADF996}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{7A9425D3-DF6F-4864-931B-92A10207B896} = {BF2F41AC-8958-44F3-A35E-21504A1E33C5}
{6D7BBC4C-9BE3-4200-9DDE-426175ADF996} = {15CFC875-DB5E-4DF9-9BF7-0AD7709A5157}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F172D321-6172-486F-B708-51769775F2EC}
EndGlobalSection
EndGlobal
+172 -41
View File
@@ -1,73 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
1. Definitions.
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 EonaCat
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+356 -2
View File
@@ -1,3 +1,357 @@
# EonaCat.gRPC
# 🚀 EonaCat.gRPC
EonaCat.gRPC
A modern .NET 10 gRPC solution built with:
* ✅ Code-First gRPC using ProtoBuf.Grpc
* ✅ Dependency Injection
* ✅ JWT Authentication
* ✅ Entity Framework Core
* ✅ JSON Transcoding (REST ↔ gRPC)
* ✅ Swagger/OpenAPI Support
* ✅ Request/Response Interceptors
* ✅ Structured Logging with EonaCat.LogStack
* ✅ Clean Architecture Separation
---
# Features
* High-performance gRPC services
* HTTP/JSON endpoint support through gRPC transcoding
* JWT authentication and authorization
* Automatic Swagger documentation
* Request tracing and exception handling
* Repository pattern implementation
* Service layer abstraction
* Dependency Injection support throughout the application
---
# Project Structure
```text
EonaCat.gRPC.Api
├── EonaCat.gRPC.Api → ASP.NET Core gRPC Host
├── EonaCat.gRPC.Service → Business Logic
├── EonaCat.gRPC.Core → Domain Models & Interfaces
├── EonaCat.gRPC.Repository → Data Access Layer
├── EonaCat.gRPC.Proto → gRPC Contracts
└── EonaCat.gRPC.Client → Sample Client
```
---
# Requirements
* .NET 10 SDK
* SQL Server
* Visual Studio 2022+ or Rider
# Installation
Clone the repository:
```bash
git clone https://github.com/your-org/EonaCat.gRPC.git
cd EonaCat.gRPC
```
Restore packages:
```bash
dotnet restore
```
Build:
```bash
dotnet build
```
Run API:
```bash
dotnet run --project EonaCat.gRPC.Api
```
# Configuration
## appsettings.json
```json
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=GrpcDb;Trusted_Connection=True;"
},
"Jwt": {
"Secret": "your-super-secret-key"
}
}
```
# Dependency Injection
Services are registered automatically during startup.
```csharp
builder.Services.AddTransient<IUserService, UserService>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped(typeof(IBaseRepository<>),
typeof(BaseRepository<>));
```
# gRPC Service Registration
```csharp
builder.Services.AddGrpc(options =>
{
options.Interceptors.Add<LoggerInterceptor>();
options.Interceptors.Add<ExceptionInterceptor>();
});
builder.Services.AddCodeFirstGrpc();
builder.Services.AddGrpcReflection();
builder.Services.AddGrpcSwagger();
builder.Services.AddGrpc().AddJsonTranscoding();
```
# User Service Contract
```csharp
[ServiceContract]
public interface IProtoUserService
{
ValueTask<BaseResponse<string>> Create(
UserCreateRequest request);
Task<BaseResponse<UserResponse?>> GetByIdAsync(
string id);
Task<BaseResponse<List<UserResponse>?>> GetAsync();
}
```
# Creating a User
## Request
```csharp
var request = new UserCreateRequest
{
FirstName = "John",
LastName = "Doe",
Email = "john@example.com"
};
```
## Client Call
```csharp
var response = await client.Create(request);
Console.WriteLine(response.Data);
```
# Getting a User
```csharp
var response = await client.GetByIdAsync("1");
Console.WriteLine(response.Data?.FirstName);
```
# Getting All Users
```csharp
var users = await client.GetAsync();
foreach (var user in users.Data)
{
Console.WriteLine(user.Email);
}
```
# Client Example
```csharp
using Grpc.Net.Client;
using var channel =
GrpcChannel.ForAddress("http://localhost:5227");
var client =
channel.CreateGrpcService<IProtoUserService>();
var users = await client.GetAsync();
```
# JSON Transcoding
Because JSON Transcoding is enabled, services can be accessed through standard HTTP requests.
Example:
```http
GET /users
```
```http
GET /users/1
```
This allows browsers, Postman, mobile apps, and JavaScript applications to consume your gRPC services.
# Authentication
JWT Authentication is configured using:
```csharp
builder.Services
.AddAuthentication()
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuerSigningKey = true
};
});
```
Add your token:
```http
Authorization: Bearer YOUR_TOKEN
```
# Logging
EonaCat.LogStack is integrated throughout the solution.
```csharp
builder.AddEonaCatLogging();
```
Client logging:
```csharp
LoggerFactory.Create(builder =>
{
builder.AddEonaCatLogging();
builder.SetMinimumLevel(LogLevel.Debug);
});
```
# Interceptors
## Logging Interceptor
```csharp
options.Interceptors.Add<LoggerInterceptor>();
```
Provides:
* Request logging
* Response logging
* Execution timing
* Diagnostics
## Exception Interceptor
```csharp
options.Interceptors.Add<ExceptionInterceptor>();
```
Provides:
* Global exception handling
* Consistent error responses
* Centralized logging
# Swagger Support
Swagger UI is automatically enabled.
Navigate to:
```text
https://localhost:<port>/swagger
```
You can:
* Browse endpoints
* Test requests
* Inspect schemas
* View authentication requirements
# Reflection Support
Reflection is enabled for tools such as:
* grpcurl
* Postman
* BloomRPC
* Kreya
```csharp
app.MapGrpcReflectionService();
```
# Example grpcurl Commands
List services:
```bash
grpcurl localhost:5227 list
```
Describe service:
```bash
grpcurl localhost:5227 describe IProtoUserService
```
Call endpoint:
```bash
grpcurl \
-d '{"id":"1"}' \
localhost:5227 \
IProtoUserService/GetByIdAsync
```
---
# Architecture
```text
Client
gRPC API
Service Layer
Repository Layer
SQL Server
```
# Performance Benefits
Compared to traditional REST APIs:
* Smaller payloads
* Faster serialization
* HTTP/2 support
* Strongly typed contracts
* Better streaming capabilities
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB