diff --git a/.gitignore b/.gitignore index 7e2e97c..3739e17 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/EonaCat.gRPC.Api/Converters/TrimStringConverter.cs b/EonaCat.gRPC.Api/Converters/TrimStringConverter.cs new file mode 100644 index 0000000..38512ec --- /dev/null +++ b/EonaCat.gRPC.Api/Converters/TrimStringConverter.cs @@ -0,0 +1,12 @@ +using System.Text.Json; + +namespace EonaCat.gRPC.Api.Converters; + +public class TrimStringConverter : System.Text.Json.Serialization.JsonConverter +{ + 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); +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/EonaCat.gRPC.Api.csproj b/EonaCat.gRPC.Api/EonaCat.gRPC.Api.csproj new file mode 100644 index 0000000..acad56f --- /dev/null +++ b/EonaCat.gRPC.Api/EonaCat.gRPC.Api.csproj @@ -0,0 +1,30 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/EonaCat.gRPC.Api/GlobalUsings.cs b/EonaCat.gRPC.Api/GlobalUsings.cs new file mode 100644 index 0000000..2f00e1c --- /dev/null +++ b/EonaCat.gRPC.Api/GlobalUsings.cs @@ -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; \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/AppSettings.cs b/EonaCat.gRPC.Api/Helpers/AppSettings.cs new file mode 100644 index 0000000..d0cdd05 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/AppSettings.cs @@ -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!; +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/CustomException.cs b/EonaCat.gRPC.Api/Helpers/CustomException.cs new file mode 100644 index 0000000..8343687 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/CustomException.cs @@ -0,0 +1,10 @@ +namespace EonaCat.gRPC.Api.Helpers +{ + public class CustomException : Exception + { + public CustomException(string message) : base(message) + { + + } + } +} diff --git a/EonaCat.gRPC.Api/Helpers/CustomMapper.cs b/EonaCat.gRPC.Api/Helpers/CustomMapper.cs new file mode 100644 index 0000000..b2ac083 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/CustomMapper.cs @@ -0,0 +1,34 @@ +namespace EonaCat.gRPC.Api.Helpers; + +public static class CustomMapper +{ + /// + /// Proto to Entity/DTO And Reverse + /// + /// + /// + /// + /// TDestination + public static TDestination Map(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}"); + } + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/ExceptionHelpers.cs b/EonaCat.gRPC.Api/Helpers/ExceptionHelpers.cs new file mode 100644 index 0000000..52cbec2 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/ExceptionHelpers.cs @@ -0,0 +1,54 @@ +using ProtoBuf.Grpc; + +namespace EonaCat.gRPC.Api.Helpers; + +public static class ExceptionHelpers +{ + public static RpcException Handle(this Exception exception, ServerCallContext context, ILogger 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(TimeoutException exception, ServerCallContext context, ILogger 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(SqlException exception, ServerCallContext context, ILogger 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(RpcException exception, ILogger 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(Exception exception, ServerCallContext context, ILogger 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; + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/Extension.cs b/EonaCat.gRPC.Api/Helpers/Extension.cs new file mode 100644 index 0000000..11d9975 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/Extension.cs @@ -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(builder.Configuration.GetSection("Jwt")); + builder.Services.AddTransient(); + } + + private static void RegisterRepositoryDependencies(IServiceCollection services) + { + services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>)); + services.AddScoped(); + } + + 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((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(); + app.MapGrpcService(); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/JwtAuthenticationManager.cs b/EonaCat.gRPC.Api/Helpers/JwtAuthenticationManager.cs new file mode 100644 index 0000000..48f16b5 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/JwtAuthenticationManager.cs @@ -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, 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 + { + 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 + }; + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Helpers/TimeStampContractResolver.cs b/EonaCat.gRPC.Api/Helpers/TimeStampContractResolver.cs new file mode 100644 index 0000000..0ec2100 --- /dev/null +++ b/EonaCat.gRPC.Api/Helpers/TimeStampContractResolver.cs @@ -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()); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Middleware/Interceptors/ExceptionInterceptor.cs b/EonaCat.gRPC.Api/Middleware/Interceptors/ExceptionInterceptor.cs new file mode 100644 index 0000000..da7188c --- /dev/null +++ b/EonaCat.gRPC.Api/Middleware/Interceptors/ExceptionInterceptor.cs @@ -0,0 +1,78 @@ +using EonaCat.gRPC.Api.Helpers; + +namespace EonaCat.gRPC.Api.Middleware.Interceptors; + +public class ExceptionInterceptor : Interceptor +{ + private readonly ILogger _logger; + private readonly Guid _correlationId; + + public ExceptionInterceptor(ILogger logger) + { + _logger = logger; + _correlationId = Guid.NewGuid(); + } + + public override async Task UnaryServerHandler( + TRequest request, + ServerCallContext context, + UnaryServerMethod continuation) + { + try + { + return await continuation(request, context); + } + catch (Exception e) + { + throw e.Handle(context, _logger, _correlationId); + } + } + + public override async Task ClientStreamingServerHandler( + IAsyncStreamReader requestStream, + ServerCallContext context, + ClientStreamingServerMethod continuation) + { + try + { + return await continuation(requestStream, context); + } + catch (Exception e) + { + throw e.Handle(context, _logger, _correlationId); + } + } + + + public override async Task ServerStreamingServerHandler( + TRequest request, + IServerStreamWriter responseStream, + ServerCallContext context, + ServerStreamingServerMethod continuation) + { + try + { + await continuation(request, responseStream, context); + } + catch (Exception e) + { + throw e.Handle(context, _logger, _correlationId); + } + } + + public override async Task DuplexStreamingServerHandler( + IAsyncStreamReader requestStream, + IServerStreamWriter responseStream, + ServerCallContext context, + DuplexStreamingServerMethod continuation) + { + try + { + await continuation(requestStream, responseStream, context); + } + catch (Exception e) + { + throw e.Handle(context, _logger, _correlationId); + } + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Middleware/Interceptors/LoggerInterceptor.cs b/EonaCat.gRPC.Api/Middleware/Interceptors/LoggerInterceptor.cs new file mode 100644 index 0000000..d591316 --- /dev/null +++ b/EonaCat.gRPC.Api/Middleware/Interceptors/LoggerInterceptor.cs @@ -0,0 +1,49 @@ +namespace EonaCat.gRPC.Api.Middleware.Interceptors; + +public class LoggerInterceptor : Interceptor +{ + private readonly ILogger _logger; + + public LoggerInterceptor(ILogger logger) + { + _logger = logger; + } + + + public override async Task UnaryServerHandler( + TRequest request, + ServerCallContext context, + UnaryServerMethod 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}"); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Program.cs b/EonaCat.gRPC.Api/Program.cs new file mode 100644 index 0000000..f5e95d5 --- /dev/null +++ b/EonaCat.gRPC.Api/Program.cs @@ -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(); + options.Interceptors.Add(); +}); +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(); diff --git a/EonaCat.gRPC.Api/Properties/launchSettings.json b/EonaCat.gRPC.Api/Properties/launchSettings.json new file mode 100644 index 0000000..de85ec0 --- /dev/null +++ b/EonaCat.gRPC.Api/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/EonaCat.gRPC.Api/Services/AuthenticationHandler.cs b/EonaCat.gRPC.Api/Services/AuthenticationHandler.cs new file mode 100644 index 0000000..f73ade1 --- /dev/null +++ b/EonaCat.gRPC.Api/Services/AuthenticationHandler.cs @@ -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; + + public AuthenticationHandler(IOptions appSettings) + { + _appSettings = appSettings; + } + + public Task 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); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/Services/UserHandler.cs b/EonaCat.gRPC.Api/Services/UserHandler.cs new file mode 100644 index 0000000..533b35d --- /dev/null +++ b/EonaCat.gRPC.Api/Services/UserHandler.cs @@ -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> Create(UserCreateRequest userCreateRequest) + { + var user = CustomMapper.Map(userCreateRequest); + var response = await _userService.CreateUser(user); + return BaseResponse.Created(response.ToString()); + } + + public async Task?>> GetAsync() + { + var users = await _userService.GetAsync(); + var mapped = CustomMapper.Map, List>(users.ToList()); + return BaseResponse?>.Ok(mapped); + } + + public async Task> GetByIdAsync(string id) + { + if (string.IsNullOrEmpty(id) || !long.TryParse(id, out _)) + return BaseResponse.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(user); + return BaseResponse.Ok(mapped); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Api/appsettings.Development.json b/EonaCat.gRPC.Api/appsettings.Development.json new file mode 100644 index 0000000..75dd8cf --- /dev/null +++ b/EonaCat.gRPC.Api/appsettings.Development.json @@ -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" + } +} diff --git a/EonaCat.gRPC.Api/appsettings.json b/EonaCat.gRPC.Api/appsettings.json new file mode 100644 index 0000000..e0ab993 --- /dev/null +++ b/EonaCat.gRPC.Api/appsettings.json @@ -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" + } + } +} diff --git a/EonaCat.gRPC.Client/AppTokenProvider.cs b/EonaCat.gRPC.Client/AppTokenProvider.cs new file mode 100644 index 0000000..9ef84b1 --- /dev/null +++ b/EonaCat.gRPC.Client/AppTokenProvider.cs @@ -0,0 +1,19 @@ +using EonaCat.gRPC.Proto; + +namespace EonaCat.gRPC.Client; + +public interface ITokenProvider +{ + Task GetTokenAsync(); +} + +public class AppTokenProvider : ITokenProvider +{ + private AuthenticationResponse _token; + public async Task GetTokenAsync() + { + if (_token == null) + _token = new AuthenticationResponse { AccessToken = "test", ExpiresIn = 300 }; + return _token; + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/AuthService.cs b/EonaCat.gRPC.Client/AuthService.cs new file mode 100644 index 0000000..807910b --- /dev/null +++ b/EonaCat.gRPC.Client/AuthService.cs @@ -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(); + var authenticationResponse = await authenticationClient.Authenticate(new AuthenticationRequest + { + UserName = "admin", + Password = "admin" + }); + Console.WriteLine($"Received Authentication Response - \nToken: {authenticationResponse.AccessToken}\nExpires In: {authenticationResponse.ExpiresIn}"); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/EonaCat.gRPC.Client.csproj b/EonaCat.gRPC.Client/EonaCat.gRPC.Client.csproj new file mode 100644 index 0000000..d44a030 --- /dev/null +++ b/EonaCat.gRPC.Client/EonaCat.gRPC.Client.csproj @@ -0,0 +1,37 @@ + + + + Exe + net10.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EonaCat.gRPC.Client/Extension.cs b/EonaCat.gRPC.Client/Extension.cs new file mode 100644 index 0000000..1b937da --- /dev/null +++ b/EonaCat.gRPC.Client/Extension.cs @@ -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(); + 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(); + 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(); + var userResponse = await userClient.GetByIdAsync(userId); + ConsoleExtensions.PrintResponse(userResponse); + } + + private static async Task UserListAsync(CallInvoker callInvoker) + { + var userClient = callInvoker.CreateGrpcService(); + var userResponse = await userClient.GetAsync(); + ConsoleExtensions.PrintResponse(userResponse); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/Helpers/AuthHeaderInterceptor.cs b/EonaCat.gRPC.Client/Helpers/AuthHeaderInterceptor.cs new file mode 100644 index 0000000..3fb0db0 --- /dev/null +++ b/EonaCat.gRPC.Client/Helpers/AuthHeaderInterceptor.cs @@ -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 AsyncUnaryCall(TRequest request, ClientInterceptorContext context, + AsyncUnaryCallContinuation 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(context.Method, context.Host, callOptions); + + return base.AsyncUnaryCall(request, context, continuation); + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/Helpers/ConsoleExtensions.cs b/EonaCat.gRPC.Client/Helpers/ConsoleExtensions.cs new file mode 100644 index 0000000..67ee7bf --- /dev/null +++ b/EonaCat.gRPC.Client/Helpers/ConsoleExtensions.cs @@ -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(BaseResponse 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. + } + + } +} diff --git a/EonaCat.gRPC.Client/Helpers/TracerInterceptor.cs b/EonaCat.gRPC.Client/Helpers/TracerInterceptor.cs new file mode 100644 index 0000000..885b3c4 --- /dev/null +++ b/EonaCat.gRPC.Client/Helpers/TracerInterceptor.cs @@ -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 _logger; + + public TracerInterceptor(ILoggerFactory logger) + { + _logger = logger.CreateLogger(); + } + + public override AsyncClientStreamingCall AsyncClientStreamingCall( + ClientInterceptorContext context, + AsyncClientStreamingCallContinuation 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 AsyncDuplexStreamingCall( + ClientInterceptorContext context, + AsyncDuplexStreamingCallContinuation 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 AsyncServerStreamingCall( + TRequest request, + ClientInterceptorContext context, + AsyncServerStreamingCallContinuation 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 AsyncUnaryCall( + TRequest request, + ClientInterceptorContext context, + AsyncUnaryCallContinuation 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; + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/Program.cs b/EonaCat.gRPC.Client/Program.cs new file mode 100644 index 0000000..0a8dc62 --- /dev/null +++ b/EonaCat.gRPC.Client/Program.cs @@ -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(); diff --git a/EonaCat.gRPC.Client/Protos/base.proto b/EonaCat.gRPC.Client/Protos/base.proto new file mode 100644 index 0000000..5e670af --- /dev/null +++ b/EonaCat.gRPC.Client/Protos/base.proto @@ -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; +} \ No newline at end of file diff --git a/EonaCat.gRPC.Client/Protos/user.proto b/EonaCat.gRPC.Client/Protos/user.proto new file mode 100644 index 0000000..0648324 --- /dev/null +++ b/EonaCat.gRPC.Client/Protos/user.proto @@ -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; +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Dtos/BaseResponseDto.cs b/EonaCat.gRPC.Core/Dtos/BaseResponseDto.cs new file mode 100644 index 0000000..e9700b6 --- /dev/null +++ b/EonaCat.gRPC.Core/Dtos/BaseResponseDto.cs @@ -0,0 +1,8 @@ +namespace EonaCat.gRPC.Core.Dtos; + +public class BaseResponseDto +{ + public bool IsSuccess { get; set; } + public string? Message { get; set; } + public T? Data { get; set; } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Entities/BaseEntity.cs b/EonaCat.gRPC.Core/Entities/BaseEntity.cs new file mode 100644 index 0000000..4a8b1bb --- /dev/null +++ b/EonaCat.gRPC.Core/Entities/BaseEntity.cs @@ -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; } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Entities/UserEntity.cs b/EonaCat.gRPC.Core/Entities/UserEntity.cs new file mode 100644 index 0000000..ea3d74b --- /dev/null +++ b/EonaCat.gRPC.Core/Entities/UserEntity.cs @@ -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!; +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Enums/AppEnums.cs b/EonaCat.gRPC.Core/Enums/AppEnums.cs new file mode 100644 index 0000000..9ec2abe --- /dev/null +++ b/EonaCat.gRPC.Core/Enums/AppEnums.cs @@ -0,0 +1,11 @@ +namespace EonaCat.gRPC.Core.Enums; + +public class AppEnums +{ + public enum Gender + { + Male = 0, + Female = 1, + Other = 2 + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/EonaCat.gRPC.Core.csproj b/EonaCat.gRPC.Core/EonaCat.gRPC.Core.csproj new file mode 100644 index 0000000..6036807 --- /dev/null +++ b/EonaCat.gRPC.Core/EonaCat.gRPC.Core.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + + + + + + diff --git a/EonaCat.gRPC.Core/Interfaces/Repositories/IBaseRepository.cs b/EonaCat.gRPC.Core/Interfaces/Repositories/IBaseRepository.cs new file mode 100644 index 0000000..f2eb3ca --- /dev/null +++ b/EonaCat.gRPC.Core/Interfaces/Repositories/IBaseRepository.cs @@ -0,0 +1,15 @@ +using EonaCat.gRPC.Core.Entities; +using EonaCat.Repositories; + +namespace EonaCat.gRPC.Core.Interfaces.Repositories; + +public interface IBaseRepository : IRepository where T : BaseEntity +{ + /// + /// Indicates whether is called after + /// the changes have been sent successfully to the database. + /// + Task SaveChangesAsync(bool acceptAllChangesOnSuccess); + Task SaveChangesAsync(); + void Save(); +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Interfaces/Repositories/IUserRepository.cs b/EonaCat.gRPC.Core/Interfaces/Repositories/IUserRepository.cs new file mode 100644 index 0000000..535a34c --- /dev/null +++ b/EonaCat.gRPC.Core/Interfaces/Repositories/IUserRepository.cs @@ -0,0 +1,7 @@ +using EonaCat.gRPC.Core.Entities; + +namespace EonaCat.gRPC.Core.Interfaces.Repositories; + +public interface IUserRepository : IBaseRepository +{ +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Interfaces/Services/IGreeterService.cs b/EonaCat.gRPC.Core/Interfaces/Services/IGreeterService.cs new file mode 100644 index 0000000..ad689f1 --- /dev/null +++ b/EonaCat.gRPC.Core/Interfaces/Services/IGreeterService.cs @@ -0,0 +1,5 @@ +namespace EonaCat.gRPC.Core.Interfaces.Services; + +public interface IGreeterService +{ +} \ No newline at end of file diff --git a/EonaCat.gRPC.Core/Interfaces/Services/IUserService.cs b/EonaCat.gRPC.Core/Interfaces/Services/IUserService.cs new file mode 100644 index 0000000..d9c4bc1 --- /dev/null +++ b/EonaCat.gRPC.Core/Interfaces/Services/IUserService.cs @@ -0,0 +1,10 @@ +using EonaCat.gRPC.Core.Entities; + +namespace EonaCat.gRPC.Core.Interfaces.Services; + +public interface IUserService +{ + Task CreateUser(UserEntity user); + Task> GetAsync(); + Task GetAsync(long id); +} \ No newline at end of file diff --git a/EonaCat.gRPC.Proto/Authentication.cs b/EonaCat.gRPC.Proto/Authentication.cs new file mode 100644 index 0000000..bd2a804 --- /dev/null +++ b/EonaCat.gRPC.Proto/Authentication.cs @@ -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 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; } + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Proto/BaseResponse.cs b/EonaCat.gRPC.Proto/BaseResponse.cs new file mode 100644 index 0000000..75db21c --- /dev/null +++ b/EonaCat.gRPC.Proto/BaseResponse.cs @@ -0,0 +1,126 @@ +using ProtoBuf; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace EonaCat.gRPC.Proto; + +[ProtoContract] +public class BaseResponse +{ + [ProtoMember(1)] + public bool IsSuccess { get; set; } + [ProtoMember(2)] + public string? Message { get; set; } + [ProtoMember(3)] + public T? Data { get; set; } + + + public static BaseResponse Ok(T? data, string? message = null) + { + return new BaseResponse + { + IsSuccess = true, + Message = message, + Data = data + }; + } + + public static BaseResponse Created(T? data, string? message = null) + { + return new BaseResponse + { + IsSuccess = true, + Message = string.IsNullOrEmpty(message) + ? ConstructMessage(GetCallingClassName()) + : message, + Data = data + }; + } + + public static BaseResponse Updated(T? data, string? message = null) + { + return new BaseResponse + { + IsSuccess = true, + Message = string.IsNullOrEmpty(message) + ? ConstructMessage(GetCallingClassName()) + : message, + Data = data + }; + } + + public static BaseResponse Deleted(T? data, string? message = null) + { + return new BaseResponse + { + IsSuccess = true, + Message = string.IsNullOrEmpty(message) + ? ConstructMessage(GetCallingClassName()) + : message, + Data = data + }; + } + + public static BaseResponse Failed(T? data, string? message = null, [CallerMemberName] string actionName = "") + { + return new BaseResponse + { + 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 +} \ No newline at end of file diff --git a/EonaCat.gRPC.Proto/EonaCat.gRPC.Proto.csproj b/EonaCat.gRPC.Proto/EonaCat.gRPC.Proto.csproj new file mode 100644 index 0000000..41340c3 --- /dev/null +++ b/EonaCat.gRPC.Proto/EonaCat.gRPC.Proto.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + diff --git a/EonaCat.gRPC.Proto/Helpers/Utility.cs b/EonaCat.gRPC.Proto/Helpers/Utility.cs new file mode 100644 index 0000000..6b1e639 --- /dev/null +++ b/EonaCat.gRPC.Proto/Helpers/Utility.cs @@ -0,0 +1,44 @@ +using ProtoBuf; + +namespace EonaCat.gRPC.Proto.Helpers; + +public static class Utility +{ + public static byte[] ProtoSerialize(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(byte[] data) where T : class + { + if (null == data) return null; + + try + { + using (var stream = new MemoryStream(data)) + { + return Serializer.Deserialize(stream); + } + } + catch + { + // Log error + throw; + } + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Proto/User.cs b/EonaCat.gRPC.Proto/User.cs new file mode 100644 index 0000000..57a8daa --- /dev/null +++ b/EonaCat.gRPC.Proto/User.cs @@ -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> Create(UserCreateRequest userCreateRequest); + + [OperationContract] + Task> GetByIdAsync(string id); + + [OperationContract] + Task?>> 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; } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Repository/Base/BaseRepository.cs b/EonaCat.gRPC.Repository/Base/BaseRepository.cs new file mode 100644 index 0000000..5795d66 --- /dev/null +++ b/EonaCat.gRPC.Repository/Base/BaseRepository.cs @@ -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 : EFRepository, IBaseRepository where T : BaseEntity +{ + private readonly AppDbContext _dbContext; + private readonly DbSet _dbSet; + private readonly IQueryable _queryable; + + public BaseRepository(AppDbContext dbContext) : base(dbContext) + { + _dbContext = dbContext; + _dbSet = _dbContext.Set(); + _queryable = _dbContext.QuerySet().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(); +} \ No newline at end of file diff --git a/EonaCat.gRPC.Repository/DatabaseContext/AppDbContext.cs b/EonaCat.gRPC.Repository/DatabaseContext/AppDbContext.cs new file mode 100644 index 0000000..37bda03 --- /dev/null +++ b/EonaCat.gRPC.Repository/DatabaseContext/AppDbContext.cs @@ -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 context) : base(context) + { + + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseLoggerFactory(_loggerFactory); + optionsBuilder.UseSqlServer().LogTo(Console.WriteLine).EnableDetailedErrors(); + base.OnConfiguring(optionsBuilder); + } + + public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) + { + UpdateEntryLog(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) + { + UpdateEntryLog(); + return base.SaveChangesAsync(cancellationToken); + } + + private void UpdateEntryLog() + { + foreach (var entry in ChangeTracker.Entries()) + { + 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 Users { get; set; } = null!; +} \ No newline at end of file diff --git a/EonaCat.gRPC.Repository/EonaCat.gRPC.Repository.csproj b/EonaCat.gRPC.Repository/EonaCat.gRPC.Repository.csproj new file mode 100644 index 0000000..61e04dd --- /dev/null +++ b/EonaCat.gRPC.Repository/EonaCat.gRPC.Repository.csproj @@ -0,0 +1,21 @@ + + + + net10.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.Designer.cs b/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.Designer.cs new file mode 100644 index 0000000..8647858 --- /dev/null +++ b/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.Designer.cs @@ -0,0 +1,60 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("FirstName") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.cs b/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.cs new file mode 100644 index 0000000..17af2bf --- /dev/null +++ b/EonaCat.gRPC.Repository/Migrations/20221204002240_initial.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Repository.Migrations +{ + /// + public partial class initial : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + FirstName = table.Column(type: "nvarchar(max)", nullable: true), + LastName = table.Column(type: "nvarchar(max)", nullable: true), + Email = table.Column(type: "nvarchar(max)", nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreatedAt = table.Column(type: "datetime2", nullable: false), + UpdatedAt = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/EonaCat.gRPC.Repository/Migrations/AppDbContextModelSnapshot.cs b/EonaCat.gRPC.Repository/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000..34d6d7d --- /dev/null +++ b/EonaCat.gRPC.Repository/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,57 @@ +// +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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("FirstName") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/EonaCat.gRPC.Repository/UserRepository.cs b/EonaCat.gRPC.Repository/UserRepository.cs new file mode 100644 index 0000000..99cabb1 --- /dev/null +++ b/EonaCat.gRPC.Repository/UserRepository.cs @@ -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, IUserRepository +{ + public UserRepository(AppDbContext dbContext) : base(dbContext) + { + + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.Service/EonaCat.gRPC.Service.csproj b/EonaCat.gRPC.Service/EonaCat.gRPC.Service.csproj new file mode 100644 index 0000000..83045a0 --- /dev/null +++ b/EonaCat.gRPC.Service/EonaCat.gRPC.Service.csproj @@ -0,0 +1,13 @@ + + + + net10.0 + enable + enable + + + + + + + diff --git a/EonaCat.gRPC.Service/GreeterService.cs b/EonaCat.gRPC.Service/GreeterService.cs new file mode 100644 index 0000000..73918bd --- /dev/null +++ b/EonaCat.gRPC.Service/GreeterService.cs @@ -0,0 +1,8 @@ +using EonaCat.gRPC.Core.Interfaces.Services; + +namespace EonaCat.gRPC.Service; + +public class GreeterService : IGreeterService +{ + +} \ No newline at end of file diff --git a/EonaCat.gRPC.Service/UserService.cs b/EonaCat.gRPC.Service/UserService.cs new file mode 100644 index 0000000..aa23f3a --- /dev/null +++ b/EonaCat.gRPC.Service/UserService.cs @@ -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 CreateUser(UserEntity user) + { + await _userRepository.AddAsync(user); + await _userRepository.SaveChangesAsync(); + return user.Id; + } + + public async Task> GetAsync() + { + var users = await _userRepository.ListAsync(); + return users; + } + + public async Task GetAsync(long id) + { + var user = await _userRepository.GetAsync(id); + return user; + } +} \ No newline at end of file diff --git a/EonaCat.gRPC.sln b/EonaCat.gRPC.sln new file mode 100644 index 0000000..459c0a6 --- /dev/null +++ b/EonaCat.gRPC.sln @@ -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 diff --git a/LICENSE b/LICENSE index 494f695..ab37379 100644 --- a/LICENSE +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md index 1e2a510..c5a288b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,357 @@ -# EonaCat.gRPC +# 🚀 EonaCat.gRPC -EonaCat.gRPC \ No newline at end of file +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(); + +builder.Services.AddScoped(); + +builder.Services.AddScoped(typeof(IBaseRepository<>), + typeof(BaseRepository<>)); +``` + +# gRPC Service Registration + +```csharp +builder.Services.AddGrpc(options => +{ + options.Interceptors.Add(); + options.Interceptors.Add(); +}); + +builder.Services.AddCodeFirstGrpc(); +builder.Services.AddGrpcReflection(); +builder.Services.AddGrpcSwagger(); +builder.Services.AddGrpc().AddJsonTranscoding(); +``` + +# User Service Contract + +```csharp +[ServiceContract] +public interface IProtoUserService +{ + ValueTask> Create( + UserCreateRequest request); + + Task> GetByIdAsync( + string id); + + Task?>> 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(); + +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(); +``` + +Provides: + +* Request logging +* Response logging +* Execution timing +* Diagnostics + +## Exception Interceptor + +```csharp +options.Interceptors.Add(); +``` + +Provides: + +* Global exception handling +* Consistent error responses +* Centralized logging + +# Swagger Support + +Swagger UI is automatically enabled. + +Navigate to: + +```text +https://localhost:/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 \ No newline at end of file diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..0595b89 Binary files /dev/null and b/icon.png differ