Exemplo n.º 1
0
	/// <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;
	}
Exemplo n.º 2
0
        internal void Start(RequestHandlerDelegate dispatch)
        {
            requestDelegate = dispatch;
            Log.Info("Starting HTTP server");

            try
            {
                //Start listening for connections
                _listener.Start();
            }
            catch (Exception e)
            {
                Log.Critical("Unable to start HttpListener.", e, true);
            }

            //Create a thread for handling and dispatching incoming requests
            new Thread(ProcessRequests).Start();
        }
    protected override async Task <TResponse> Process(EntityModelCommand <TEntityModel, TResponse> request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
    {
        if (request is null)
        {
            throw new ArgumentNullException(nameof(request));
        }

        if (next is null)
        {
            throw new ArgumentNullException(nameof(next));
        }

        await SetTenantId(request).ConfigureAwait(false);

        // continue pipeline
        return(await next().ConfigureAwait(false));
    }
Exemplo n.º 4
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            await _writer.WriteLineAsync("-- Handling Request");

            var response = await next();

            await _writer.WriteLineAsync("-- Finished Request");

            return(response);
        }
Exemplo n.º 5
0
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var errors = _validators
                         .Select(v => v.Validate(request))
                         .SelectMany(result => result.Errors)
                         .Where(error => error != null)
                         .ToList();

            if (errors.Any())
            {
                var errorBuilder = new StringBuilder();

                errorBuilder.AppendLine("Invalid command, reason: ");

                foreach (var error in errors)
                {
                    errorBuilder.AppendLine(error.ErrorMessage);
                }

                throw new InvalidCommandException(errorBuilder.ToString(), null);
            }

            return(next());
        }
Exemplo n.º 6
0
        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());
        }
        /// <summary>
        /// Handles the request.
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellation">A cancellation token</param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellation, RequestHandlerDelegate <TResponse> next)
        {
            _timer.Start();

            var response = await next();

            _timer.Stop();

            if (_timer.ElapsedMilliseconds > 500)
            {
                var name = typeof(TRequest).Name;
                _logger.LogWarning($"EventsCore Long Running Request: {name} ({_timer.ElapsedMilliseconds} milliseconds) {_currentUserService.UserId} {request}");
            }
            return(response);
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var authorizeAttributes = request.GetType().GetCustomAttributes <AuthorizeAttribute>();

            if (authorizeAttributes.Any())
            {
                // Must be authenticated user
                if (_currentUserService.UserId == null)
                {
                    throw new UnauthorizedAccessException();
                }

                // Role-based authorization
                var authorizeAttributesWithRoles = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Roles));

                if (authorizeAttributesWithRoles.Any())
                {
                    foreach (var roles in authorizeAttributesWithRoles.Select(a => a.Roles.Split(',')))
                    {
                        var authorized = false;
                        foreach (var role in roles)
                        {
                            var isInRole = await _identityService.IsInRoleAsync(_currentUserService.UserId, role.Trim());

                            if (isInRole)
                            {
                                authorized = true;
                                break;
                            }
                        }

                        // Must be a member of at least one role in roles
                        if (!authorized)
                        {
                            throw new ForbiddenAccessException();
                        }
                    }
                }

                // Policy-based authorization
                var authorizeAttributesWithPolicies = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Policy));
                if (authorizeAttributesWithPolicies.Any())
                {
                    foreach (var policy in authorizeAttributesWithPolicies.Select(a => a.Policy))
                    {
                        var authorized = await _identityService.AuthorizeAsync(_currentUserService.UserId, policy);

                        if (!authorized)
                        {
                            throw new ForbiddenAccessException();
                        }
                    }
                }
            }

            // User is authorized / authorization not required
            return(await next());
        }
Exemplo n.º 9
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            if (!((EntityBase)request).Valid)
            {
                var response = (TResponse) new Response(request.Notifications, true);
                return(response);
            }

            var result = await next();

            return(result);
        }
