Example #1
0
        public void Given_Values_When_Implicitly_Converted_Then_It_Should_Return_Result(string upn, InterfaceType @interface, string message)
        {
            var correlationId = Guid.NewGuid();
            var spanId        = Guid.NewGuid();
            var eventId       = Guid.NewGuid();

            var error = new InternalServerErrorObjectResult()
            {
                Upn           = upn,
                CorrelationId = correlationId,
                Interface     = @interface,
                SpanId        = spanId,
                EventId       = eventId,
                Message       = message,
            };

            ObjectResult result = error;

            result.Should().NotBeNull();
            result.Value.Should().BeOfType <ErrorResponseMessage>();
            (result.Value as ErrorResponseMessage).Upn.Should().Be(upn);
            (result.Value as ErrorResponseMessage).CorrelationId.Should().Be(correlationId);
            (result.Value as ErrorResponseMessage).Interface.Should().Be(@interface);
            (result.Value as ErrorResponseMessage).SpanId.Should().Be(spanId);
            (result.Value as ErrorResponseMessage).EventId.Should().Be(eventId);
            (result.Value as ErrorResponseMessage).Message.Should().Be(message);
            result.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);
        }
        public bool ValidateDelete(
            OfmDeletionQueryResult <TId> ofmDeletionQueryResult,
            TId id,
            out ObjectResult objectResult)
        {
            objectResult = null;

            if (ofmDeletionQueryResult.ErrorMessages.Count > 0)
            {
                // For the moment, we return 500 error message to avoid exposing too much info.
                // No errorMessage from lower levels are anticipated, so an exception was probably thrown
                _controller.ModelState.AddModelError(_shortCamelCasedControllerName, "There was an internal server error. Please contact support.");
                objectResult = new InternalServerErrorObjectResult(_controller.ModelState);
                return(false);
            }

            if (ofmDeletionQueryResult.DidEntityExist == false && ofmDeletionQueryResult.ErrorMessages.Count == 0)
            {
                _controller.ModelState.AddModelError(_shortCamelCasedControllerName, "No " + _shortCamelCasedControllerName + " found for id=" + id);
                objectResult = new EntityNotFoundObjectResult(_controller.ModelState);
                return(false);
            }

            return(true);
        }
        public void ForbiddenObjectResultHasStatusCode409()
        {
            // Arrange
            var result = new InternalServerErrorObjectResult("Some Message");

            // Assert
            Assert.Equal(500, result.StatusCode);
        }
        public void Construct()
        {
            var result = new InternalServerErrorObjectResult();

            Assert.Equal(500, result.StatusCode);

            result = new InternalServerErrorObjectResult("some message");
            Assert.Equal(500, result.StatusCode);
            Assert.Equal("some message", result.Value);
        }
Example #5
0
        public void ShouldReturnInternalServerErrorObjectResult()
        {
            // given
            string randomMessage  = GetRandomMessage();
            string inputMessage   = randomMessage;
            var    expectedResult = new InternalServerErrorObjectResult(inputMessage);

            // when
            InternalServerErrorObjectResult actualResult =
                this.restfulController.InternalServerError(inputMessage);

            // then
            actualResult.Should().BeEquivalentTo(expectedResult);
        }
Example #6
0
        /// <summary>
        /// OnException
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType);

            ObjectResult     result     = null;
            BaseDTO <object> baseResult = new BaseDTO <object>()
            {
                Code = StatusCodes.Status500InternalServerError,
                Msg  = context.Exception.Message,
                Data = context.Exception.Message
            };

            if (_baseExceptions.Contains(context.Exception.GetType()) || context.Exception.GetType().IsSubclassOf(typeof(BaseException)))
            {
                logger.LogInformation(
                    new EventId(context.Exception.HResult),
                    context.Exception.Message
                    );

                if (context.Exception is BaseException baseException)
                {
                    baseResult.Code = baseException.Code;
                }
                result = new ApplicationErrorResult(baseResult);
            }
            else
            {
                logger.LogError(
                    new EventId(context.Exception.HResult),
                    context.Exception,
                    context.Exception.Message
                    );

                result = new InternalServerErrorObjectResult(baseResult);
            }

            if (_env.IsDevelopment())
            {
                baseResult.Data = context.Exception?.ToString()
                                  ?? context.Exception?.Message
                                  ?? string.Empty;
            }

            context.Result           = result;
            context.ExceptionHandled = true;
        }
