Exemple #1
0
        protected async Task SendRequest(BehaviorContext <TInstance> context, ConsumeContext consumeContext, TRequest requestMessage)
        {
            var pipe = new SendRequestPipe(consumeContext.ReceiveContext.InputAddress);

            var endpoint = await consumeContext.GetSendEndpoint(_request.Settings.ServiceAddress).ConfigureAwait(false);

            await endpoint.Send(requestMessage, pipe).ConfigureAwait(false);

            _request.SetRequestId(context.Instance, pipe.RequestId);

            if (_request.Settings.Timeout > TimeSpan.Zero)
            {
                var now            = DateTime.UtcNow;
                var expirationTime = now + _request.Settings.Timeout;

                RequestTimeoutExpired message = new TimeoutExpired(now, expirationTime, context.Instance.CorrelationId, pipe.RequestId);

                MessageSchedulerContext schedulerContext;
                if (_request.Settings.SchedulingServiceAddress != null)
                {
                    var scheduleEndpoint = await consumeContext.GetSendEndpoint(_request.Settings.SchedulingServiceAddress).ConfigureAwait(false);

                    await scheduleEndpoint.ScheduleSend(consumeContext.ReceiveContext.InputAddress, expirationTime, message).ConfigureAwait(false);
                }
                else if (consumeContext.TryGetPayload(out schedulerContext))
                {
                    await schedulerContext.ScheduleSend(expirationTime, message).ConfigureAwait(false);
                }
                else
                {
                    throw new ConfigurationException("A request timeout was specified but no message scheduler was specified or available");
                }
            }
        }
        public async Task Consume(ConsumeContext <CreateJobsCommand> context)
        {
            var redisDB = _connectionMultiplexer.GetDatabase(_redisOptions.Database);

            /// the reason we don't use the in-memory inbox is because for use we process thousands of jobs
            /// if the process fails, then we start all over again and lose any processing
            /// instead, we keep track of jobs that we've enqueued in a redis set
            /// if something goes wrong, we can skip what we've already processed
            /// choice is yours though how to go. your mileage may vary
            /// also, I have fud over what guarantees the inbox offers

            var alreadyEnqueued = (await redisDB.SetMembersAsync($"{context.Message.CorrelationId}:JobList").ConfigureAwait(false))
                                  .Select(m => (string)m)
                                  .ToHashSet();
            var jobs = alreadyEnqueued.Any()
                ? context.Message.Jobs.Where(j => !alreadyEnqueued.Contains(j)).ToArray()
                : context.Message.Jobs;

            _logger.LogInformation("Enqueuing jobs");
            var doJobEndpoint = await context.GetSendEndpoint(new Uri("loopback://localhost/do_job")).ConfigureAwait(false);

            foreach (var job in jobs)
            {
                /// if we want, we can add all items before we start
                /// we add the job id before enqueuing the job to prevent cases where the job finishes be we add it to the queue
                /// in this case, the id will never get removed and we would be stuck in limbo
                await redisDB.SetAddAsync($"{context.Message.CorrelationId}:JobList", job).ConfigureAwait(false);

                //_logger.LogInformation("Enqueued: {Job}", job);
                await doJobEndpoint.Send(new DoJobCommand
                {
                    CorrelationId = context.Message.CorrelationId,
                    Job           = job,
                }).ConfigureAwait(false);
            }
            _logger.LogInformation("All jobs enqueued");

            _logger.LogInformation("Starting job tracker");
            /// no need to check immediately. let's give it some time
            var trackJobsEndpoint = await context.GetSendEndpoint(new Uri("loopback://localhost/quartz")).ConfigureAwait(false);

            await trackJobsEndpoint.ScheduleSend(new Uri("loopback://localhost/track_jobs"), TimeSpan.FromSeconds(2), new TrackJobsCommand
            {
                CorrelationId = context.Message.CorrelationId,
            }).ConfigureAwait(false);

            _logger.LogInformation("tracker started");
        }
