public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { ValidationResult validationResult; CustomValidationFailedException validationError; if (_type == _typeOperationResult) { validationResult = _validator.Validate(request); if (validationResult.IsValid) { return(next?.Invoke()); } validationError = new CustomValidationFailedException(validationResult.Errors.GroupBy(v => v.PropertyName, v => v.ErrorMessage).ToDictionary(v => v.Key, v => v.Select(y => y))); return(Task.FromResult((TResponse)Convert.ChangeType(OperationResult.Error(validationError), _type))); } if (!_type.IsGenericType || _type.GetGenericTypeDefinition() != _typeOperationResultGeneric) { return(next?.Invoke()); } validationResult = _validator.Validate(request); if (validationResult.IsValid) { return(next?.Invoke()); } validationError = new CustomValidationFailedException(validationResult.Errors.GroupBy(v => v.PropertyName, v => v.ErrorMessage).ToDictionary(v => v.Key, v => v.Select(y => y))); return(Task.FromResult((TResponse)Convert.ChangeType(_operationResultError.Invoke(null, new object[] { validationError }), _type))); }
public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message, RequestHandlerDelegate <TResponse> next) { var context = message.Context; if (_skipAuthentication) { return(await next.Invoke()); } var loginResult = await context.Connection.Authenticate(context.Metadata.AccessToken); context.UserId = loginResult.UserId; context.User = loginResult.User; return(await next.Invoke()); }
/// <summary> /// Add um ouvinte pra quando os dados da plataforma estiverem prontos para serem lidos /// </summary> /// <param name="__callbackRequestCompleted">__callback request completed.</param> public void AddListener(RequestHandlerDelegate __callbackRequestCompleted) { if(_platformDataReceived != null) __callbackRequestCompleted.Invoke(); callbackRequestCompleted += __callbackRequestCompleted; }
public async Task <PipelineResponse> Handle(PizzaPipelineContext context, CancellationToken cancellationToken, RequestHandlerDelegate <PipelineResponse> nextFilter) { context.CurrentStep = nameof(ValidationFilter); if (context.Request.Values.Contains("continue")) { // SIMULATE: Validation succeeded, call next step _logger.LogInformation("Validation succeeded"); var result = string.Concat(context.Request.Values, " | Validation Signature | "); context.Request.Values = result; var pipelineResponse = await nextFilter.Invoke(); return(pipelineResponse); } // SIMULATE: Validation failed, short circuit and return an error response var pipelineError = new PipelineError { OcurredAtStep = nameof(ValidationFilter), Message = "Validation failed" }; var response = new PipelineResponse(string.Empty, pipelineError); return(response); }
/// <inheritdoc /> public async Task <Test1Response> Handle(Test1Request request, CancellationToken cancellationToken, RequestHandlerDelegate <Test1Response> next) { var response = await next.Invoke(); RequestHistory.TryAdd(request, response); return(response); }
public async Task <PipelineResponse> Handle(PizzaPipelineContext context, CancellationToken cancellationToken, RequestHandlerDelegate <PipelineResponse> next) { _logger.LogInformation("Adding Garnish"); context.AddGarnish("Mozarella Cheese, Veggies"); return(await next.Invoke()); }
public override Task <ExecutionResult> Execute(TCommand command, TUser user, CancellationToken cancellationToken) { var profiler = StackExchange.Profiling.MiniProfiler.Current; if (profiler == null || !this.miniProfilerSwitch.Condition(user)) { return(base.Execute(command, user, cancellationToken)); } RequestHandlerDelegate <ExecutionResult> next = null; using (profiler.CustomTiming("Message", JsonSerializer.Serialize(command))) foreach (var keyValuePair in list) { var next1 = next; next = () => { using (profiler.Step(keyValuePair.GetType().Name)) { return(keyValuePair.Execute(command, user, cancellationToken, next1)); } }; } return(next?.Invoke()); }
public async Task <PipelineResponse> Handle(PizzaPipelineContext context, CancellationToken cancellationToken, RequestHandlerDelegate <PipelineResponse> nextFilter) { context.CurrentStep = nameof(MakePizzaCrustFilter); if (_fakeCounter % 4 == 0) { _fakeCounter++; throw new Exception("Boom"); } if (context.Request.Values.Contains("continue")) { _logger.LogInformation("Setting pizza base"); context.SetPizzaBase(PizzaBaseFlourType.Wheat, PizzaBaseType.Pan); _fakeCounter++; return(await nextFilter.Invoke()); } // SIMULATE: Validation failed, short circuit and return an error response var pipelineError = new PipelineError { OcurredAtStep = nameof(MakePizzaCrustFilter), Message = "Validation failed" }; var response = new PipelineResponse(string.Empty, pipelineError); _fakeCounter++; return(response); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { ArgumentValidation.ValidateNotNull(request, next); var context = new ValidationContext(request); var failures = _validators .Select(v => v.Validate(context)) .SelectMany(result => result.Errors) .Where(f => f != null) .ToList(); if (failures.Count > 0) { _logger.LogInformation($"Validation failure for request [{request}]"); var validationErrors = new OpenReddingValidationErrors(); foreach (var validationFailure in failures.Select(failure => new OpenReddingValidationError(failure.PropertyName, failure.ErrorMessage))) { validationErrors.Errors.Add(validationFailure); } // throw new ValidationException(failures); request.ValidationErrors = validationErrors; } return(await next.Invoke()); }
public async Task <TResponse> Handle(TRequest request, CancellationToken token, RequestHandlerDelegate <TResponse> next) { var actorRequest = request as ActorRequest; if (actorRequest == null || actorRequest.HandleNow || actorRequest.ActorRequestType == ActorRequestType.RequestResponse) { var sw = new Stopwatch(); sw.Start(); var result = await next.Invoke(); sw.Stop(); logger.LogInformation($"Handled [{typeof(TRequest).Name}] in {sw.ElapsedMilliseconds} ms."); return(result); } if (actorRequest?.ActorRequestType == ActorRequestType.Send) { if (typeof(TResponse) != typeof(ActorResult)) { throw new Exception($"Incorrect Response Type {typeof(TResponse).Name} - should be Unit!"); } var response = new TResponse(); var actorResult = response as ActorResult; if (actorResult != null) { actorResult.Result = await actorManager.Send(request); } logger.LogInformation($"Queued [{typeof(TRequest).Name}]"); return(response); } if (actorRequest?.ActorRequestType == ActorRequestType.Post) { if (typeof(TResponse) != typeof(ActorResult)) { throw new Exception($"Incorrect Response Type {typeof(TResponse).Name} - should be Unit!"); } var response = new TResponse(); var actorResult = response as ActorResult; if (actorResult != null) { actorResult.Result = await actorManager.Post(request); } return(response); } return(new TResponse()); }
/// <summary> /// Listener da request /// </summary> private void OnRequestCompleted(BaseRequestModel request) { _platformDataReceived = request.svo as GetPlatformDataSVO; if (callbackRequestCompleted != null) { callbackRequestCompleted.Invoke(); } }
public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { _unitofWork.Begin(); var res = next.Invoke(); _unitofWork.Commit(); return(res); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { _logger.LogInformation("Handling request: {requestType}", request.GetType().FullName); var response = await next.Invoke(); _logger.LogInformation("Done Handling request: {requestType}", request.GetType().FullName); return(response); }
public Task <TOut> Handle( TIn request, CancellationToken cancellationToken, RequestHandlerDelegate <TOut> next) { // Check permissions here return(next.Invoke()); }
/// <summary> /// Add um ouvinte pra quando os dados da plataforma estiverem prontos para serem lidos /// </summary> /// <param name="__callbackRequestCompleted">__callback request completed.</param> public void AddListener(RequestHandlerDelegate __callbackRequestCompleted) { if (_platformDataReceived != null) { __callbackRequestCompleted.Invoke(); } callbackRequestCompleted += __callbackRequestCompleted; }
public void Subscribe(RequestHandlerDelegate handler) { if (_completed) { handler?.Invoke(_succeed); return; } _handlers.Add(handler); StartInternal(); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var result = await new Infrastructure.RequestAuthorizationAnalyzer(_userAccessor, _authorizationService).Authorize(request); if (result.Succeeded == false) { throw new Exceptions.AuthorizationFailureException(result.Failure); } return(await next.Invoke()); }
public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var failures = _validators .Select(v => v.Validate(request)) .SelectMany(result => result.Errors) .Where(f => f != null) .ToList(); return(failures.Any() ? ErrorsAsync(failures) : next?.Invoke()); }
public virtual Task <ExecutionResult> Execute(TCommand command, TUser user, CancellationToken cancellationToken) { RequestHandlerDelegate <ExecutionResult> next = null; foreach (var keyValuePair in this.list) { var innerNext = next; next = () => keyValuePair.Execute(command, user, cancellationToken, innerNext); } return(next?.Invoke()); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="next">The next.</param> /// <returns></returns> public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { _timer.Start(); TResponse response = await next?.Invoke(); _timer.Stop(); if (_timer.ElapsedMilliseconds > 500) { var requestName = typeof(TRequest).Name; _logger.LogWarning($"Dev App Long Running Request: {requestName} ({_timer.ElapsedMilliseconds} milliseconds) {request}"); } return(response); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { try { var result = await next.Invoke(); return(result); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); throw ex; } }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { try { return(await next?.Invoke()); } catch (Exception e) { return(_type == _typeOperationResult ? (TResponse)Convert.ChangeType(OperationResult.Error(e), _type) : (TResponse)Convert.ChangeType(_operationResultError.Invoke(null, new object[] { e }), _type)); } }
public async Task <TResponse> Handle(TRequest request, CancellationToken token, RequestHandlerDelegate <TResponse> next) { var sw = new Stopwatch(); sw.Start(); var result = await next.Invoke(); sw.Stop(); this.Logger.Log($"Handled [{typeof(TRequest).Name}] in {sw.ElapsedMilliseconds} ms."); return(result); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { try { return(await next?.Invoke()); } catch (Exception ex) { var requestName = typeof(TRequest).Name; _logger.LogError(ex, "Application Request: Unhandled Exception for Request {Name} {@Request}", requestName, request); throw; } }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var user = await _userAccessor.GetUser() ?? new ApplicationUser() { UserName = "******" }; using (_logger.BeginScope(request)) { try { _logger.LogInformation($"user {user} executing request {request}"); try { _logger.LogTrace($"user {user} executing request {request}: {JsonConvert.SerializeObject(request, _serializerSettings)}"); } catch (JsonException ex) { _logger.LogWarning($"user {user} executing request {request}: failed to serialize the request ({ex})"); } var response = await next.Invoke(); _logger.LogInformation($"user {user} finished executing request {request}, response {response}"); try { _logger.LogTrace($"user {user} executed request {request}: {JsonConvert.SerializeObject(request, _serializerSettings)}; received response {response}: {JsonConvert.SerializeObject(response, _serializerSettings)}"); } catch (JsonException ex) { _logger.LogWarning($"user {user} executing request {request}, response {response}: failed to serialize request/response pair ({ex})"); } return(response); } catch (Exception ex) { try { _logger.LogError($"user {user} executing request {request}: {JsonConvert.SerializeObject(request, _serializerSettings)}; and encountered exception {ex}"); } catch (JsonException jsonEx) { _logger.LogError(ex, $"user {user} executed request {request}: failed to serialize the request ({jsonEx}); and encountered exception {ex}"); } throw; } } }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var obj = (EntityBase)request; obj.Validate(); if (obj.Invalid) { var response = (TResponse) new Response(obj.Notifications, true); return(response); } return(await next?.Invoke()); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="next">The next.</param> /// <returns></returns> /// <exception cref="Common.Exceptions.ValidationException"></exception> public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var context = new ValidationContext(request); var failures = _validators .Select(v => v.Validate(context)) .SelectMany(result => result.Errors) .Where(f => f != null) .ToList(); if (failures.Count != 0) { throw new Common.Exceptions.ValidationException(failures); } return(next?.Invoke()); }
private async Task <TResponse> ExecuteBehaviors(IList <Type> types, TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { if (!types.Any()) { return(await next.Invoke().ConfigureAwait(false)); } var type = types[0]; types.RemoveAt(0); if (_factory(type) is not IPipelineBehavior <TRequest, TResponse> service) { return(await ExecuteBehaviors(types, request, cancellationToken, next).ConfigureAwait(false)); } return(await service.Handle(request, cancellationToken, async() => await ExecuteBehaviors(types, request, cancellationToken, next).ConfigureAwait(false) ).ConfigureAwait(false)); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { if (_validators.Any()) { var context = new ValidationContext <TRequest>(request); var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken))); var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList(); if (failures.Count != 0) { throw new ValidationException(failures); } } return(await next?.Invoke()); }
public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message, RequestHandlerDelegate <TResponse> next) { var context = message.Context; try { return(await next.Invoke()); } catch (Exception ex) { _counter.Increment(); var level = ex is UserException ? LogEventLevel.Warning : LogEventLevel.Error; _logger.Write(level, ex, "[{TraceId}-{UserId}] {Message}", context.Metadata.TraceId, context.UserId == null ? "Anonymous" : context.UserId.ToString(), ex.Message); throw; } }
public async Task Handle_ActiveTransaction_InvokeNext( [Frozen] Mock <IDbContext> mockDbContext, TransactionBehavior <CreateSalesOrderCommand, bool> sut, CreateSalesOrderCommand command, RequestHandlerDelegate <bool> next ) { //Arrange mockDbContext.Setup(_ => _.HasActiveTransaction) .Returns(true); //Act var result = await sut.Handle(command, CancellationToken.None, next); //Assert result.Should().Be(await next.Invoke()); mockDbContext.Verify(_ => _.Execute( It.IsAny <Func <Task> >() ), Times.Never); }