Beispiel #1
0
        public async Task <IActionResult> BookingWithSaga(BookingAccepted model)
        {
            model.BookingId = NewId.NextGuid();
            await _publishEndpoint.Publish(model);

            return(Accepted());
        }
Beispiel #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(100);

            foreach (var i in Enumerable.Range(1, 11))
            {
                Console.Write($"Messages Published count: {i}");

                //RabbitMQ publish with routing key information
                //await _publish.Publish(new SomeValue($"{i}.Dark.Red"), ctx => ctx.SetRoutingKey("dark.red"));

                //Azure Service Bus with header information
                await _publish.Publish(new SomeValue { Payload = $"{i}.Dark.Red" }, x => x.Headers.Set("RoutingKey", "dark.red"));

                await _publish.Publish(new SomeValue { Payload = $"{i}.Light.Red" }, x => x.Headers.Set("RoutingKey", "light.red"));

                await _publish.Publish(new SomeValue { Payload = $"{i}.Dark.Blue" }, x => x.Headers.Set("RoutingKey", "dark.blue"));

                //await _publish.Publish(new SomeValue { Payload = $"{i}.Light.Blue" });
                //await _publish.Publish(new SomeValue { Payload = $"{i}.Dark.Red" });
                //await _publish.Publish(new SomeValue { Payload = $"{i}.Light.Red" });
                //await _publish.Publish(new SomeValue { Payload = $"{i}.Dark.Blue" });
            }
            ;
        }
        public async Task <IAccountModel?> EvaluateAccountPendingAsync(IAccountModel accountCheckCommand)
        {
            if (
                string.IsNullOrEmpty(accountCheckCommand.ProfileId) ||
                string.IsNullOrEmpty(accountCheckCommand.Id)
                )
            {
                return(null);
            }

            var isCreationAllowed = await _licenseManager.EvaluateNewEntityAsync(accountCheckCommand);

            if (isCreationAllowed)
            {
                accountCheckCommand.SetApproval();
            }
            else
            {
                accountCheckCommand.SetDenial();
            }

            var approvedEntity = await _approvalsService.CreateApprovalAsync(
                accountCheckCommand.ToApprovalEntity()
                );

            if (approvedEntity != null)
            {
                var accountIsCheckedEvent = approvedEntity.ToAccountModel <AccountIsCheckedEvent>(accountCheckCommand);
                await _publishEndpoint.Publish(accountIsCheckedEvent);

                return(accountIsCheckedEvent);
            }

            return(null);
        }
        public async Task <ActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userEvent = new CreateUserEvent
                {
                    Name     = model.Name,
                    Username = model.Username,
                    Password = model.Password
                };

                try
                {
                    await _publishEndpoint.Publish <CreateUserEvent>(userEvent);

                    return(RedirectToAction(nameof(Index), new { success = true }));
                }
                catch
                {
                    ModelState.AddModelError(string.Empty, "Error - Create User Event Publish");
                }
            }

            return(View(model));
        }
Beispiel #5
0
        public async Task <ActionResult> Create(CreateOrderViewModel model)
        {
            if (ModelState.IsValid)
            {
                var filteredProducts = model.Products.Where(p => p.Amount > 0).ToList();
                var orderEvent       = new CreateOrderEvent
                {
                    UserId   = model.UserId,
                    Products = filteredProducts.Select(p => new CreateOrderEvent.CreateOrderEventProductDto(p.Id, p.Amount)).ToList()
                };

                try
                {
                    await _publishEndpoint.Publish <CreateOrderEvent>(orderEvent);

                    return(RedirectToAction(nameof(Index), new { success = true }));
                }
                catch
                {
                    ModelState.AddModelError(string.Empty, "Error - Create Order Event Publish");
                }
            }

            model.SetUserList(await _orderService.GetUsersAsync());
            model.SetProductList(await _orderService.GetProductsAsync());
            return(View(model));
        }
        public async Task <ActionResult> Create(CreateProductViewModel model)
        {
            if (ModelState.IsValid)
            {
                var productEvent = new CreateProductEvent
                {
                    Name   = model.Name,
                    Amount = model.Amount,
                    Price  = model.Price
                };

                try
                {
                    await _publishEndpoint.Publish <CreateProductEvent>(productEvent);

                    return(RedirectToAction(nameof(Index), new { success = true }));
                }
                catch
                {
                    ModelState.AddModelError(string.Empty, "Error - Create Product Event Publish");
                }
            }

            return(View(model));
        }