Exemplo n.º 10
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var response = default(TResponse);
            var typeName = request.GetGenericTypeName();

            try
            {
                if (_dbContext.HasActiveTransaction)
                {
                    return(await next());
                }

                var strategy = _dbContext.Database.CreateExecutionStrategy();

                await strategy.ExecuteAsync(async() =>
                {
                    Guid transactionId;

                    using (var transaction = await _dbContext.BeginTransactionAsync())
                        using (LogContext.PushProperty("TransactionContext", transaction))
                        {
                            _logger.LogInformation("----- Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, JsonFormatting.Formated(request));

                            response = await next();

                            _logger.LogInformation("----- Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName);

                            await _dbContext.CommitTransactionAsync(transaction);

                            transactionId = transaction.TransactionId;
                        }

                    await _posServiceIntegrationEventService.PublishEventsThroughEventBusAsync(transactionId);
                });

                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request);

                throw;
            }
        }
Exemplo n.º 11
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            if (!(request is IApplicationRequest <object> appRequest))
            {
                throw new ArgumentNullException($"{nameof(appRequest)} app request must implement {nameof(IApplicationRequest<object>)}");
            }

            var requestType = appRequest.Data?.GetType();

            ProcessOnlyUserItselfPermission(appRequest, requestType);
            ProcessRequirePermissionAttribute(appRequest, requestType);

            return(await next());
        }
Exemplo n.º 12
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            if (request is SemanticTokensParams semanticTokensParams)
            {
                var response = await next().ConfigureAwait(false);

                if (GetResponse(semanticTokensParams, response, out var result) && string.IsNullOrEmpty(result.ResultId))
                {
                    result.ResultId = Guid.NewGuid().ToString();
                }
                return(response);
            }

            if (request is SemanticTokensDeltaParams semanticTokensDeltaParams)
            {
                var response = await next().ConfigureAwait(false);

                if (GetResponse(semanticTokensDeltaParams, response, out var result))
                {
                    if (result?.IsFull == true && string.IsNullOrEmpty(result.Value.Full.ResultId))
                    {
                        result.Value.Full.ResultId = semanticTokensDeltaParams.PreviousResultId;
                    }

                    if (result?.IsDelta == true && string.IsNullOrEmpty(result.Value.Delta.ResultId))
                    {
                        result.Value.Delta.ResultId = semanticTokensDeltaParams.PreviousResultId;
                    }
                }
                return(response);
            }

            return(await next().ConfigureAwait(false));
        }
Exemplo n.º 13
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            _logger.Log(LogLevel.Information, $"Handling {typeof(TRequest).Name}");
            var response = await next();

            _logger.Log(LogLevel.Information, $"Handled {typeof(TRequest).Name}");
            return(response);
        }
Exemplo n.º 14
0
        public Task <SearchTransactionResult> Handle(SearchTransaction request, CancellationToken cancellationToken, RequestHandlerDelegate <SearchTransactionResult> next)
        {
            if (!request.Filter.Accounts.Any())
            {
                var accounts = accountRepository
                               .Query
                               .Where(a => a.UserId == request.UserId)
                               .Select(a => a.Id)
                               .ToList();

                request.Filter.Accounts.AddRange(accounts);
            }

            return(next());
        }
Exemplo n.º 15
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context  = new ValidationContext <TRequest>(request);
            var failures = _validators
                           .Select(async(x) => await x.ValidateAsync(context, cancellationToken))
                           .SelectMany(x => x.Result.Errors)
                           .Where(x => x is not null)
                           .ToList();

            if (failures.Any())
            {
                throw new ValidationException(failures);
            }

            return(await next());
        }
Exemplo n.º 16
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            LogRequest(request);
            var response = await next();

            LogResponse(response);

            return(response);
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var transactionOptions = new TransactionOptions
            {
                IsolationLevel = IsolationLevel.ReadCommitted,
                Timeout        = TransactionManager.MaximumTimeout
            };

            using (var transaction = new TransactionScope(TransactionScopeOption.Required, transactionOptions,
                                                          TransactionScopeAsyncFlowOption.Enabled))
            {
                TResponse response = await next();

                transaction.Complete();

                return(response);
            }
        }