Example #7
0
        public void OnException(ExceptionContext context)
        {
            var message = RequestInfo.GetRequestErrorMessage(context.HttpContext.Request);

            if (context.Exception is BaseException)
            {
                var ex          = context.Exception as BaseException;
                var errorResult = new ValidationErrorResult(message, ex.Errors);
                this.BuildResponse(context, ex.GetObjectResult(errorResult));
            }
            else
            {
                LogInternalServerError(context);
                var errorResult = new ValidationErrorResult(message, GetInternalServerError());

                if (_env.IsDevelopment())
                {
                    errorResult.AddDeveloperMessage(context.Exception.Message);
                }

                var objectResult = new InternalServerErrorObjectResult(errorResult);
                this.BuildResponse(context, objectResult);
            }
        }
Example #8
0
        public async Task <IActionResult> CreateExercisesAsync(
            [HttpTrigger(AuthorizationLevel.Function, HttpVerbs.Post, Route = "routines/{routineId}/exercises")] HttpRequest req,
            Guid routineId,
            ExecutionContext context,
            ILogger log)
        {
            var request = await req.ToRequestMessageAsync <ExerciseRequestMessage>().ConfigureAwait(false);

            var eventId       = context.InvocationId;
            var spanId        = request.SpanId;
            var correlationId = request.CorrelationId;
            var upn           = request.Upn;
            var @interface    = request.Interface;

            log.LogData(LogLevel.Information, request,
                        EventType.ExerciseReceived, EventStatusType.Succeeded, eventId,
                        SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                        @interface, correlationId);

            if (routineId != request.RoutineId)
            {
                log.LogData(LogLevel.Error, request,
                            EventType.InvalidRoutine, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            message: EventType.InvalidRoutine.ToDisplayName());

                return(new BadRequestResult());
            }

            var exerciseId = Guid.NewGuid();
            var entity     = new ExerciseEntity()
            {
                PartitionKey    = correlationId.ToString(),
                RowKey          = eventId.ToString(),
                Upn             = upn,
                CorrelationId   = correlationId,
                SpanId          = spanId,
                Interface       = @interface,
                EventId         = eventId,
                EventName       = EventType.ExerciseCreated.ToDisplayName(),
                RoutineId       = request.RoutineId,
                Routine         = request.Routine,
                Target          = request.Target,
                ExerciseId      = exerciseId,
                Exercise        = request.Exercise,
                Sets            = request.Sets.ToJson(),
                AdditionalNotes = request.AdditionalNotes,
            };

            var res = default(ObjectResult);

            try
            {
                if (this._settings.ForceError.Publisher.Exercise)
                {
                    throw new ErrorEnforcementException("Error Enforced!");
                }

                await this._client.CreateTableIfNotExistsAsync(this._settings.GymLog.StorageAccount.Table.TableName).ConfigureAwait(false);

                var table    = this._client.GetTableClient(this._settings.GymLog.StorageAccount.Table.TableName);
                var response = await table.UpsertEntityAsync(entity).ConfigureAwait(false);

                res = response.ToExerciseResponseMessage(request, entity.EventId, entity.ExerciseId);

                log.LogData(response.Status.ToLogLevel(), res.Value,
                            response.Status.ToExerciseEventType(), response.Status.ToEventStatusType(), eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            clientRequestId: response.ClientRequestId,
                            message: response.Status.ToResponseMessage(res));
            }
            catch (Exception ex)
            {
                res = new InternalServerErrorObjectResult()
                {
                    Upn           = upn,
                    CorrelationId = correlationId,
                    Interface     = @interface,
                    SpanId        = spanId,
                    EventId       = eventId,
                    Message       = ex.Message,
                };

                log.LogData(LogLevel.Error, res.Value,
                            EventType.ExerciseNotCreated, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            ex: ex,
                            message: ex.Message);
            }

            return(res);
        }