Beispiel #7
0
        public async Task <IActionResult> TriggerFirstMessage()
        {
            var message = new FirstMessage();
            await _publishEndpoint.Publish(message);

            return(Ok());
        }
Beispiel #8
0
        public async Task <TransactionDto?> CreateNewTransactionAsync(ITransactionModel transactionModel)
        {
            if (
                string.IsNullOrEmpty(transactionModel.ProfileId) ||
                transactionModel.AccountId == Guid.Empty.ToString() ||
                !await _licenseManager.EvaluateNewEntityAsync(transactionModel)
                )
            {
                return(null);
            }

            // Optimistic Concurrency Control: set the sequential number
            var sequencedTransaction = await _concurrencyManager.SetNextSequentialNumber(transactionModel);

            var newTransaction = await _transactionsService.CreateTransactionAsync(
                sequencedTransaction.ToTransactionEntity()
                );

            if (newTransaction != null)
            {
                await _publishEndpoint.Publish(newTransaction.ToTransactionModel <TransactionCreatedEvent>());

                await _publishEndpoint.Publish(newTransaction.ToTransactionModel <TransactionCheckCommand>());

                return(newTransaction.ToTransactionModel <TransactionDto>());
            }

            return(null);
        }
        public async void Created(Booking booking)
        {
            var contract = _mapper.Map <BookingCreatedContract>(booking);

            contract.ItemNo = booking.Id;
            await _publishEndpoint.Publish <IBookingCreated>(contract);

            _logger.Information("Event: Created published, with name: {ItemName} and id: {Id}", contract.ItemName, contract.Id);
        }
        public async Task <IActionResult> AddManyAsync([FromBody, Required] IEnumerable <StudentOpticalForm> forms)
        {
            await _opticalFormRepository.DeleteManyAsync(forms);

            await _opticalFormRepository.AddManyAsync(forms);

            await _publishEndpoint.Publish(new EvaluateExam(forms.First().ExamId));

            return(Ok());
        }
Beispiel #11
0
 private async Task Publish <TEvent>(TEvent evt, Type type) where TEvent : Event
 {
     if (type == null)
     {
         await _publishEndpoint.Publish(evt);
     }
     else
     {
         await _publishEndpoint.Publish(evt, type);
     }
 }
        public async void Deleted(int Id, string ItemNo)
        {
            var contract = new ItemEntityDeleted {
                Id = Id, ItemNo = ItemNo
            };
            //await _bus.Publish<ItemEntityDeleted>(contract);
            await _publishEndpoint.Publish <IItemEntityDeleted>(contract);

            _logger.Information("ItemManagerService - Publishing ItemEntityDeleted events with Id: {Id}, ItemNo: {ItemNo}",
                                Id, ItemNo);
        }
Beispiel #13
0
 public async Task <HttpResponseMessage> Register(HttpRequestMessage request, UserInput userInput)
 {
     return(await _apiHelper.CreateHttpResponse <string>(request, async() =>
     {
         var Id = await _userAppService.Register(userInput);
         if (!string.IsNullOrWhiteSpace(Id))
         {
             await _publishEndpoint.Publish <UserRegisted>(new { Id = Id, UserName = userInput.UserName });
         }
         return Id;
     }));
 }
        public async Task <DefaultResponse> Handle(StartSagaSampleCommand request, CancellationToken cancellationToken)
        {
            var @event = new SagaStartedEvent()
            {
                ItemId    = request.ItemId,
                Timestamp = DateTime.Now,
                Text      = request.TextRequest
            };
            await _publishEndpoint.Publish(@event);

            return(DefaultResponse.Success());
        }
