Skip to content

Commit

Permalink
logging
Browse files Browse the repository at this point in the history
  • Loading branch information
KSemenenko committed Jun 6, 2023
1 parent 5332fb3 commit 47a9c46
Show file tree
Hide file tree
Showing 17 changed files with 92 additions and 109 deletions.
16 changes: 12 additions & 4 deletions ManagedCode.Communication.Extensions/CommunicationHubFilter.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
using System;
using System.Net;
using System.Threading.Tasks;
using ManagedCode.Communication.Extensions.Extensions;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ManagedCode.Communication.Extensions;

public class CommunicationHubFilter : IHubFilter
{
private readonly ILogger<CommunicationHubFilter> _logger;
private readonly IOptions<CommunicationOptions> _options;

public CommunicationHubFilter(ILogger<CommunicationHubFilter> logger)
public CommunicationHubFilter(ILogger<CommunicationHubFilter> logger, IOptions<CommunicationOptions> options)
{
_logger = logger;
_options = options;
}

public async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
public async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext,
Func<HubInvocationContext, ValueTask<object?>> next)
{
try
{
Expand All @@ -24,8 +29,11 @@ public CommunicationHubFilter(ILogger<CommunicationHubFilter> logger)
catch (Exception ex)
{
_logger.LogError(ex, invocationContext.Hub.GetType().Name + "." + invocationContext.HubMethodName);
var result = Result.Fail(HttpStatusCode.InternalServerError, ex.Message);
return result;

if (_options.Value.ShowErrorDetails)
return Result.Fail(HttpStatusCode.InternalServerError, ex.Message);

return Result.Fail(HttpStatusCode.InternalServerError, nameof(HttpStatusCode.InternalServerError));
}
}
}
64 changes: 16 additions & 48 deletions ManagedCode.Communication.Extensions/CommunicationMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
using ManagedCode.Communication.Extensions.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ManagedCode.Communication.Extensions;