Exemplo n.º 18
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context  = new ValidationContext <TRequest>(request);
            var failures = validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).Where(x => x != null).ToList();

            if (failures.Count != 0)
            {
                throw new ValidationException(failures);
            }

            return(await next());
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            _timer.Start();

            var response = await next();

            _timer.Stop();

            if (_timer.ElapsedMilliseconds > 500)
            {
                var name = typeof(TRequest).Name;

                _logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@Request}",
                                   name, _timer.ElapsedMilliseconds, request);
            }

            return(response);
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            if (request is ICacheableQuery cacheableQuery)
            {
                TResponse response;
                async Task <TResponse> GetResponseAndAddToCache()
                {
                    response = await next();

                    var options = cacheableQuery.SlidingExpiration != null ? new DistributedCacheEntryOptions {
                        SlidingExpiration = cacheableQuery.SlidingExpiration
                    } : defaultCacheOptions;
                    await cache.SetAsync(cacheableQuery.CacheKey, byteSerializer.Serialize(response), options, cancellationToken);

                    return(response);
                }

                if (cacheableQuery.ReplaceCachedEntry)
                {
                    logger.LogInformation($"Replacing cache entry for key '{cacheableQuery.CacheKey}'.");
                    response = await GetResponseAndAddToCache();
                }
                else
                {
                    var cachedResponse = await cache.GetAsync(cacheableQuery.CacheKey, cancellationToken);

                    if (cachedResponse != null)
                    {
                        logger.LogInformation($"Cache hit for key '{cacheableQuery.CacheKey}'.");
                        response = byteSerializer.Deserialize <TResponse>(cachedResponse);
                    }
                    else
                    {
                        logger.LogInformation($"Cache miss for key '{cacheableQuery.CacheKey}'. Adding to cache.");
                        response = await GetResponseAndAddToCache();
                    }
                }

                if (cacheableQuery.RefreshCachedEntry)
                {
                    logger.LogInformation($"Cache refreshed for key '{cacheableQuery.CacheKey}'.");

                    await cache.RefreshAsync(cacheableQuery.CacheKey, cancellationToken);
                }

                return(response);
            }
            else
            {
                return(await next());
            }
        }
Exemplo n.º 21
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context  = new ValidationContext(request);
            var failures = validators
                           .Select(async v => (await v.ValidateAsync(context, cancellationToken)))
                           .SelectMany(result => result.Result.Errors)
                           .Where(f => f != null)
                           .ToList();

            if (failures.Count == 0)
            {
                return(await next());
            }

            if (typeof(TResponse).IsAssignableFrom(typeof(UseCaseResult)))
            {
                return((TResponse)Activator.CreateInstance(typeof(TResponse), failures, ResultCategory.ValidationFailed));
            }

            throw new ValidationException(failures);
        }
Exemplo n.º 22
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            if (_authorisers.Any())
            {
                foreach (var authoriser in _authorisers)
                {
                    var authorised = await authoriser.Authorise(request, cancellationToken);

                    if (!authorised)
                    {
                        throw new UnauthorisedApplicationException("Current user is not authorised to perform this action");
                    }
                }
            }

            return(await next());
        }
Exemplo n.º 23
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            TResponse response = await next();

            string requestName = request.ToString();

            // Commands convention
            if (requestName.EndsWith("Command"))
            {
                Type   requestType = request.GetType();
                string commandName = requestType.Name;

                var data = new Dictionary <string, object>
                {
                    {
                        "request", request
                    },
                    {
                        "response", response
                    }
                };

                string jsonData  = JsonConvert.SerializeObject(data);
                byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData);

                EventData eventData = new EventData(eventId: Guid.NewGuid(),
                                                    type: commandName,
                                                    isJson: true,
                                                    data: dataBytes,
                                                    metadata: null);

                await _eventStoreDbContext.AppendToStreamAsync(eventData);
            }

            return(response);
        }