Exemple #3
0
        public async Task Consume(ConsumeContext <IRegisterOrderCommand> context)
        {
            var result = context.Message;

            if (result.OrderId != null)
            {
                SaveOrder(result);
                await _hubConntext.Clients.All.SendAsync("UpdateOrders", "New order created", result.OrderId);

                var client = _clientFactory.CreateClient();
                Tuple <List <byte[]>, Guid> orderDetailData = await GetFacesFromFaceApiAsync(client, result.ImageData, result.OrderId);

                List <byte[]> faces   = orderDetailData.Item1;
                Guid          orderId = orderDetailData.Item2;

                SaveOrderDetails(orderId, faces);
                await _hubConntext.Clients.All.SendAsync("UpdateOrders", "Order processedd", result.OrderId);

                var sendToUri = new Uri($"{RabbitMqMassiveTransitConstants.RabbitMqUri }/" +
                                        $"{RabbitMqMassiveTransitConstants.NotificationServiceQueue}");

                var endPoint = await context.GetSendEndpoint(sendToUri);

                await endPoint.Send <IOrderProcessedEvent>(
                    new
                {
                    context.Message.OrderId,
                    faces,
                    context.Message.Email
                });
            }
        }
        public async Task Consume(ConsumeContext <ProceedBeautifiedPoem> context)
        {
            Console.WriteLine("Poem filtering completed");
            bool isPoemSaved = false;

            try
            {
                _storage.Save(context.Message.UserId, context.Message.CorrId, string.Join("\n", context.Message.Poem));
                isPoemSaved = true;
            }
            catch (Exception)
            {
            }

            if (!isPoemSaved)
            {
                Console.WriteLine("Failed to save poem to database");

                Uri sendEndpointUri = new Uri(string.Concat(ConfigurationManager.AppSettings["RabbitMQHost"], ConfigurationManager.AppSettings["PoemBeatifierManagerQueueName"]));
                var endpoint        = await context.GetSendEndpoint(sendEndpointUri);

                await endpoint.Send <RejectPoem>(new
                {
                    CorrId = context.Message.CorrId,
                });
            }
            else
            {
                await Task.FromResult(1);
            }
        }
        public async Task Consume(ConsumeContext <RoutingSlipFaulted> context)
        {
            var request   = context.Message.GetVariable <TRequest>("Request");
            var requestId = context.Message.GetVariable <Guid>("RequestId");

            Uri responseAddress = null;

            if (context.Message.Variables.ContainsKey("FaultAddress"))
            {
                responseAddress = context.Message.GetVariable <Uri>("FaultAddress");
            }
            if (responseAddress == null && context.Message.Variables.ContainsKey("ResponseAddress"))
            {
                responseAddress = context.Message.GetVariable <Uri>("ResponseAddress");
            }

            if (responseAddress == null)
            {
                throw new ArgumentException($"The response address could not be found for the faulted routing slip: {context.Message.TrackingNumber}");
            }

            var endpoint = await context.GetSendEndpoint(responseAddress).ConfigureAwait(false);

            var response = await CreateFaultedResponseMessage(context, request, requestId);

            await endpoint.Send(response, x => x.RequestId = requestId)
            .ConfigureAwait(false);
        }
