public TraceEventCache ()
			{
#if SSHARP
			started = DateTimePrecise.Now;
#else
			started = DateTime.Now;
#endif
#if NETCF
			try
				{
				throw new ApplicationException ();
				}
			catch (ApplicationException aex)
				{
				callstack = aex.StackTrace;
				}
#else
			manager = Trace.CorrelationManager;
			callstack = Environment.StackTrace;
#endif
			timestamp = Stopwatch.GetTimestamp ();
#if SSHARP
			process = (int)Crestron.SimplSharp.InitialParametersClass.ApplicationNumber;
#if SSHARP_PRO
			thread = CurrentThread.Name;
#else
			thread = String.Empty;
#endif
#else
			thread = Thread.CurrentThread.Name;
			process = Process.GetCurrentProcess ().Id;
#endif
			}
Esempio n. 2
0
        public async Task Invoke(MessagingContext context, CancellationToken cancellationToken, Func <Task> next)
        {
            var    extractedSpanContext = _tracer.Extract(BuiltinFormats.TextMap, new TextMapExtractAdapter(context.MessagingEnvelope.Headers));
            string operationName        = $"Subscriber {context.MessagingEnvelope.Payload.GetType().GetPrettyName()}";

            using (var scope = _tracer.BuildSpan(operationName)
                               .AddReference(References.FollowsFrom, extractedSpanContext)
                               .WithTag(Tags.Component, "NBB.Messaging")
                               .WithTag(Tags.SpanKind, Tags.SpanKindConsumer)
                               .WithTag(Tags.PeerService,
                                        context.MessagingEnvelope.Headers.TryGetValue(MessagingHeaders.Source, out var value) ? value : default)
                               .WithTag("correlationId", CorrelationManager.GetCorrelationId()?.ToString())
                               .StartActive(true))
            {
                try
                {
                    await next();
                }
                catch (Exception exception)
                {
                    scope.Span.SetException(exception);
                    throw;
                }
            }
        }
        public Task PublishAsync <T>(T message, MessagingPublisherOptions options = null,
                                     CancellationToken cancellationToken          = default)
        {
            options ??= MessagingPublisherOptions.Default;

            void NewEnvelopeCustomizer(MessagingEnvelope outgoingEnvelope)
            {
                var correlationId = CorrelationManager.GetCorrelationId();

                if (correlationId.HasValue)
                {
                    outgoingEnvelope.SetHeader(MessagingHeaders.CorrelationId, correlationId.ToString());
                }

                var messagingEnvelope = _messagingContextAccessor.MessagingContext?.MessagingEnvelope;

                if (messagingEnvelope != null)
                {
                    messagingEnvelope.TransferHeaderTo(outgoingEnvelope, MessagingHeaders.CorrelationId);
                    messagingEnvelope.TransferCustomHeadersTo(outgoingEnvelope);
                }

                options?.EnvelopeCustomizer?.Invoke(outgoingEnvelope);
            }

            return(_inner.PublishAsync(message, options with {
                EnvelopeCustomizer = NewEnvelopeCustomizer
            },
        public TraceEventCache()
        {
#if SSHARP
            started = DateTimePrecise.Now;
#else
            started = DateTime.Now;
#endif
#if NETCF
            try
            {
                throw new ApplicationException();
            }
            catch (ApplicationException aex)
            {
                callstack = aex.StackTrace;
            }
#else
            manager   = Trace.CorrelationManager;
            callstack = Environment.StackTrace;
#endif
            timestamp = Stopwatch.GetTimestamp();
#if SSHARP
            process = (int)Crestron.SimplSharp.InitialParametersClass.ApplicationNumber;
#if SSHARP_PRO
            thread = CurrentThread.Name;
#else
            thread = String.Empty;
#endif
#else
            thread  = Thread.CurrentThread.Name;
            process = Process.GetCurrentProcess().Id;
#endif
        }
Esempio n. 5
0
        public async static Task PublishEvent([TimerTrigger("00:00:03", RunOnStartup = true)] TimerInfo myTimer, ILogger logger)
        {
            CorrelationManager.SetStartTrace();

            string requestId = Guid.NewGuid().ToString();

            CorrelationManager.SetRequestId(requestId);

            string operationId = Guid.NewGuid().ToString();

            CorrelationManager.SetOperationId(operationId);

            string operationParentId = Guid.NewGuid().ToString();

            CorrelationManager.SetOperationParentId(operationParentId);

            string sourceBatchId = Guid.NewGuid().ToString();

            CorrelationManager.SetSourceBatchId(sourceBatchId);

            try
            {
                //var myEvent = new Event
                //{
                //    EventId = 1000,
                //    EventName = "Event1000",
                //    EventType = "Claim",
                //    Priority = 1,
                //    Properties = new Dictionary<string, string>
                //    {
                //        { "prop1", "value1" },
                //        { "prop2", "value2" }
                //    }
                //};

                var    events  = GetEventsCollection();
                Random random  = new Random();
                int    index   = random.Next(0, 11);
                var    myEvent = events[index];

                var eventMessage = new BrokeredMessage(myEvent);
                eventMessage.Properties["EventType"] = myEvent.EventType;
                CorrelationManager.SetCorrelation(eventMessage);

                if (myEvent.EventName == "ClearCache")
                {
                    await clearCacheQueueManager.SendToQueueAsync(eventMessage);
                }
                else
                {
                    await queueManager.SendToQueueAsync(eventMessage);
                }

                logger.LogInformation($"Sent {myEvent.EventType} event with ID {myEvent.EventId}.");
            }
            catch (Exception ex)
            {
                logger.LogCritical($"Failed to send event! {ex.Message}");
            }
        }
Esempio n. 6
0
 public async Task Invoke(MessagingContext context, CancellationToken cancellationToken, Func <Task> next)
 {
     using (CorrelationManager.NewCorrelationId(context.MessagingEnvelope.GetCorrelationId()))
     {
         await next();
     }
 }
Esempio n. 7
0
        public async Task Invoke(string body, CancellationToken cancellationToken)
        {
            var correlationId = GetCorrelationIdFromBuffer(body);

            using (CorrelationManager.NewCorrelationId(correlationId))
            {
                using (var scope = _container.CreateScope())
                {
                    var command        = GetCommandFromBuffer(body);
                    var commandHandler = scope.ServiceProvider.GetService <IRequestHandler <Application.Commands.CreateContract> >();
                    if (commandHandler != null)
                    {
                        await commandHandler.Handle(command, cancellationToken);
                    }
                }
            }

            //using (CorrelationManager.NewCorrelationId(correlationId))
            //{
            //    var command = GetCommandFromBuffer(buffer);
            //    var commandHandler = GetCommandHandler();
            //    await commandHandler.Handle(command, CancellationToken.None);
            //    await commandHandler.Handle(command, CancellationToken.None);
            //}
        }
        public async static Task RouteEvent([ServiceBusTrigger(topicName, subscriptionName, AccessRights.Manage, Connection = serviceBusConnectionStringKey)]
                                            BrokeredMessage eventMessage, ILogger logger)
        {
            try
            {
                if (eventMessage == null)
                {
                    throw new ArgumentNullException("eventMessage");
                }

                if (logger == null)
                {
                    throw new ArgumentNullException("logger");
                }

                var    myEvent   = eventMessage.GetBody <Event>();
                string eventType = $"Enriched{myEvent.EventType}";
                myEvent.EventType = eventType;

                var eventEnrichedMessage = new BrokeredMessage(myEvent);
                eventEnrichedMessage.Properties["EventType"] = eventType;
                CorrelationManager.SetCorrelation(eventEnrichedMessage);

                await queueManager.SendToQueueAsync(eventEnrichedMessage);

                logger.LogInformation($"Received valid {eventType} event with ID {myEvent.EventId}.");
            }
            catch (Exception ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to receive evaluated event for message with Message ID: {eventMessage.MessageId}. {ex.Message}");
            }
        }
Esempio n. 9
0
        public Task PublishAsync <T>(T message, MessagingPublisherOptions options = null,
                                     CancellationToken cancellationToken          = default)
        {
            options ??= MessagingPublisherOptions.Default;

            void NewCustomizer(MessagingEnvelope outgoingEnvelope)
            {
                if (_tracer.ActiveSpan != null)
                {
                    _tracer.Inject(_tracer.ActiveSpan.Context, BuiltinFormats.TextMap,
                                   new TextMapInjectAdapter(outgoingEnvelope.Headers));
                }

                options.EnvelopeCustomizer?.Invoke(outgoingEnvelope);
            }

            var formattedTopicName = _topicRegistry.GetTopicForName(options.TopicName) ??
                                     _topicRegistry.GetTopicForMessageType(message.GetType());
            var operationName = $"Publisher {message.GetType().GetPrettyName()}";

            using (var scope = _tracer.BuildSpan(operationName)
                               .WithTag(Tags.Component, MessagingTags.ComponentMessaging)
                               .WithTag(Tags.SpanKind, Tags.SpanKindProducer)
                               .WithTag(Tags.MessageBusDestination, formattedTopicName)
                               .WithTag(MessagingTags.CorrelationId, CorrelationManager.GetCorrelationId()?.ToString())
                               .StartActive(true))
            {
                try
                {
                    return(_inner.PublishAsync(message, options with {
                        EnvelopeCustomizer = NewCustomizer
                    },
                                               cancellationToken));
                }
Esempio n. 10
0
        public static IApplicationBuilder UseCorrelation(this IApplicationBuilder app)
        {
            return(app.Use((context, inner) =>
            {
                Guid?ExtractGuid(StringValues values)
                {
                    if (values.Count <= 0)
                    {
                        return null;
                    }
                    if (!Guid.TryParse(values[0], out var uuid))
                    {
                        return null;
                    }

                    return uuid;
                }

                var correlationId =
                    ExtractGuid(context.Request.Headers[HttpRequestHeaders.CorrelationId]) ??
                    ExtractGuid(context.Request.Query["correlationId"]);

                using (CorrelationManager.NewCorrelationId(correlationId))
                {
                    return inner();
                }
            }));
        }
Esempio n. 11
0
        public Task PublishAsync <T>(T message, CancellationToken cancellationToken = default, Action <MessagingEnvelope> customizer = null, string topicName = null)
        {
            void NewCustomizer(MessagingEnvelope outgoingEnvelope)
            {
                if (_tracer.ActiveSpan != null)
                {
                    _tracer.Inject(_tracer.ActiveSpan.Context, BuiltinFormats.TextMap,
                                   new TextMapInjectAdapter(outgoingEnvelope.Headers));
                }

                customizer?.Invoke(outgoingEnvelope);
            }

            var formattedTopicName = _topicRegistry.GetTopicForName(topicName) ??
                                     _topicRegistry.GetTopicForMessageType(message.GetType());
            var operationName = $"Publisher {message.GetType().GetPrettyName()}";

            using (var scope = _tracer.BuildSpan(operationName)
                               .WithTag(Tags.Component, MessagingTags.ComponentMessaging)
                               .WithTag(Tags.SpanKind, Tags.SpanKindProducer)
                               .WithTag(Tags.MessageBusDestination, formattedTopicName)
                               .WithTag(MessagingTags.CorrelationId, CorrelationManager.GetCorrelationId()?.ToString())
                               .StartActive(true))
            {
                try
                {
                    return(_inner.PublishAsync(message, cancellationToken, NewCustomizer, topicName));
                }
                catch (Exception exception)
                {
                    scope.Span.SetException(exception);
                    throw;
                }
            }
        }
        public static void RouteEvent([ServiceBusTrigger(topicName, subscriptionName, AccessRights.Manage, Connection = serviceBusConnectionStringKey)]
                                      BrokeredMessage eventMessage, ILogger logger)
        {
            try
            {
                if (eventMessage == null)
                {
                    throw new ArgumentNullException("eventMessage");
                }

                if (logger == null)
                {
                    throw new ArgumentNullException("logger");
                }

                var myEvent = eventMessage.GetBody <Event>();

                CorrelationManager.SetStopTrace();
                logger.LogInformation($"Received valid {myEvent.EventType} event with ID {myEvent.EventId}.");
            }
            catch (Exception ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to receive evaluated event for message with Message ID: {eventMessage.MessageId}. {ex.Message}");
            }
        }
Esempio n. 13
0
        private MessagingEnvelope <TMessage> PrepareMessageEnvelope <TMessage>(TMessage message,
                                                                               Action <MessagingEnvelope> customizer = null)
        {
            var outgoingEnvelope = new MessagingEnvelope <TMessage>(new Dictionary <string, string>
            {
                [MessagingHeaders.MessageId]   = Guid.NewGuid().ToString(),
                [MessagingHeaders.PublishTime] = DateTime.Now.ToString(CultureInfo.InvariantCulture)
            }, message);

            if (message is IKeyProvider messageKeyProvider)
            {
                outgoingEnvelope.Headers[MessagingHeaders.StreamId] = messageKeyProvider.Key;
            }

            var sourceId = GetSourceId();

            if (!string.IsNullOrWhiteSpace(sourceId))
            {
                outgoingEnvelope.Headers[MessagingHeaders.Source] = sourceId;
            }

            customizer?.Invoke(outgoingEnvelope);

            outgoingEnvelope.SetHeader(MessagingHeaders.CorrelationId,
                                       (CorrelationManager.GetCorrelationId() ?? Guid.NewGuid()).ToString());

            return(outgoingEnvelope);
        }
        public async Task ProcessQueueMessage([QueueTrigger("fixits")] FixItTaskMessage message, TextWriter log)
        {
            CorrelationManager.SetOperationId(message.OperationId);

            await repository.CreateAsync(message.Task);

            log.WriteLine("Created task {0}", message.Task.Title);
        }
Esempio n. 15
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Context.Operation.Name                    = CorrelationManager.GetOperationName();
     telemetry.Context.Operation.ParentId                = CorrelationManager.GetOperationParentId();
     telemetry.Context.Operation.Id                      = CorrelationManager.GetOperationId();
     telemetry.Context.Properties["StartTrace"]          = CorrelationManager.GetStartTrace();
     telemetry.Context.Properties["StopTrace"]           = CorrelationManager.GetStopTrace();
     telemetry.Context.Properties[this.sourceBatchIdKey] = CorrelationManager.GetSourceBatchId();
 }
Esempio n. 16
0
 public Task SubscribeToAllAsync(Func <IEvent, Task> handler, CancellationToken cancellationToken = default)
 {
     return(_messageBusSubscriber.SubscribeAsync(async envelope =>
     {
         using (CorrelationManager.NewCorrelationId(envelope.GetCorrelationId()))
         {
             await handler(envelope.Payload);
         }
     }, cancellationToken, _messagingTopicResolver.ResolveTopicName(), _subscriberOptions));
 }
        public RebusIntegrationTests(RebusFixture fixture)
        {
            _fixture   = fixture;
            _activator = fixture.CreateActivator();
            _bus       = _activator.Bus;

            _correlationContextAccessor = new CorrelationContextAccessor();
            _correlationManager         = new CorrelationManager(new CorrelationContextFactory(_correlationContextAccessor), new GuidCorrelationIdFactory(), _correlationContextAccessor, new TestLogger <CorrelationManager>());

            _tcs = new TaskCompletionSource <string>();
        }
Esempio n. 18
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var requestTelemetry = filterContext.HttpContext.Features.Get <RequestTelemetry>();

            if (null == requestTelemetry)
            {
                return;
            }

            CorrelationManager.SetOperationId(requestTelemetry.Context.Operation.Id);
        }
Esempio n. 19
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Items.Contains(RequestTelemetryKey))
            {
                var requestTelemetry = filterContext.HttpContext.Items[RequestTelemetryKey] as RequestTelemetry;
                if (requestTelemetry == null)
                {
                    return;
                }

                CorrelationManager.SetOperationId(requestTelemetry.Id);
            }
        }
Esempio n. 20
0
        public void UncorrelatedMessage_should_decrease_reputation()
        {
            var reputationBefore = _reputationByPeerIdentifier[PeerIds[1]];
            var responseMatchingIndex1 = new PingResponse().ToProtocolMessage(
                PeerIds[1],
                CorrelationId.GenerateCorrelationId());

            CorrelationManager.TryMatchResponse(responseMatchingIndex1);

            _testScheduler.Start();

            var reputationAfter = _reputationByPeerIdentifier[PeerIds[1]];
            reputationAfter.Should().BeLessThan(reputationBefore);
        }
        // Puts a serialized fixit onto the queue.
        public async Task SendMessageAsync(FixItTask fixIt)
        {
            CloudQueue queue = queueClient.GetQueueReference(FixitQueueName);
            await queue.CreateIfNotExistsAsync();

            var fixitJson = JsonConvert.SerializeObject(new FixItTaskMessage
            {
                Task        = fixIt,
                OperationId = CorrelationManager.GetOperationId()
            });
            CloudQueueMessage message = new CloudQueueMessage(fixitJson);

            await queue.AddMessageAsync(message);
        }
Esempio n. 22
0
        static void SimpleCorrelationManager()
        {
            Guid activityGuid = Guid.NewGuid();

            CorrelationManager cm = Trace.CorrelationManager;

            cm.StartLogicalOperation("MainThread");

            cm.ActivityId = activityGuid;

            cm.LogicalOperationStack.Push("Some sheet");
            cm.LogicalOperationStack.Push("Some sheet2");

            cm.StopLogicalOperation();
        }
Esempio n. 23
0
        public async void Should_setNewCorrelationId()
        {
            //Arrange
            var  correlationMiddleWare = new CorrelationMiddleware();
            var  sentMessage           = new { Field = "value" };
            Guid?correlationId         = null;
            var  envelope = new MessagingEnvelope(new System.Collections.Generic.Dictionary <string, string>(), sentMessage);


            Task Next()
            {
                correlationId = CorrelationManager.GetCorrelationId(); return(Task.CompletedTask);
            }

            //Act
            await correlationMiddleWare.Invoke(new MessagingContext(envelope, string.Empty, null), default, Next);
        public void CreateValue(string value)
        {
            var storageAccount = CloudStorageAccount.Parse(AzureStorageConfiguration.Value.QueueConnectionString);
            var queueClient    = storageAccount.CreateCloudQueueClient();
            var queue          = queueClient.GetQueueReference(AzureStorageConfiguration.Value.QueueName);

            queue.CreateIfNotExists();

            var message = new CloudQueueMessage(JsonConvert.SerializeObject(new ValueMessage
            {
                OperationId = CorrelationManager.GetOperationId(),
                Value       = value
            }));

            queue.AddMessage(message);
        }
Esempio n. 25
0
        public void TryMatchResponseAsync_when_matching_should_increase_reputation()
        {
            var reputationBefore = _reputationByPeerIdentifier[PeerIds[1]];

            var responseMatchingIndex1 = new PingResponse().ToProtocolMessage(
                PeerIds[1],
                PendingRequests[1].Content.CorrelationId.ToCorrelationId());

            var request = CorrelationManager.TryMatchResponse(responseMatchingIndex1);
            request.Should().BeTrue();

            _testScheduler.Start();

            var reputationAfter = _reputationByPeerIdentifier[PeerIds[1]];
            reputationAfter.Should().BeGreaterThan(reputationBefore);

            _reputationByPeerIdentifier.Where(r => !r.Key.Equals(PeerIds[1]))
               .Select(r => r.Value).Should().AllBeEquivalentTo(0);
        }
Esempio n. 26
0
        public async Task AsyncLocalForCorrelationId()
        {
            var correlationManager = new CorrelationManager();

            async Task CrelateCorrelatedTask()
            {
                var correlationId = Guid.NewGuid().ToString();

                correlationManager.SetCorrelationId(correlationId);

                await Task.Delay(1000);

                Assert.Equal(correlationId, correlationManager.GetCorrelationId());
            }

            await Task.WhenAll(
                CrelateCorrelatedTask(),
                CrelateCorrelatedTask()
                );
        }
Esempio n. 27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CorrelateMiddleware"/> class.
        /// </summary>
        /// <param name="next">The next request delegate to invoke in the request execution pipeline.</param>
        /// <param name="options">The options.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="correlationManager">The correlation manager.</param>
        public CorrelateMiddleware(
            RequestDelegate next,
            IOptions <CorrelateOptions> options,
            ILogger <CorrelateMiddleware> logger,
            CorrelationManager correlationManager)
        {
            _next               = next ?? throw new ArgumentNullException(nameof(next));
            _options            = options?.Value ?? throw new ArgumentNullException(nameof(options));
            _logger             = logger ?? throw new ArgumentNullException(nameof(logger));
            _correlationManager = correlationManager ?? throw new ArgumentNullException(nameof(correlationManager));

            if (_options.RequestHeaders == null || !_options.RequestHeaders.Any())
            {
                _acceptedRequestHeaders = ImmutableArray <string> .Empty;
            }
            else
            {
                _acceptedRequestHeaders = _options.RequestHeaders.ToImmutableArray();
            }
        }
        /// <summary>
        /// Use Correlate with Hangfire to manage the correlation context.
        /// </summary>
        /// <param name="configuration">The global configuration.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public static IGlobalConfiguration UseCorrelate(this IGlobalConfiguration configuration, ILoggerFactory loggerFactory)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            var correlationContextAccessor = new CorrelationContextAccessor();
            var correlationManager         = new CorrelationManager(
                new CorrelationContextFactory(correlationContextAccessor),
                new GuidCorrelationIdFactory(), correlationContextAccessor,
                loggerFactory.CreateLogger <CorrelationManager>()
                );
            var correlateFilterAttribute = new CorrelateFilterAttribute(correlationContextAccessor, correlationManager);

            return(configuration.UseFilter(correlateFilterAttribute));
        }
Esempio n. 29
0
        public static void ClearCache([ServiceBusTrigger(queueName, AccessRights.Manage, Connection = serviceBusConnectionStringKey)]
                                      BrokeredMessage eventMessage, ILogger logger)
        {
            try
            {
                if (eventMessage == null)
                {
                    throw new ArgumentNullException("eventMessage");
                }

                if (logger == null)
                {
                    throw new ArgumentNullException("logger");
                }

                if (eventMessage.Properties.ContainsKey("EventType"))
                {
                    string eventType = eventMessage.Properties["EventType"].ToString();

                    var cache = new Cache <List <Rule <Event> > >();
                    cache.Clear(eventType);

                    CorrelationManager.SetStopTrace();
                    logger.LogTrace($"ClearCache request successfully executed. Cache cleared for {eventType} rules.");
                }
                else
                {
                    CorrelationManager.SetStopTrace();
                    logger.LogError($"Unable to  to execute ClearCache request. Property EventType is missing.");
                }
            }
            catch (Exception ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to execute ClearCache request. {ex.Message}");
            }
        }
        public Task PublishAsync <T>(T message, CancellationToken cancellationToken = default, Action <MessagingEnvelope> envelopeCustomizer = null, string topicName = null)
        {
            void NewEnvelopeCustomizer(MessagingEnvelope outgoingEnvelope)
            {
                var correlationId = CorrelationManager.GetCorrelationId();

                if (correlationId.HasValue)
                {
                    outgoingEnvelope.SetHeader(MessagingHeaders.CorrelationId, correlationId.ToString(), false);
                }

                var receivedMessageEnvelope = _messagingContextAccessor.MessagingContext?.ReceivedMessageEnvelope;

                if (receivedMessageEnvelope != null)
                {
                    receivedMessageEnvelope.TransferHeaderTo(outgoingEnvelope, MessagingHeaders.CorrelationId, false);
                    receivedMessageEnvelope.TransferCustomHeadersTo(outgoingEnvelope, false);
                }

                envelopeCustomizer?.Invoke(outgoingEnvelope);
            }

            return(_inner.PublishAsync(message, cancellationToken, NewEnvelopeCustomizer, topicName));
        }
Esempio n. 31
0
        public static async Task EvaluateEvent([ServiceBusTrigger(queueName, AccessRights.Manage, Connection = serviceBusConnectionStringKey)]
                                               BrokeredMessage eventMessage, ILogger logger)
        {
            try
            {
                if (eventMessage == null)
                {
                    throw new ArgumentNullException("eventMessage");
                }

                if (logger == null)
                {
                    throw new ArgumentNullException("logger");
                }

                // Retrieve event and event type from the message.
                var    myEvent   = eventMessage.GetBody <Event>();
                string eventType = myEvent.EventType;

                // Load rules.
                var rulesCollection = new RulesCollection(logger, storageManager);
                var rules           = rulesCollection.GetRulesCollection(eventType);

                // Evaluate event by rules.
                var  eventEvaluator = new EventEvaluator(logger);
                bool isValid        = eventEvaluator.EvaluateEvent(myEvent, rules);

                // If true, send to Event Matched Topic.
                if (isValid)
                {
                    var eventEvaluatedMessage = eventMessage.Clone();
                    eventEvaluatedMessage.Properties["EventType"] = eventType;
                    CorrelationManager.SetCorrelation(eventEvaluatedMessage);

                    await topicManager.SendToTopicAsync(eventEvaluatedMessage);

                    logger.LogInformation($"Approved {eventType} event with ID {myEvent.EventId}.");
                }
                else
                {
                    // Log exit trace.
                    CorrelationManager.SetStopTrace();
                    logger.LogInformation($"Rejected {eventType} event with ID {myEvent.EventId}.");
                }
            }
            catch (ArgumentNullException ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to evaluate event for message with Message ID: {eventMessage.MessageId}. {ex.Message}");
            }
            catch (ServiceException ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to evaluate event for message with Message ID: {eventMessage.MessageId}. {ex.Message}");
            }
            catch (Exception ex)
            {
                // Log critical error and continue.
                CorrelationManager.SetStopTrace();
                logger.LogCritical($"Failed to evaluate event for message with Message ID: {eventMessage.MessageId}. {ex.Message}");
            }
        }