Example #9
0
        public async Task <IActionResult> PublishRoutineAsync(
            [HttpTrigger(AuthorizationLevel.Function, HttpVerbs.Post, Route = "routines/{routineId}/publish")] HttpRequest req,
            Guid routineId,
            ExecutionContext context,
            [ServiceBus(GymLogTopicKey)] IAsyncCollector <ServiceBusMessage> collector,
            ILogger log)
        {
            var request = await req.ToRequestMessageAsync <PublishRequestMessage>().ConfigureAwait(false);

            var eventId       = context.InvocationId;
            var spanId        = request.SpanId;
            var correlationId = request.CorrelationId;
            var upn           = request.Upn;
            var @interface    = request.Interface;

            log.LogData(LogLevel.Information, request,
                        EventType.PublishRequestReceived, EventStatusType.Succeeded, eventId,
                        SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                        @interface, correlationId);

            if (routineId != request.RoutineId)
            {
                log.LogData(LogLevel.Error, request,
                            EventType.InvalidPublishRequest, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            message: EventType.InvalidPublishRequest.ToDisplayName());

                return(new BadRequestResult());
            }

            var entity = new RoutineEntity()
            {
                PartitionKey  = correlationId.ToString(),
                RowKey        = eventId.ToString(),
                Upn           = upn,
                CorrelationId = correlationId,
                SpanId        = spanId,
                Interface     = @interface,
                EventId       = eventId,
                EventName     = EventType.RoutineCompleted.ToDisplayName(),
                RoutineId     = routineId,
                Routine       = request.Routine,
            };

            var res = default(ObjectResult);

            try
            {
                if (this._settings.ForceError.Publisher.Publish)
                {
                    throw new ErrorEnforcementException("Error Enforced!");
                }

                await this._client.CreateTableIfNotExistsAsync(this._settings.GymLog.StorageAccount.Table.TableName).ConfigureAwait(false);

                var table = this._client.GetTableClient(this._settings.GymLog.StorageAccount.Table.TableName);

                var records = await table.QueryAsync <ExerciseEntity>(p => p.PartitionKey == correlationId.ToString() &&
                                                                      p.SpanId == spanId)
                              .ToListAsync()
                              .ConfigureAwait(false);

                records = records.Where(p => !p.Exercise.IsNullOrWhiteSpace())
                          .ToList();

                if (!records.Any())
                {
                    res = records.ToPublishResponseMessage(request, eventId);

                    log.LogData(LogLevel.Error, res.Value,
                                EventType.RecordNotFound, EventStatusType.Failed, eventId,
                                SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                                request.Interface, correlationId,
                                message: EventType.RecordNotFound.ToDisplayName());

                    return(res);
                }

                var entities = records.GroupBy(p => p.Exercise)
                               .Select(g => new ExerciseEntityGroup()
                {
                    Exercise = g.Key, Entity = g.OrderByDescending(q => q.Timestamp).First()
                })
                               .Select(p => p.Entity)
                               .OrderByDescending(p => p.Timestamp)
                               .ToList();

                res = entities.ToPublishResponseMessage(request, eventId);

                log.LogData(LogLevel.Information, res.Value,
                            EventType.RecordPopulated, EventStatusType.Succeeded, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            message: EventType.RecordPopulated.ToDisplayName());

                var messageId = Guid.NewGuid();
                var subSpanId = Guid.NewGuid();
                var timestamp = DateTimeOffset.UtcNow;
                var message   = (RoutineQueueMessage)(PublishResponseMessage)res.Value;
                var msg       = new ServiceBusMessage(message.ToJson())
                {
                    CorrelationId = correlationId.ToString(),
                    MessageId     = messageId.ToString(),
                    ContentType   = ContentTypes.ApplicationJson,
                };
                msg.ApplicationProperties.Add("pubSpanId", spanId);
                msg.ApplicationProperties.Add("subSpanId", subSpanId);
                msg.ApplicationProperties.Add("interface", @interface.ToString());
                msg.ApplicationProperties.Add("timestamp", timestamp.ToString(CultureInfo.InvariantCulture));

                await collector.AddAsync(msg).ConfigureAwait(false);

                log.LogData(LogLevel.Information, msg,
                            EventType.MessagePublished, EventStatusType.Succeeded, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherInProgress, spanId,
                            @interface, correlationId,
                            messageId: messageId.ToString(),
                            message: EventType.MessagePublished.ToDisplayName());

                var response = await table.UpsertEntityAsync(entity).ConfigureAwait(false);

                var r = response.ToRoutineResponseMessage(request, eventId, entity.RoutineId);

                log.LogData(response.Status.ToLogLevel(), r.Value,
                            response.Status.ToRoutineCompletedEventType(), response.Status.ToEventStatusType(), eventId,
                            SpanType.Publisher, SpanStatusType.PublisherCompleted, spanId,
                            @interface, correlationId,
                            clientRequestId: response.ClientRequestId,
                            message: response.Status.ToResponseMessage(r));
            }
            catch (Exception ex)
            {
                res = new InternalServerErrorObjectResult()
                {
                    Upn           = upn,
                    CorrelationId = correlationId,
                    Interface     = @interface,
                    SpanId        = spanId,
                    EventId       = eventId,
                    Message       = ex.Message,
                };

                log.LogData(LogLevel.Error, res.Value,
                            EventType.MessageNotPublished, EventStatusType.Failed, eventId,
                            SpanType.Publisher, SpanStatusType.PublisherCompleted, spanId,
                            @interface, correlationId,
                            ex: ex,
                            message: ex.Message);
            }

            return(res);
        }