Beispiel #15
0
        public async Task Execute(BehaviorContext <OrderState> context, Behavior <OrderState> next)
        {
            await Console.Out.WriteLineAsync(
                $"Publishing Order Event Created: {context.Instance.CorrelationId} ({context.GetPayload<ConsumeContext>().ConversationId})");

            await _publishEndpoint.Publish <OrderStateCreated>(new
            {
                OrderId   = context.Instance.CorrelationId,
                Timestamp = DateTime.UtcNow
            }, sendContext => sendContext.CorrelationId = NewId.NextGuid());

            await next.Execute(context);
        }
Beispiel #16
0
 private void PublishItemCreatedEvent(SaveParticipantLibraryItemCommand saveParticipantLibraryItemCommand)
 {
     _publishEndpoint.Publish <IParticipantLibraryItemCreated>(new ParticipantLibraryItemCreated
     {
         NexusKey    = saveParticipantLibraryItemCommand.NexusKey,
         DisplayCode = saveParticipantLibraryItemCommand.DisplayCode,
         Iso2Code    = saveParticipantLibraryItemCommand.Iso2Code,
         Iso3Code    = saveParticipantLibraryItemCommand.Iso3Code,
         Name        = saveParticipantLibraryItemCommand.Name,
         DisplayName = saveParticipantLibraryItemCommand.DisplayName,
         TypeKey     = saveParticipantLibraryItemCommand.TypeKey,
     });
 }
Beispiel #17
0
        public Task Publish <T>(object values, CancellationToken cancellationToken = default) where T : class
        {
            if (Transaction.Current == null)
            {
                return(_publishEndpoint.Publish(values, cancellationToken));
            }

            var pendingActions = _pendingActions.GetOrAdd(Transaction.Current, new TransactionOutboxEnlistment(_loggerFactory));

            pendingActions.Add(() => _publishEndpoint.Publish(values, cancellationToken));

            return(Task.CompletedTask);
        }
 public async Task<IActionResult> CrearProceso([FromBody] Proceso proceso)
 {
     var procesoProgreso = new
     {
         IdEmpresa = proceso.IdEmpresa,
         IdNomina = proceso.IdNomina,
         IdProceso = proceso.Tipo,
         TotalRegistros = proceso.Cantidad
     };
     await _publicador.Publish<ICrearProcesoProgreso>(procesoProgreso);
     CrearNotificacionesProgreso(procesoProgreso);
     return Ok(procesoProgreso);
 }
Beispiel #19
0
        public async Task Publish(IPublishEndpoint endpoint, TInput input, IPipe <PublishContext> pipe, CancellationToken cancellationToken)
        {
            InitializeMessageContext <TMessage, TInput> messageContext = await InitializeMessage(input, cancellationToken).ConfigureAwait(false);

            if (_headerInitializers.Length > 0)
            {
                await endpoint.Publish(messageContext.Message, new InitializerPublishContextPipe(_headerInitializers, messageContext, pipe), cancellationToken)
                .ConfigureAwait(false);
            }
            else
            {
                await endpoint.Publish(messageContext.Message, pipe, cancellationToken).ConfigureAwait(false);
            }
        }
Beispiel #20
0
        public async Task <ActionResult <ItemDTO> > PostAsync([FromBody] CreateItemContract createItemContract)
        {
            var item = new Item
            {
                Name        = createItemContract.Name,
                Description = createItemContract.Description,
                Price       = createItemContract.Price,
                CreatedDate = DateTimeOffset.UtcNow
            };
            await _itemsRepository.CreateAsync(item);

            await _publishEndpoint.Publish(new CatalogItemCreatedContract(item.Id, item.Name, item.Description));

            return(CreatedAtAction(nameof(GetByIdAsync), new { id = item.Id }, item));
        }
        public async Task <ActionResult <ItemDto> > PostAsync(CreateItemDto createItemDto)
        {
            var item = new Item
            {
                Name        = createItemDto.Name,
                Description = createItemDto.Description,
                Price       = createItemDto.Price,
                CreatedDate = DateTimeOffset.UtcNow
            };
            await itemsRepository.CreateAsync(item);

            await publishEndpoint.Publish(new CatalogItemCreated(item.Id, item.Name, item.Description));

            return(CreatedAtAction(nameof(GetByIdAsync), new { id = item.Id }, item));
        }
        public async Task Consume(ConsumeContext <SubmitOrderRequest> context)
        {
            _logger.LogInformation("Received Order {OrderId} at {OrderDate}", context.Message.OrderId, context.Message.OrderDate);

            // await generate/submit order

            //publish/broadcast an event that order submitted successfully
            await _publishEndpoint.Publish <OrderSubmittedEvent>(new
            {
                context.Message.OrderId,
                context.Message.OrderDate,
                context.Message.CustomerNumber,
                context.Message.OrderTotal,
                OrderStatus = "Submitted"
            });

            //caller expects a response
            //mass transit can do both patterns i.e fire and forget and respond, however it is generally not recommended to do both in a consumer
            if (context.RequestId != null)
            {
                await context.RespondAsync <SubmitOrderResponse>(new
                {
                    Ack         = true,
                    OrderStatus = "Submitted"
                });
            }
        }