Exemple #6
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="endpointAddress"></param>
        /// <param name="message">The message</param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri endpointAddress, T message)
            where T : class
        {
            ISendEndpoint endpoint = await context.GetSendEndpoint(endpointAddress).ConfigureAwait(false);

            await endpoint.Send(message, context.CancellationToken).ConfigureAwait(false);
        }
        public async Task Consume(ConsumeContext <RoutingSlipFaulted> context)
        {
            var request   = context.Message.GetVariable <TRequest>("Request");
            var requestId = context.Message.GetVariable <Guid>("RequestId");

            Uri responseAddress = null;

            if (context.Message.Variables.ContainsKey("FaultAddress"))
            {
                responseAddress = context.Message.GetVariable <Uri>("FaultAddress");
            }
            if (responseAddress == null && context.Message.Variables.ContainsKey("ResponseAddress"))
            {
                responseAddress = context.Message.GetVariable <Uri>("ResponseAddress");
            }

            if (responseAddress == null)
            {
                throw new ArgumentException($"The response address could not be found for the faulted routing slip: {context.Message.TrackingNumber}");
            }

            var endpoint = await context.GetSendEndpoint(responseAddress).ConfigureAwait(false);

            ActivityException[] exceptions = context.Message.ActivityExceptions;

            await endpoint.Send <Fault <TRequest> >(new FaultEvent <TRequest>(request, requestId, context.Host, exceptions.Select(x => x.ExceptionInfo)),
                                                    x => x.RequestId = requestId)
            .ConfigureAwait(false);
        }
        async Task Execute(BehaviorContext <TInstance> context)
        {
            ConsumeContext consumeContext = context.CreateConsumeContext();

            Guid?requestId = _request.GetRequestId(context.Instance);

            if (requestId.HasValue && _request.Settings.Timeout > TimeSpan.Zero)
            {
                MessageSchedulerContext schedulerContext;
                if (_request.Settings.SchedulingServiceAddress != null)
                {
                    var scheduleEndpoint = await consumeContext.GetSendEndpoint(_request.Settings.SchedulingServiceAddress).ConfigureAwait(false);

                    await scheduleEndpoint.CancelScheduledSend(requestId.Value).ConfigureAwait(false);
                }
                else if (consumeContext.TryGetPayload(out schedulerContext))
                {
                    await schedulerContext.CancelScheduledSend(consumeContext.ReceiveContext.InputAddress, requestId.Value).ConfigureAwait(false);
                }
                else
                {
                    throw new ConfigurationException("A scheduler was not available to cancel the scheduled request timeout");
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="endpointAddress"></param>
        /// <param name="values"></param>
        /// <param name="pipe"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri endpointAddress, object values, IPipe <SendContext> pipe)
            where T : class
        {
            ISendEndpoint endpoint = await context.GetSendEndpoint(endpointAddress).ConfigureAwait(false);

            await endpoint.Send <T>(values, pipe, context.CancellationToken).ConfigureAwait(false);
        }
        /// <summary>
        /// Deletes the scheduled message with the specified group and name.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="groupName"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static async Task DeleteSchedule(
            this ConsumeContext context,
            string groupName,
            string name)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (groupName == null)
            {
                throw new ArgumentNullException(nameof(groupName));
            }
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            // endpoint of scheduler
            var i = await context.GetSendEndpoint(new Uri(context.ReceiveContext.InputAddress, "/scheduler"));

            if (i == null)
            {
                throw new InvalidOperationException("Could not resolve scheduler endpoint.");
            }

            await i.Send(new DeleteSchedule()
            {
                GroupName = groupName,
                Name      = name,
            });
        }
Exemple #11
0
        public static async Task Forward <T>(this ConsumeContext context, Uri address, T message)
            where T : class
        {
            var endpoint = await context.GetSendEndpoint(address).ConfigureAwait(false);

            await Forward(context, endpoint, message).ConfigureAwait(false);
        }
Exemple #12
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="destinationAddress"></param>
        /// <param name="message">The message</param>
        /// <param name="pipe"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri destinationAddress, T message, IPipe <SendContext> pipe)
            where T : class
        {
            var endpoint = await context.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send(message, pipe, context.CancellationToken).ConfigureAwait(false);
        }
Exemple #13
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="destinationAddress"></param>
        /// <param name="values"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri destinationAddress, object values)
            where T : class
        {
            var endpoint = await context.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send <T>(values, context.CancellationToken).ConfigureAwait(false);
        }
        /// <summary>
        /// Prepare for game
        /// - Guesses
        /// - GuessedWord
        /// - WordLeft
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public async Task Consume(ConsumeContext <SetupProcessing> ctx)
        {
            var msg = ctx.Message;

            var ep = await ctx.GetSendEndpoint(rmqConfig.GetEndpoint(Queues.GameSaga));

            using (var scope = logger.BeginScope($"CorrelationId={msg.CorrelationId}"))
            {
                var word = msg.Word.ToLowerInvariant();

                var game = await dbContext.GameSagas.Find(x => x.CorrelationId == msg.CorrelationId)
                           .FirstAsync();

                game.Word     = word;
                game.WordLeft = word;

                game.GuessedWord = Enumerable.Range(0, word.Length)
                                   .Select(x => '-')
                                   .ToArray();

                game.Guesses = new List <char>();

                await dbContext.GameSagas.ReplaceOneAsync(x => x.CorrelationId == game.CorrelationId, game);

                logger.LogInformation("Processing setup done");

                await ep.Send(new ProcessingSetup
                {
                    CorrelationId = msg.CorrelationId,
                    GuessedWord   = string.Join("", game.GuessedWord)
                });
            }
        }
Exemple #15
0
        public async Task Consume(ConsumeContext <IDownloadPackage> context)
        {
            var conversationEnricher    = new PropertyEnricher(nameof(context.ConversationId), context.ConversationId);
            var archiveRecordIdEnricher = new PropertyEnricher(nameof(context.Message.ArchiveRecordId), context.Message.ArchiveRecordId);
            var packageIdEnricher       = new PropertyEnricher(nameof(context.Message.PackageId), context.Message.PackageId);

            using (LogContext.Push(conversationEnricher, archiveRecordIdEnricher, packageIdEnricher))
            {
                Log.Information("Received {CommandName} command with conversationId {ConversationId} from the bus", nameof(IDownloadPackage),
                                context.ConversationId);

                // Get the package from the repository
                // We are not waiting for it to end, because we want to free the consumer as early as possible
                var packageId       = context.Message.PackageId;
                var archiveRecordId = context.Message.ArchiveRecordId;
                var result          = await repositoryManager.GetPackage(packageId, archiveRecordId, context.Message.PrimaerdatenAuftragId);

                // Do we have a valid package?
                if (result.Success && result.Valid)
                {
                    // Forward the downloaded package to the asset manager for transformation
                    var endpoint = await context.GetSendEndpoint(new Uri(bus.Address, BusConstants.AssetManagerPrepareForTransformation));

                    await endpoint.Send(new PrepareForTransformationMessage
                    {
                        AssetType             = AssetType.Gebrauchskopie,
                        CallerId              = context.Message.CallerId,
                        RetentionCategory     = context.Message.RetentionCategory,
                        Recipient             = context.Message.Recipient,
                        Language              = context.Message.Language,
                        ProtectWithPassword   = context.Message.RetentionCategory != CacheRetentionCategory.UsageCopyPublic,
                        PrimaerdatenAuftragId = context.Message.PrimaerdatenAuftragId,
                        RepositoryPackage     = result.PackageDetails
                    });

                    // also publish the event, that the package is downloaded
                    await context.Publish <IPackageDownloaded>(
                        new
                    {
                        PackageInfo = result
                    });
                }
                else
                {
                    // Publish the download asset failure event
                    await context.Publish <IAssetReady>(new AssetReady
                    {
                        Valid                 = false,
                        ErrorMessage          = result.ErrorMessage,
                        AssetType             = AssetType.Gebrauchskopie,
                        CallerId              = context.Message.CallerId,
                        ArchiveRecordId       = context.Message.ArchiveRecordId,
                        RetentionCategory     = context.Message.RetentionCategory,
                        Recipient             = context.Message.Recipient,
                        PrimaerdatenAuftragId = context.Message.PrimaerdatenAuftragId
                    });
                }
            }
        }
        public async Task Consume(ConsumeContext <PaymentAcceptedEvent> context)
        {
            var sendEndpoint = await context.GetSendEndpoint(createBaseCoffeeEndpoint);

            await sendEndpoint.Send <CreateBaseCoffeeCommand>(new { this.CorrelationId, CoffeeType = this.CoffeeTypeRequested, NoTopping = string.IsNullOrWhiteSpace(this.ToppingsRequested) });

            this.State = "Paid";
        }
        public async Task Consume(ConsumeContext <IAmlValidationEvent> context)
        {
            AmlDataAccess amlDataAccess = new AmlDataAccess();
            var           remitterData  = context.Message;

            if (remitterData.RemitterFirstName.Contains("modi"))
            {
                amlDataAccess.SaveData(new Models.AmlData
                {
                    AmlStatus    = "Block",
                    CountryName  = remitterData.RemitterCountry,
                    CustomerName = String.Format($"{remitterData.RemitterFirstName} {remitterData.RemitterLastName}"),
                    RemitterID   = remitterData.RemitterID
                });
                var endpoint = await context.GetSendEndpoint(new Uri("queue:" + BusConfiguration.AmlQueueName));

                await endpoint.Send <IAmlData>(new
                {
                    RemitterID = remitterData.RemitterID,
                    AmlStatus  = "Block",
                });

                await Task.FromResult(true);
            }
            else
            {
                amlDataAccess.SaveData(new Models.AmlData
                {
                    AmlStatus    = "Allow",
                    CountryName  = remitterData.RemitterCountry,
                    CustomerName = String.Format($"{remitterData.RemitterFirstName} {remitterData.RemitterLastName}"),
                    RemitterID   = remitterData.RemitterID
                });
                var endpoint = await context.GetSendEndpoint(new Uri("queue:" + BusConfiguration.AmlQueueName));

                await endpoint.Send <IAmlData>(new
                {
                    RemitterID = remitterData.RemitterID,
                    AmlStatus  = "Allow",
                });

                await Task.FromResult(true);
            }
            await Task.FromResult(false);
        }
        /// <summary>
        ///     Consumes the specified message from the bus.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>Task.</returns>
        public async Task Consume(ConsumeContext <IUpdateArchiveRecord> context)
        {
            var currentStatus = AufbereitungsStatusEnum.OCRAbgeschlossen;

            using (LogContext.PushProperty(nameof(context.ConversationId), context.ConversationId))
            {
                Log.Information("Received {CommandName} command with conversationId {ConversationId} from the bus", nameof(IUpdateArchiveRecord),
                                context.ConversationId);

                try
                {
                    indexManager.UpdateArchiveRecord(context);
                    Log.Information($"Updated archive record {context.Message.ArchiveRecord.ArchiveRecordId} in elastic index.");

                    currentStatus = AufbereitungsStatusEnum.IndizierungAbgeschlossen;
                    await UpdatePrimaerdatenAuftragStatus(context, AufbereitungsServices.IndexService, currentStatus);

                    // update the individual tokens for download and access
                    // these tokens need to be updated even if the record has no primary data.
                    // Use case: Ö2 user asks for Einsichtsgesuch. It gets approved, but record may not (yet) have primary data.
                    var ep = await context.GetSendEndpoint(new Uri(context.SourceAddress, BusConstants.RecalcIndivTokens));

                    await ep.Send(new RecalcIndivTokens
                    {
                        ArchiveRecordId = Convert.ToInt32(context.Message.ArchiveRecord.ArchiveRecordId),
                        ExistingMetadataAccessTokens            = context.Message.ArchiveRecord.Security.MetadataAccessToken.ToArray(),
                        ExistingPrimaryDataDownloadAccessTokens = context.Message.ArchiveRecord.Security.PrimaryDataDownloadAccessToken.ToArray(),
                        ExistingPrimaryDataFulltextAccessTokens = context.Message.ArchiveRecord.Security.PrimaryDataFulltextAccessToken.ToArray()
                    });

                    Log.Information(
                        $"Recalculated and updated individual tokens for archive record {context.Message.ArchiveRecord.ArchiveRecordId} in elastic index.");

                    await context.Publish <IArchiveRecordUpdated>(new
                    {
                        context.Message.MutationId,
                        context.Message.ArchiveRecord.ArchiveRecordId,
                        ActionSuccessful = true,
                        context.Message.PrimaerdatenAuftragId
                    });
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to update archiveRecord with conversationId {ConversationId} in Elastic or SQL", context.ConversationId);
                    await context.Publish <IArchiveRecordUpdated>(new
                    {
                        context.Message.MutationId,
                        context.Message.ArchiveRecord.ArchiveRecordId,
                        ActionSuccessful = false,
                        context.Message.PrimaerdatenAuftragId,
                        ErrorMessage = ex.Message,
                        ex.StackTrace
                    });
                    await UpdatePrimaerdatenAuftragStatus(context, AufbereitungsServices.IndexService, currentStatus, ex.Message);
                }
            }
        }
Exemple #19
0
        public async Task Consume(ConsumeContext <IArchiveRecordExtractFulltextFromPackage> context)
        {
            using (LogContext.PushProperty(nameof(context.ConversationId), context.ConversationId))
            {
                Log.Information("Received {CommandName} command with conversationId {ConversationId} from the bus",
                                nameof(IArchiveRecordExtractFulltextFromPackage), context.ConversationId);

                // Process the package and extract the full text
                var mutationId            = context.Message.MutationId;
                var archiveRecord         = context.Message.ArchiveRecord;
                var primaerdatenAuftragId = context.Message.PrimaerdatenAuftragId;
                var success = await assetManager.ExtractFulltext(mutationId, archiveRecord, primaerdatenAuftragId);

                if (success)
                {
                    await UpdatePrimaerdatenAuftragStatus(context.Message, AufbereitungsServices.AssetService,
                                                          AufbereitungsStatusEnum.OCRAbgeschlossen);

                    // Put the final message on the queue for indexing.
                    // Important: use bus address here, because we are in SSZ and the original message comes
                    // from the BV-Zone
                    var ep = await context.GetSendEndpoint(new Uri(bus.Address, BusConstants.IndexManagerUpdateArchiveRecordMessageQueue));

                    await ep.Send <IUpdateArchiveRecord>(new
                    {
                        MutationId            = mutationId,
                        ArchiveRecord         = archiveRecord,
                        PrimaerdatenAuftragId = primaerdatenAuftragId
                    });

                    Log.Information("Put {CommandName} message on index queue with mutation ID: {MutationId}", nameof(IUpdateArchiveRecord),
                                    mutationId);
                }
                else
                {
                    // If package creation was not successful, stop syncing here and return failure.
                    Log.Error("Failed to extract fulltext for the supported file types for archiveRecord with conversationId {ConversationId}",
                              context.ConversationId);
                    var errorText = "Failed to extract fulltext. See log for further details.";
                    await UpdatePrimaerdatenAuftragStatus(context.Message, AufbereitungsServices.AssetService,
                                                          AufbereitungsStatusEnum.OCRAbgeschlossen, errorText);

                    await context.Publish <IArchiveRecordUpdated>(new
                    {
                        context.Message.MutationId,
                        context.Message.ArchiveRecord.ArchiveRecordId,
                        ActionSuccessful      = false,
                        PrimaerdatenAuftragId = primaerdatenAuftragId,
                        ErrorMessage          = errorText
                    });

                    Log.Information("Put {CommandName} message on index queue with mutation ID: {MutationId}", nameof(IArchiveRecordUpdated),
                                    mutationId);
                }
            }
        }
        async Task MessageRedeliveryContext.ScheduleRedelivery(TimeSpan delay)
        {
            var receiveSettings = _context.ReceiveContext.GetPayload <ReceiveSettings>();

            var delayExchangeAddress = GetDelayExchangeAddress(receiveSettings);

            ISendEndpoint delayEndpoint = await _context.GetSendEndpoint(delayExchangeAddress).ConfigureAwait(false);

            await delayEndpoint.Send(_context.Message, _context.CreateCopyContextPipe((x, y) => UpdateDeliveryContext(x, y, delay))).ConfigureAwait(false);
        }
Exemple #21
0
        public Task Consume(ConsumeContext <EmailContentCreated> context)
        {
            try
            {
                var userName  = Configuration.GetSection(Constants.SmtpSettings)[Constants.SmtpUserName];
                var password  = Configuration.GetSection(Constants.SmtpSettings)[Constants.SmtpPassword];
                var address   = Configuration.GetSection(Constants.SmtpSettings)[Constants.SmtpAddress];
                var port      = Configuration.GetSection(Constants.SmtpSettings)[Constants.SmtpPort];
                var enableSsl = Configuration.GetSection(Constants.SmtpSettings)[Constants.SmtpEnableSsl];

                var client = new SmtpClient(address, int.Parse(port))
                {
                    Credentials = new NetworkCredential(userName, password),
                    EnableSsl   = bool.Parse(enableSsl)
                };
                client.Send(context.Message.From, context.Message.To, context.Message.Subject, context.Message.Body);

                var sendEndPoint = context.GetSendEndpoint(new System.Uri(Configuration.GetConnectionString(Constants.RabbitMQHost) + "/" + EventRouteConstants.LoggingService)).Result;
                sendEndPoint.Send(new WriteLogEvent()
                {
                    Level   = LogLevel.Information.ToString(),
                    Logger  = typeof(EmailNotificationConsumer).FullName,
                    Message = "Email was sent!",
                    Thread  = ""
                });
            }
            catch (System.Exception ex)
            {
                var sendEndPoint = context.GetSendEndpoint(new System.Uri(Configuration.GetConnectionString(Constants.RabbitMQHost) + "/" + EventRouteConstants.LoggingService)).Result;
                sendEndPoint.Send(new WriteLogEvent()
                {
                    Level   = LogLevel.Error.ToString(),
                    Logger  = typeof(EmailNotificationConsumer).FullName,
                    Message = $"Failure sending mail. {ex.Message} {ex.InnerException.Message}",
                    Thread  = "",
                    Data    = JsonConvert.SerializeObject(context.Message)
                });
                throw;
            }

            context.Respond(new { Status = true });
            return(Task.CompletedTask);
        }
        public async Task Consume(ConsumeContext <RejectPoem> context)
        {
            Console.WriteLine("Poem rejected");
            Uri sendEndpointUri = new Uri(string.Concat(ConfigurationManager.AppSettings["RabbitMQHost"], ConfigurationManager.AppSettings["PoemStatsQueueName"]));
            var endpoint        = await context.GetSendEndpoint(sendEndpointUri);

            await endpoint.Send <RejectPoem>(new
            {
                CorrId = context.Message.CorrId,
            });
        }
Exemple #23
0
        public async Task Consume(ConsumeContext <IArchiveRecordAppendPackageMetadata> context)
        {
            var conversationEnricher    = new PropertyEnricher(nameof(context.ConversationId), context.ConversationId);
            var archiveRecordIdEnricher = new PropertyEnricher(nameof(context.Message.ArchiveRecord.ArchiveRecordId),
                                                               context.Message.ArchiveRecord?.ArchiveRecordId);

            using (LogContext.Push(conversationEnricher, archiveRecordIdEnricher))
            {
                Log.Information("Received {CommandName} command with conversationId {ConversationId} from the bus",
                                nameof(IArchiveRecordAppendPackage), context.ConversationId);

                if (context.Message.ArchiveRecord != null)
                {
                    // Get the package from the repository
                    var result = repositoryManager.ReadPackageMetadata(context.Message.ArchiveRecord.Metadata.PrimaryDataLink,
                                                                       context.Message.ArchiveRecord.ArchiveRecordId);

                    // Inform the world about the created package
                    if (result != null && result.Success && result.Valid)
                    {
                        // Add the metadata to the archive record.
                        context.Message.ArchiveRecord.PrimaryData.Add(result.PackageDetails);
                        Log.Information("Package metadata extraction was successful for packageId {packageId}", result.PackageDetails.PackageId);

                        var endpoint = await context.GetSendEndpoint(new Uri(context.SourceAddress,
                                                                             BusConstants.AssetManagerSchdeduleForPackageSyncMessageQueue));

                        await endpoint.Send <IScheduleForPackageSync>(new
                        {
                            Workload = new ArchiveRecordAppendPackage
                            {
                                MutationId    = context.Message.MutationId,
                                ArchiveRecord = context.Message.ArchiveRecord,
                                ElasticRecord = context.Message.ElasticRecord
                            }
                        });
                    }
                    else
                    {
                        // If package creation was not successful, stop syncing here and return failure.
                        Log.Error(
                            "Failed to extract primary metadata from repository for archiveRecord with conversationId {ConversationId} with message {ErrorMessage}",
                            context.ConversationId, result?.ErrorMessage);
                        await context.Publish <IArchiveRecordUpdated>(new
                        {
                            context.Message.MutationId,
                            context.Message.ArchiveRecord.ArchiveRecordId,
                            ActionSuccessful = false,
                            result?.ErrorMessage
                        });
                    }
                }
            }
        }
Exemple #24
0
        private void WriteLog <T>(ConsumeContext <T> context, IConfiguration Configuration, LogLevel logLevel, string message, object data = null) where T : class
        {
            var sendEndPoint = context.GetSendEndpoint(new Uri($"{Configuration.GetConnectionString(MicroservicesConstants.MessageBusHost)}/{EventRouteConstants.LoggingService}")).Result;

            sendEndPoint.Send(new WriteLogEvent()
            {
                Level   = logLevel.ToString(),
                Logger  = typeof(T).FullName,
                Message = message,
                Data    = data == null ? "" : JsonConvert.SerializeObject(data)
            });
        }
        protected void WriteLog <T>(ConsumeContext <T> context, IConfiguration Configuration, LogLevel logLevel, string message, object data = null) where T : class
        {
            var sendEndPoint = context.GetSendEndpoint(new System.Uri(Configuration.GetConnectionString(Constants.RabbitMQHost) + "/" + EventRouteConstants.LoggingService)).Result;

            sendEndPoint.Send(new WriteLogEvent()
            {
                Level   = logLevel.ToString(),
                Logger  = typeof(T).FullName,
                Message = message,
                Data    = data == null ? "" : JsonConvert.SerializeObject(data)
            });
        }
Exemple #26
0
        public static async Task <ISendEndpoint> GetSendEndpointAsync <TCommand>(this ConsumeContext context) where TCommand : class, new()
        {
            var busBaseAddress = context.DestinationAddress;
            var className      = typeof(TCommand).Name;

            ValidationHelpers.EnsureNamingConventionForCommand(className);

            var completeUri = BusAddressHelpers.CreateSendEndPointUri <TCommand>(busBaseAddress);
            var sender      = await context.GetSendEndpoint(completeUri);

            return(sender);
        }
        public async Task Consume(ConsumeContext <OrderSubmittedEvent> context)
        {
            this.CustomerName        = context.Message.CustomerName;
            this.CoffeeTypeRequested = context.Message.CoffeeType;
            this.ToppingsRequested   = string.Join(",", context.Message.Toppings);
            this.Amount = CoffeePriceCalculator.Compute(context.Message.CoffeeType, context.Message.Toppings);
            var sendEndpoint = await context.GetSendEndpoint(requestPaymentEndpoint);

            await sendEndpoint.Send <RequestPaymentCommand>(new { this.CorrelationId, this.Amount });

            this.State = "AwaitingPayment";
        }
        private async Task SendMessage(string queue, ConsumeContext <ProceedBeautifiedPoem> context)
        {
            Uri sendEndpointUri = new Uri(string.Concat(ConfigurationManager.AppSettings["RabbitMQHost"], queue));
            var endpoint        = await context.GetSendEndpoint(sendEndpointUri);

            await endpoint.Send <ProceedBeautifiedPoem>(new
            {
                UserId = context.Message.UserId,
                CorrId = context.Message.CorrId,
                Poem   = context.Message.Poem
            });
        }
        public async Task Consume(ConsumeContext <PrepareForTransformationMessage> context)
        {
            var conversationEnricher    = new PropertyEnricher(nameof(context.ConversationId), context.ConversationId);
            var archiveRecordIdEnricher = new PropertyEnricher(nameof(context.Message.RepositoryPackage.ArchiveRecordId), context.Message.RepositoryPackage.ArchiveRecordId);
            var packageIdEnricher       = new PropertyEnricher(nameof(context.Message.RepositoryPackage.PackageId), context.Message.RepositoryPackage.PackageId);

            using (LogContext.Push(conversationEnricher, archiveRecordIdEnricher, packageIdEnricher))
            {
                Log.Information("Received {CommandName} command with conversationId {ConversationId} from the bus", nameof(PrepareForTransformationMessage), context.ConversationId);

                // 1. Step: Extract Zip file(s)
                preparationSteps.Add(ExtractRepositoryPackage);
                // 2. Step: ConvertAreldaXml
                preparationSteps.Add(ConvertAreldaMetadataXml);
                // 3. Step: ConvertJp2ToPdf
                preparationSteps.Add(ConvertSingleJp2ToPdf);
                // 4. Step: Detect and mark files with large dimensions
                preparationSteps.Add(DetectAndFlagLargeDimensions);
                // 5. Step: Detect and optimize pdf files that need optimization
                preparationSteps.Add(DetectAndOptimizePdf);


                foreach (var step in preparationSteps)
                {
                    var result = await step(context.Message);

                    // In case any step was not successful, fail the sync
                    if (!result.Success)
                    {
                        await PublishAssetReadyFailed(context, result.ErrorMessage);

                        return;
                    }
                }

                // Forward the prepared data to the next processing point
                var endpoint = await context.GetSendEndpoint(new Uri(context.SourceAddress, BusConstants.AssetManagerTransformAssetMessageQueue));

                await endpoint.Send(new TransformAsset
                {
                    AssetType             = context.Message.AssetType,
                    OrderItemId           = context.Message.OrderItemId,
                    CallerId              = context.Message.CallerId,
                    RetentionCategory     = context.Message.RetentionCategory,
                    Recipient             = context.Message.Recipient,
                    Language              = context.Message.Language,
                    ProtectWithPassword   = context.Message.ProtectWithPassword,
                    PrimaerdatenAuftragId = context.Message.PrimaerdatenAuftragId,
                    RepositoryPackage     = context.Message.RepositoryPackage
                });
            }
        }
Exemple #30
0
        public async Task Consume(ConsumeContext <OrderSubmittedEvent> context)
        {
            var endpoint = await context.GetSendEndpoint(new Uri($"rabbitmq://{Configuration.RabbitMqHost}/payment_initiate_payment"));

            Logger.Info($"Initiating payment for customer {context.Message.CustomerId}, order {context.Message.OrderId} in total of {context.Message.Total}");

            await endpoint.Send(new InitiatePaymentCommand()
            {
                CustomerId = context.Message.CustomerId,
                OrderId    = context.Message.OrderId,
                Total      = context.Message.Total
            });
        }