コード例 #1
0
        /// <inheritdoc/>
        public override async Task InvokeAsync(IHttpFunctionContext context)
        {
            var       hasError  = true;
            Exception exception = null;

            try
            {
                await Next.InvokeAsync(context).ConfigureAwait(false);

                hasError = false;
            }
            catch (UnauthorizedAccessException ex)
            {
                exception        = ex;
                context.Response = new UnauthorizedResult();
            }
            catch (Exception ex)
            {
                exception        = ex;
                context.Response = GetUnpredictableResult(context.Request, ex);
            }
            finally
            {
                if (hasError)
                {
                    serverlessLogger.LogError(exception, $"[{nameof(ExceptionMiddleware)}]");
                }
            }
        }
        private void CheckAuthHeader(IHttpFunctionContext context)
        {
            var request       = context.Request;
            var authorization = (string)request.Headers["Authorization"];

            if (authorization == null || authorization?.Split(' ').Length != 2 || HasInvalidAuthHeader(authorization))
            {
                context.Response = new UnauthorizedObjectResult(string.Empty);
                return;
            }

            try
            {
                var token     = authorization.Split(' ')[1];
                var principal = ExtractClaimFromExternalJwt(token);

                AddCustomClaims(authorization, principal, request.HttpContext);

                acessor.HttpContext = context.Request.HttpContext;
            }
            catch (Exception e)
            {
                serverlessLogger.LogError(e, $"[{nameof(AuthenticationMiddleware)}] {e.Message}");

                context.Response = GetForbiddenContent(e);
                return;
            }
        }
コード例 #3
0
 public static object ConvertToJson(string data, IServerlessLogger serverlessLogger)
 {
     try
     {
         return(string.IsNullOrWhiteSpace(data) ? null : JsonConvert.DeserializeObject(data));
     }
     catch (Exception ex)
     {
         serverlessLogger.LogError(ex, $"{nameof(LoggerHelper)} -> Fail using {nameof(ConvertToJson)}: data -> {data}. message: {ex.Message}");
         return(data);
     }
 }