Beispiel #23
0
        protected async Task <Guid> LoadBlob(IPublishEndpoint endpoint, Guid userId, string bucket, string fileName, string contentType = "application/octet-stream", IDictionary <string, object> metadata = null)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", fileName);

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            var blobId = await _blobStorage.AddFileAsync(fileName, File.OpenRead(path), contentType, bucket, metadata);

            var blobInfo = await _blobStorage.GetFileInfo(blobId, bucket);

            await endpoint.Publish <BlobLoaded>(new
            {
                //CorrelationId = blobInfo.Metadata != null ? blobInfo.Metadata.ContainsKey("correlationId") ? new Guid(blobInfo.Metadata["correlationId"].ToString()) : Guid.Empty,
                BlobInfo  = new LoadedBlobInfo(blobId, fileName, blobInfo.Length, userId, blobInfo.UploadDateTime, blobInfo.MD5, bucket, blobInfo.Metadata),
                TimeStamp = DateTimeOffset.UtcNow
            });

            //Thread.Sleep(100);

            Log.Debug($"BlobLoaded: {fileName}; BlobId: {blobId}");

            return(blobId);
        }
        public async Task Consume(ConsumeContext <EditProductEvent> context)
        {
            _logger.LogInformation($"Processing msg: '{context.MessageId}' with topic: '{context.ConversationId}'.");

            try
            {
                var product = context.Message;

                var dbProduct = await _applicationDbContext.Products.FirstOrDefaultAsync(x => x.Id == product.Id);

                if (dbProduct == null)
                {
                    throw new ApplicationException("Product not found");
                }

                dbProduct.Name   = product.Name;
                dbProduct.Price  = product.Price;
                dbProduct.Amount = product.Amount;

                await _applicationDbContext.SaveChangesAsync();

                _logger.LogInformation($"Edited product with ID {dbProduct.Id} and name {dbProduct.Name}");

                await _publishEndpoint.Publish(new ProductEditedEvent
                {
                    Id     = dbProduct.Id,
                    Name   = dbProduct.Name,
                    Amount = dbProduct.Amount,
                    Price  = dbProduct.Price
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(default, ex, ex.Message);
Beispiel #25
0
        async public Task <OperationResult <List <TemplateModel> > > GetAll()
        {
            var productRepository           = _sqlUnitOfWork.GetRepository <ITempateSQLServerRepository>();
            List <TestMessageResponse> list = new List <TestMessageResponse>();

            for (var index = 0; index <= 10; index++)
            {
                await _publishEndpoint.Publish(new TestMessagePublish
                {
                    Id    = Guid.NewGuid(),
                    Text  = "TestText",
                    Value = 5
                });
            }


            for (var index = 0; index <= 10; index++)
            {
                var result = await _client.GetResponse <OperationResult <TestMessageResponse> >(new TestMessageRequest { Text = index.ToString() });

                list.Add(result.Message.Data);
            }

            return(productRepository.Get());
        }
Beispiel #26
0
        public async Task Consume(ConsumeContext <UserCheckoutAcceptedIntegrationEvent> context)
        {
            IExecutionResult result = ExecutionResult.Failed();
            var orderId             = OrderId.New;

            // Send Integration event to clean basket once basket is converted to Order and before starting with the order creation process
            var orderItems = from orderItem in context.Message.Basket.Items
                             select new OrderStockItem(int.Parse(orderItem.ProductId), orderItem.Quantity);

            if (context.Message.RequestId != Guid.Empty)
            {
                var createOrderCommand = new CreateOrderCommand(orderId, new SourceId(context.Message.RequestId.ToString()), context.Message.Basket.Items, context.Message.UserId, context.Message.UserName, context.Message.City, context.Message.Street,
                                                                context.Message.State, context.Message.Country, context.Message.ZipCode,
                                                                context.Message.CardNumber, context.Message.CardHolderName, context.Message.CardExpiration,
                                                                context.Message.CardSecurityNumber, context.Message.CardTypeId);

                result = await _commandBus.PublishAsync(createOrderCommand, CancellationToken.None).ConfigureAwait(false);

                if (result.IsSuccess)
                {
                    var orderStartedIntegrationEvent = new OrderStartedIntegrationEvent(context.Message.UserId, orderId.Value, orderItems.ToList(), context.Message.RequestId);
                    await _endpoint.Publish(orderStartedIntegrationEvent);
                }
            }
        }
        public async Task <ActionResult <Purchase> > Add(PurchaseRequest request)
        {
            try
            {
                int userId   = int.Parse(User.Claims.FirstOrDefault(x => x.Type == "id")?.Value ?? "-1");
                var purchase = await _service.AddAsync(userId, request);

                var storePurchase = new StorePurchase
                {
                    Date             = purchase.TimeOfPurchase,
                    UserId           = userId,
                    PurchaseProducts = purchase.ReceiptPositions.Select(x => new PurchaseProduct
                    {
                        Count = x.Count,
                        Name  = x.Product.ProductName,
                        Price = x.Product.Price
                    }).ToList()
                };
                await _endpoint.Publish(storePurchase);

                return(Ok(purchase));
            }
            catch (ApiException e)
            {
                return(BadRequest(new ProblemDetails {
                    Detail = e.Message
                }));
            }
        }
Beispiel #28
0
        public async Task <IActionResult> Checkout([FromBody] BasketCheckout basketCheckout)
        {
            // get existing basket with total price
            // Set TotalPrice on basketCheckout eventMessage
            // send checkout event to rabbitmq
            // remove the basket

            // get existing basket with total price
            var basket = await _repository.GetBasket(basketCheckout.UserName);

            if (basket == null)
            {
                return(BadRequest());
            }

            // send checkout event to rabbitmq
            var eventMessage = _mapper.Map <BasketCheckoutEvent>(basketCheckout);

            eventMessage.TotalPrice = basket.TotalPrice;
            await _publishEndpoint.Publish <BasketCheckoutEvent>(eventMessage);

            // remove the basket
            await _repository.DeleteBasket(basket.UserName);

            return(Accepted());
        }
        public async Task <IActionResult> CreateOrder([FromBody] Order order)
        {
            order.OrderStatus = OrderStatus.Preparing;
            order.OrderDate   = DateTime.UtcNow;

            _logger.LogInformation(" testing ");

            _logger.LogInformation(" In Create Order");
            _logger.LogInformation(" Order" + order.UserName);


            _ordersContext.Orders.Add(order);
            _ordersContext.OrderItems.AddRange(order.OrderItems);

            _logger.LogInformation(" Order added to context");
            _logger.LogInformation(" Saving........");
            try
            {
                await _ordersContext.SaveChangesAsync();

                _logger.LogWarning("BuyerId is: " + order.BuyerId);

                _bus.Publish(new OrderCompletedEvent(order.BuyerId)).Wait();
                return(Ok(new { order.OrderId }));
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError("An error occored during Order saving .." + ex.Message);
                return(BadRequest());
            }
        }
Beispiel #30
0
        public async Task <ActionResult <ItemDTO> > Post(CreateItemDTO createItemDTO)
        {
            var item = new Items
            {
                Name        = createItemDTO.Name,
                Description = createItemDTO.Description,
                Price       = createItemDTO.Price,
                CreatedDate = DateTimeOffset.UtcNow
            };

            await _itemsRepository.Create(item);

            await _publishEndpoint.Publish(new CatalogItemCreated(item.Id, item.Name, item.Description));

            return(CreatedAtAction(nameof(GetById), new { id = item.Id }, item));
        }