Exemplo n.º 1
0
        public async Task <IActionResult> PlaceOrder([FromBody] OrderCreateDto orderCreate)
        {
            // dependency tracking
            var telemetryClient = _telemetryClientFactory.Create();

            _logger.LogInformation("API - Order controller - PlaceOrders");
            ConcertUser entityConcertUser;

            try
            {
                entityConcertUser = Mapper.Map <ConcertUser>(orderCreate);
                _ordersRepository.PlaceOrderAsync(entityConcertUser);
                await _ordersRepository.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                if (ex.InnerException.Message.Contains("PK_"))
                {
                    return(BadRequest(new ProblemDetailsError(StatusCodes.Status400BadRequest, "Duplicate order.")));
                }
                throw;
            }

            _logger.LogInformation($"Retrieving new order");
            var orderDb = await _ordersRepository.GetOrderAsync(entityConcertUser.Token);

            var orderDto = Mapper.Map <ApiLib.DTOs.OrderDto>(orderDb);

            // dependency tracking
            var current          = Activity.Current;
            var requestActivity  = new Activity("command://order.pay");
            var requestOperation = telemetryClient.StartOperation <RequestTelemetry>(requestActivity);

            try
            {
                // drop message in the queue
                _logger.LogInformation($"Drop message in the queue");

                //TODO KeyVault : local MSI and docker
                var sbConnectionString = String.Empty;
                try
                {
                    sbConnectionString = _vaultService.GetSecret("cn-servicebus").Result;
                }
                catch (Exception ex)
                {
                    // TODO local debug with docker
                    // MSI + docker not working in debug mode?
                    _logger.LogError(ex.Message);
                }
                if (String.IsNullOrEmpty(sbConnectionString))
                {
                    sbConnectionString = _configuration.GetConnectionString(name: "ServiceBus");
                }

                var pub        = new Publisher("q-payment-in", sbConnectionString);
                var cloudEvent = new CloudEvent("command://order.pay", new Uri("app://ticketing.api"))
                {
                    Id          = Guid.NewGuid().ToString(),
                    ContentType = new ContentType(MediaTypeNames.Application.Json),
                    Data        = JsonConvert.SerializeObject(new PaymentContext()
                    {
                        Attendee = orderDto.Attendee,
                        OrderId  = orderDto.OrderId.ToString(),
                        Token    = orderDto.Token,
                    })
                };

                _logger.LogInformation(new EventId((int)LoggingContext.EventId.Processing),
                                       LoggingContext.Template,
                                       "cloud event publishing [command://order.pay]",
                                       LoggingContext.EntityType.Order.ToString(),
                                       LoggingContext.EventId.Processing.ToString(),
                                       LoggingContext.Status.Pending.ToString(),
                                       "correlationId",
                                       LoggingContext.CheckPoint.Publisher.ToString(),
                                       "long description");

                _logger.LogInformation("COMMAND - Sending message to the bus.");
                var jsonFormatter = new JsonEventFormatter();
                var messageBody   = jsonFormatter.EncodeStructuredEvent(cloudEvent, out var contentType);
                await pub.SendMessagesAsync(Encoding.UTF8.GetString(messageBody));
            }
            catch (Exception ex)
            {
                // dependency tracking
                telemetryClient.TrackException(ex);
                throw;
            }
            finally
            {
                // dependency tracking
                telemetryClient.StopOperation(requestOperation);
            }

            _logger.LogInformation($"Returning order token '{entityConcertUser.Token}'");
            return(CreatedAtRoute("Orders_GetOrderDetails",
                                  new { token = entityConcertUser.Token },
                                  orderDto));
        }