public class CommunicationMiddleware
{
private readonly ILogger<CommunicationMiddleware> _logger;
private readonly RequestDelegate _next;
private readonly IOptions<CommunicationOptions> _options;

public CommunicationMiddleware(ILogger<CommunicationMiddleware> logger, RequestDelegate next)
public CommunicationMiddleware(ILogger<CommunicationMiddleware> logger, RequestDelegate next,
IOptions<CommunicationOptions> options)
{
_logger = logger;
_next = next;
_options = options;
}

public async Task Invoke(HttpContext httpContext)
Expand All @@ -32,55 +31,24 @@ public async Task Invoke(HttpContext httpContext)
catch (Exception ex)
{
_logger.LogError(ex, httpContext.Request.Method + "::" + httpContext.Request.Path);

if (httpContext.Response.HasStarted)
throw;
throw;

httpContext.Response.Headers.CacheControl = "no-cache,no-store";
httpContext.Response.Headers.Pragma = "no-cache";
httpContext.Response.Headers.Expires = "-1";
httpContext.Response.Headers.ETag = default;

httpContext.Response.ContentType = "application/json; charset=utf-8";
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

var result = Result.Fail(HttpStatusCode.InternalServerError, ex.Message);
await httpContext.Response.WriteAsJsonAsync(result);
}

/*catch (Exception ex) when (ex is InvalidDataException ||
ex is InvalidDataContractException)
{
_logger.LogError("Request throw an error", ex);
httpContext.Response.ContentType = "application/json; charset=utf-8";
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = Result.Fail(HttpStatusCode.InternalServerError, ex);
var json = JsonSerializer.Serialize(result);
await httpContext.Response.WriteAsJsonAsync(json);
}
catch (Exception ex) when (ex is ValidationException)
{
_logger.LogError("Request throw an error", ex);
//httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = Result.Fail(HttpStatusCode.InternalServerError, ex.Message);
var json = JsonSerializer.Serialize(result);
//await httpContext.Response.WriteAsJsonAsync(json);

var response = httpContext.Response;
response.ContentType = "application/json";
// get the response code and message
response.StatusCode = (int)HttpStatusCode.InternalServerError;
await response.WriteAsync(json);
if (_options.Value.ShowErrorDetails)
await httpContext.Response.WriteAsJsonAsync(Result.Fail(HttpStatusCode.InternalServerError,
ex.Message));
else
await httpContext.Response.WriteAsJsonAsync(Result.Fail(HttpStatusCode.InternalServerError,
nameof(HttpStatusCode.InternalServerError)));
}
catch (Exception ex)
{
_logger.LogError("Request throw an error", ex);
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = Result.Fail(HttpStatusCode.InternalServerError, ex.Message);
var json = JsonSerializer.Serialize(result);
await httpContext.Response.WriteAsJsonAsync(json);
}*/
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ManagedCode.Communication.Extensions;
namespace ManagedCode.Communication.Extensions.Extensions;

public static class CommunicationAppBuilderExtensions
{
public static IApplicationBuilder UseCommunication(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}


return app.UseMiddleware<CommunicationMiddleware>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace ManagedCode.Communication.Extensions.Extensions;

public class CommunicationOptions
{
public bool ShowErrorDetails { get; set; } = false;
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ManagedCode.Communication.Extensions;
namespace ManagedCode.Communication.Extensions.Extensions;

public static class ControllerExtensions
{
public static IActionResult ToActionResult<T>(this Result<T> result)
{
return result.IsSuccess ? new OkObjectResult(result.Value) : new BadRequestObjectResult(result.GetError()?.Message);
return result.IsSuccess
? new OkObjectResult(result.Value)
: new BadRequestObjectResult(result.GetError()?.Message);
}

public static Microsoft.AspNetCore.Http.IResult ToHttpResult<T>(this Result<T> result)
{
return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(result.GetError()?.Message);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.SignalR;

namespace ManagedCode.Communication.Extensions;
namespace ManagedCode.Communication.Extensions.Extensions;

public static class HubOptionsExtensions
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using Microsoft.Extensions.DependencyInjection;

namespace ManagedCode.Communication.Extensions.Extensions;

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCommunication(this IServiceCollection services,
Action<CommunicationOptions> options)
{
services.AddOptions<CommunicationOptions>().Configure(options);
return services;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
<Description>Communication for .NET</Description>
<PackageTags>managedcode, Communication, Result</PackageTags>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\ManagedCode.Communication\ManagedCode.Communication.csproj" />
<ProjectReference Include="..\ManagedCode.Communication\ManagedCode.Communication.csproj"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@
namespace ManagedCode.Communication.Converters;

[RegisterConverter]
public sealed class CollectionResultTSurrogateConverter<T> : IConverter<CollectionResult<T>, CollectionResultTSurrogate<T>>
public sealed class
CollectionResultTSurrogateConverter<T> : IConverter<CollectionResult<T>, CollectionResultTSurrogate<T>>
{
public CollectionResult<T> ConvertFromSurrogate(in CollectionResultTSurrogate<T> surrogate)
{
return new CollectionResult<T>(surrogate.IsSuccess, surrogate.Collection, surrogate.PageNumber, surrogate.PageSize, surrogate.TotalItems, surrogate.Errors,
surrogate.InvalidObject);
return new CollectionResult<T>(surrogate.IsSuccess, surrogate.Collection, surrogate.PageNumber,
surrogate.PageSize, surrogate.TotalItems, surrogate.Errors, surrogate.InvalidObject);
}

public CollectionResultTSurrogate<T> ConvertToSurrogate(in CollectionResult<T> value)
{
return new CollectionResultTSurrogate<T>(value.IsSuccess, value.Collection, value.PageNumber, value.PageSize, value.TotalItems, value.Errors,
value.InvalidObject);
return new CollectionResultTSurrogate<T>(value.IsSuccess, value.Collection, value.PageNumber, value.PageSize,
value.TotalItems, value.Errors, value.InvalidObject);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using ManagedCode.Communication.Filters;
using Orleans.Hosting;

Expand All @@ -10,6 +9,7 @@ public static ISiloBuilder UseOrleansCommunication(this ISiloBuilder builder)
{
return builder.AddIncomingGrainCallFilter<CommunicationIncomingGrainCallFilter>();
}

public static IClientBuilder UseOrleansCommunication(this IClientBuilder builder)
{
return builder.AddOutgoingGrainCallFilter<CommunicationOutgoingGrainCallFilter>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Orleans;
Expand All @@ -19,20 +18,16 @@ public async Task Invoke(IIncomingGrainCallContext context)
{
Type type;
if (context.InterfaceMethod.ReturnType.IsAssignableFrom(typeof(IResult)))
{
type = typeof(Result);
}
else
{
type = context.InterfaceMethod.ReturnType.IsGenericType
type = context.InterfaceMethod.ReturnType.IsGenericType
? context.InterfaceMethod.ReturnType.GetGenericArguments()[0]
: context.InterfaceMethod.ReturnType;
}

var resultType = Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance,
null, new object[] { exception }, CultureInfo.CurrentCulture);

var resultType = Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[] { exception }, CultureInfo.CurrentCulture);

context.Result = resultType;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,16 @@ public async Task Invoke(IOutgoingGrainCallContext context)
{
Type type;
if (context.InterfaceMethod.ReturnType.IsAssignableFrom(typeof(IResult)))
{
type = typeof(Result);
}
else
{
type = context.InterfaceMethod.ReturnType.IsGenericType
type = context.InterfaceMethod.ReturnType.IsGenericType
? context.InterfaceMethod.ReturnType.GetGenericArguments()[0]
: context.InterfaceMethod.ReturnType;
}

var resultType = Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance,
null, new object[] { exception }, CultureInfo.CurrentCulture);

var resultType = Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[] { exception }, CultureInfo.CurrentCulture);

context.Result = resultType;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.1.0" />
<PackageReference Include="Microsoft.Orleans.Runtime" Version="7.1.0" />
<PackageReference Include="Microsoft.Orleans.Serialization.Abstractions" Version="7.1.0" />
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.1.0"/>
<PackageReference Include="Microsoft.Orleans.Runtime" Version="7.1.0"/>
<PackageReference Include="Microsoft.Orleans.Serialization.Abstractions" Version="7.1.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ManagedCode.Communication\ManagedCode.Communication.csproj" />
<ProjectReference Include="..\ManagedCode.Communication\ManagedCode.Communication.csproj"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ namespace ManagedCode.Communication.Surrogates;
[GenerateSerializer]
public struct CollectionResultTSurrogate<T>
{
public CollectionResultTSurrogate(bool isSuccess, T[]? collection, int pageNumber, int pageSize, int totalItems, Error[]? errors,
Dictionary<string, string>? invalidObject)
public CollectionResultTSurrogate(bool isSuccess, T[]? collection, int pageNumber, int pageSize, int totalItems,
Error[]? errors, Dictionary<string, string>? invalidObject)
{
IsSuccess = isSuccess;
Collection = collection ?? Array.Empty<T>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using Orleans;

namespace ManagedCode.Communication.Surrogates;
Expand All @@ -7,13 +6,10 @@ namespace ManagedCode.Communication.Surrogates;
[GenerateSerializer]
public struct CommandSurrogate
{
[Id(0)]
public string? Id;
[Id(0)] public string? Id;

public CommandSurrogate(string? id)
{
Id = id;
}


}
Loading

0 comments on commit 47a9c46

Please sign in to comment.