Exemplo n.º 24
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var typeName = request.GetGenericTypeName();

            _logger.LogInformation("----- Validating command {CommandType}", typeName);

            var failures = _validators
                           .Select(v => v.Validate(request))
                           .SelectMany(result => result.Errors)
                           .Where(error => error != null)
                           .ToList();

            if (failures.Any())
            {
                _logger.LogWarning("Validation errors - {CommandType} - Command: {@Command} - Errors: {@ValidationErrors}", typeName, request, failures);

                throw new ValidationException("Validation errors", failures);
            }

            return(await next());
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            try
            {
                return(await next());
            }
            catch (Exception ex)
            {
                var requestName = typeof(TRequest).Name;

                _logger.LogError(ex, "BeerTracker Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);

                throw;
            }
        }
Exemplo n.º 26
0
        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 ValidationException(failures);
            }

            return(next());
        }
Exemplo n.º 27
0
 internal void Stop()
 {
     _listener.Stop();
     _listener.Close();
     requestDelegate = null;
 }
Exemplo n.º 28
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var validator = (IValidator <TRequest>)_serviceProvider.GetService(typeof(IValidator <TRequest>));

            if (validator != null)
            {
                _logger.LogInformation("Validating command {CommandType}", request.GetType().Name);

                var failures = (await validator.ValidateAsync(request, cancellationToken)).Errors;
                if (failures.Any())
                {
                    _logger.LogWarning("Validation errors - {CommandType} - Command: {@Command} - Errors: {@ValidationErrors}",
                                       request.GetType().Name, request, failures);

                    var validationErrors = failures.Select(er => new ValidationError
                    {
                        FieldName      = er.PropertyName,
                        Message        = er.ErrorMessage,
                        AttemptedValue = er.AttemptedValue,
                    }).ToList();
                    throw new CommandValidationException(validationErrors);
                }
            }

            return(await next());
        }
Exemplo n.º 29
0
	/// <summary>
	/// Remove o listener da callback da request
	/// </summary>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	public void RemoveListener(RequestHandlerDelegate __callbackRequestCompleted)
	{	
		callbackRequestCompleted -= __callbackRequestCompleted;
	}
Exemplo n.º 30
0
 public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
 {
     return(default);
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            try
            {
                _logger.Information(
                    "Executing command/query {Command}",
                    typeof(TRequest).GetType().Name);

                var result = await next();

                _logger.Information("Command/Query {Command} processed successful", typeof(TRequest).GetType().Name);

                return(result);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, "Command/Query {Command} processing failed", typeof(TRequest).GetType().Name);
                throw;
            }
        }
Exemplo n.º 32
0
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context  = new ValidationContext <TRequest>(request);
            var failures = _validators
                           .Select(validator => validator.Validate(context))
                           .SelectMany(validationResult => validationResult.Errors)
                           .Where(validationFailure => validationFailure != null)
                           .ToList();

            return(failures.Count != 0 ?
                   throw new ValidationException(failures) :
                   next());
        }
Exemplo n.º 33
0
        public async 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.Any())
            {
                var errors = string.Join(",", failures.Select(x => x.ErrorMessage).ToArray());
                throw new ApplicationException(
                          $"Request {typeof(TRequest).Name} => {errors}", new ValidationException("Validation exception", failures));
            }

            var response = await next();

            return(response);
        }
Exemplo n.º 34
0
		public static Uri GetUri (RequestHandlerDelegate dlg)
		{
			var handler = instance.handlerByMethod [dlg.Method];
			if (handler == null)
				throw new InvalidOperationException ();

			return GetUri (handler);
		}
Exemplo n.º 35
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            try
            {
                return(await next());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                var resultType = typeof(TResponse);

                if (resultType.IsGenericType)
                {
                    var genericResultType = resultType.GetGenericArguments()[0];
                    var failureResultType = typeof(FailureResult <>).MakeGenericType(genericResultType);
                    return(Activator.CreateInstance(failureResultType, ex) as TResponse);
                }

                return(new FailureResult(ex) as TResponse);
            }
        }