コード例 #4
0
        /// <inheritdoc/>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply != null)
            {
                try
                {
                    var endProcess = DateTimeOffset.UtcNow;
                    var buffer     = reply.CreateBufferedCopy(int.MaxValue);
                    var msgCopy    = buffer.CreateMessage();

                    reply = buffer.CreateMessage();
                    var isFault = reply.IsFault;

                    CreateLog(msgCopy, endProcess, isFault);
                }
                catch (Exception ex)
                {
                    logger.LogError($"Fail to create a third party wcf log response: {ex.ToString()}");
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Start event hub process.
        /// </summary>
        /// <param name="serverlessLogger">Logger to save log.</param>
        /// <param name="logger">Logger to be injected in <paramref name="serverlessLogger"/>.</param>
        /// <param name="patternLog">Pattern log.</param>
        /// <param name="events">Events to be processed.</param>
        /// <param name="processEventAsync">Process with business rules to be processed.</param>
        /// <param name="publishPoisonedEventAsync">Function receiving error parameter to publish poisoned event data.</param>
        /// <param name="eventReliabilitySettings">Event reliability settings.</param>
        /// <returns>Task executed.</returns>
        public static async Task StartEventProcessAsync(
            IServerlessLogger serverlessLogger,
            ILogger logger,
            string patternLog,
            EventData[] events,
            Func <EventData, Task> processEventAsync,
            Func <EventData, Exception, Task> publishPoisonedEventAsync,
            EventReliabilitySettings eventReliabilitySettings)
        {
            try
            {
                serverlessLogger.InjectLogger(logger);

                if (events.Length == 0)
                {
                    serverlessLogger.LogWarning($"{patternLog} No event to process.");
                    return;
                }

                serverlessLogger.LogInformation($"{patternLog} Start processing...");

                var waitAndRetryAsync = GetWaitAndRetry(eventReliabilitySettings);

                var eventCount = events.Length;

                for (int eventIndex = 0; eventIndex < eventCount; eventIndex++)
                {
                    serverlessLogger.LogInformation($"{patternLog} Processing event index {eventIndex}...");

                    var eventData     = events[eventIndex];
                    var fallbackAsync = GetFallback(serverlessLogger, patternLog, eventData, publishPoisonedEventAsync);

                    await Policy
                    .WrapAsync(fallbackAsync, waitAndRetryAsync)
                    .ExecuteAsync(() => processEventAsync(eventData))
                    .ConfigureAwait(false);

                    serverlessLogger.LogInformation($"{patternLog} Event index {eventIndex} processed!");
                }

                serverlessLogger.LogInformation($"{patternLog} Processing completed!");
            }
            catch (Exception ex)
            {
                serverlessLogger.LogError(ex, $"{patternLog} Processing failed!");
                throw;
            }
        }
コード例 #6
0
 private static Polly.Fallback.AsyncFallbackPolicy GetFallback(
     IServerlessLogger serverlessLogger,
     string patternLog,
     EventData eventData,
     Func <EventData, Exception, Task> publishPoisonedEventAsync)
 {
     return(Policy
            .Handle <Exception>()
            .FallbackAsync(
                (exception, context, cancellationToken) => publishPoisonedEventAsync(eventData, exception),
                (exception, context) =>
     {
         serverlessLogger.LogError(exception, $"{patternLog} Processing failed!");
         return Task.CompletedTask;
     }));
 }
コード例 #7
0
        /// <inheritdoc/>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = null;
            var requestText  = string.Empty;
            var responseText = string.Empty;

            if (request != null && request.Content != null)
            {
                requestText = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
            }

            try
            {
                var startProcess = DateTimeOffset.UtcNow;
                response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                var endProcess = DateTimeOffset.UtcNow;

                if (response.Content != null)
                {
                    responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                var log = CreateLog(
                    startProcess,
                    endProcess,
                    request,
                    response,
                    requestText,
                    responseText);

                await Task.Run(() =>
                {
                    serverlessLogger.LogInformation(Serialize(log));
                }).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                serverlessLogger.LogError(ex, $"{nameof(ServerlessLogger)}.{nameof(LoggingHandler)} -> Fail to log Third Party: {ex.Message}");
            }

            return(response);
        }
コード例 #8
0
        /// <summary>
        /// Start cosmosdb process.
        /// </summary>
        /// <param name="serverlessLogger">Logger to save log.</param>
        /// <param name="logger">Logger to be injected in <paramref name="serverlessLogger"/>.</param>
        /// <param name="patternLog">Pattern log.</param>
        /// <param name="documents">Documents to be processed.</param>
        /// <param name="func">Process with business rules to be processed.</param>
        /// <returns>Task executed.</returns>
        public static async Task StartDocumentProcessAsync(
            IServerlessLogger serverlessLogger,
            ILogger logger,
            string patternLog,
            IReadOnlyList <Document> documents,
            Func <Document, Task> func)
        {
            try
            {
                serverlessLogger.InjectLogger(logger);

                if (documents.Count == 0)
                {
                    serverlessLogger.LogWarning($"{patternLog} No document to process.");
                    return;
                }

                serverlessLogger.LogInformation($"{patternLog} Start processing...");

                var documentCount = documents.Count;

                for (int documentIndex = 0; documentIndex < documentCount; documentIndex++)
                {
                    var document = documents[documentIndex];
                    serverlessLogger.LogInformation($"{patternLog} Processing document index: {documentIndex}, id: {document.Id} and resourceId: {document.ResourceId}!");
                    await func(document).ConfigureAwait(false);

                    serverlessLogger.LogInformation($"{patternLog} Document index {documentIndex} processed!");
                }

                serverlessLogger.LogInformation($"{patternLog} Processing completed!");
            }
            catch (Exception ex)
            {
                serverlessLogger.LogError(ex, $"{patternLog} Processing failed!");
                throw;
            }
        }
        /// <summary>
        /// Start event hub process.
        /// </summary>
        /// <param name="serverlessLogger">Logger to save log.</param>
        /// <param name="logger">Logger to be injected in <paramref name="serverlessLogger"/>.</param>
        /// <param name="patternLog">Pattern log.</param>
        /// <param name="events">Events to be processed.</param>
        /// <param name="func">Process with business rules to be processed.</param>
        /// <returns>Task executed.</returns>
        public static async Task StartEventProcessAsync(
            IServerlessLogger serverlessLogger,
            ILogger logger,
            string patternLog,
            EventData[] events,
            Func <EventData, Task> func)
        {
            try
            {
                serverlessLogger.InjectLogger(logger);

                if (events.Length == 0)
                {
                    serverlessLogger.LogWarning($"{patternLog} No event to process.");
                    return;
                }

                serverlessLogger.LogInformation($"{patternLog} Start processing...");

                var eventCount = events.Length;

                for (int eventIndex = 0; eventIndex < eventCount; eventIndex++)
                {
                    serverlessLogger.LogInformation($"{patternLog} Processing event index {eventIndex}...");
                    await func(events[eventIndex]).ConfigureAwait(false);

                    serverlessLogger.LogInformation($"{patternLog} Event index {eventIndex} processed!");
                }

                serverlessLogger.LogInformation($"{patternLog} Processing completed!");
            }
            catch (Exception ex)
            {
                serverlessLogger.LogError(ex, $"{patternLog} Processing failed!");
                throw;
            }
        }
コード例 #10
0
        /// <inheritdoc/>
        public async Task <IActionResult> ExecuteAsync(IHttpFunctionContext context)
        {
            try
            {
                if (pipeline.Any())
                {
                    await pipeline[0].InvokeAsync(context).ConfigureAwait(false);

                    if (context.Response != null)
                    {
                        return(context.Response);
                    }
                }

                throw new Exception();
            }
            catch (Exception e)
            {
                serverlessLogger.LogError(e, $"[{nameof(MiddlewarePipeline)}] {e.Message}");
                return(new StatusCodeResult((int)HttpStatusCode.InternalServerError));

                throw;
            }
        }