예제 #1
0
        public virtual void ReceiveEvent(IEvent <TAuthenticationToken> @event)
        {
            switch (@event.Framework)
            {
            case FrameworkType.Akka:
                Logger.LogInfo(string.Format("An event arrived of the type '{0}' but was marked as coming from the '{1}' framework, so it was dropped.", @event.GetType().FullName, @event.Framework));
                return;
            }

            CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken);

            Type eventType  = @event.GetType();
            bool isRequired = BusHelper.IsEventRequired(eventType);

            IEnumerable <Action <IMessage> > handlers = Routes.GetHandlers(@event, isRequired).Select(x => x.Delegate).ToList();

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (!handlers.Any())
            {
                Logger.LogDebug(string.Format("The event handler for '{0}' is not required.", eventType.FullName));
            }

            foreach (Action <IMessage> handler in handlers)
            {
                handler(@event);
            }
        }
예제 #2
0
        public virtual void Add_ValidProjectionView_ProjectionViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            TableStorageDataStore <TestEvent> dataStore = CreateDataStore <TestEvent>(logger, new ConfigurationManager());

            var event1 = new TestEvent
            {
                Rsn           = Guid.NewGuid(),
                Id            = Guid.NewGuid(),
                CorrelationId = correlationIdHelper.GetCorrelationId(),
                Frameworks    = new List <string> {
                    "Test 1"
                },
                TimeStamp = DateTimeOffset.UtcNow
            };

            // Act
            dataStore.Add(event1);

            // Assert
            var timer      = new Stopwatch();
            var repository = new TableStorageRepository <TestQueryStrategy, TestQueryBuilder <TestEvent>, TestEvent>(() => dataStore, null);

            timer.Start();
            TestEvent view = repository.Load(event1.Rsn);

            timer.Stop();
            Console.WriteLine("Load operation took {0}", timer.Elapsed);
            Assert.IsNotNull(view);
            Assert.AreEqual(event1.Id, view.Id);
        }
예제 #3
0
        protected virtual void StartSettingsChecking()
        {
            Guid currentCorrelationId;

            try
            {
                currentCorrelationId = CorrelationIdHelper.GetCorrelationId();
            }
            catch (Exception)
            {
                currentCorrelationId = Guid.NewGuid();
            }
            Task.Factory.StartNew(() =>
            {
                // New thread remember
                CorrelationIdHelper.SetCorrelationId(currentCorrelationId);

                SpinWait.SpinUntil(ValidateSettingsHaveChanged, sleepInMilliseconds: 1000);

                Logger.LogInfo("Connecting string settings for the Azure Service Bus changed and will now refresh.");

                // Update the connection string and trigger a restart;
                if (ValidateSettingsHaveChanged())
                {
                    TriggerSettingsChecking();
                }
            });
        }
        public virtual void Save_ValidProjectionView_ProjectionViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger    = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            var dataStore = new BlobStorageDataStore <TestEvent>(logger, new BlobStorageDataStoreConnectionStringFactory(new ConfigurationManager(), logger));

            var event1 = new TestEvent
            {
                Rsn           = Guid.NewGuid(),
                Id            = Guid.NewGuid(),
                CorrelationId = correlationIdHelper.GetCorrelationId(),
                Frameworks    = new List <string> {
                    "Test 1"
                },
                TimeStamp = DateTimeOffset.UtcNow
            };

            // Act
            dataStore.Add(event1);

            // Assert
            var timer = new Stopwatch();

            timer.Start();
            TestEvent view = dataStore.GetByName(event1.Rsn);

            timer.Stop();
            Console.WriteLine("Load operation took {0}", timer.Elapsed);
            Assert.IsNotNull(view);
            Assert.AreEqual(event1.Id, view.Id);
        }
예제 #5
0
        public virtual void Add_ValidProjectionEntityView_ProjectionEntityViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            TableStorageDataStore <TestEntity> dataStore = CreateDataStore <TestEntity>(logger, new ConfigurationManager());

            var event1 = new TestEntity
            {
                Rsn  = Guid.NewGuid(),
                Name = "Name"
            };

            // Act
            dataStore.Add(event1);

            // Assert
            var timer      = new Stopwatch();
            var repository = new TableStorageRepository <TestQueryStrategy, TestQueryBuilder <TestEntity>, TestEntity>(() => dataStore, null);

            timer.Start();
            TestEntity view = repository.Load(event1.Rsn);

            timer.Stop();
            Console.WriteLine("Load operation took {0}", timer.Elapsed);
            Assert.IsNotNull(view);
            Assert.AreEqual(event1.Rsn, view.Rsn);
            Assert.AreEqual(event1.Name, view.Name);
        }
예제 #6
0
        /// <summary>
        /// Get all <see cref="MessageEntity">messages</see> for the provided conversation.
        /// </summary>
        public virtual IServiceResponseWithResultData <IEnumerable <MessageEntity> > GetMessages(IServiceRequestWithData <Guid, ConversationParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            Guid conversationRsn = serviceRequest.Data.ConversationRsn;

            // Define Query
            ICollectionResultQuery <MessageQueryStrategy, MessageEntity> query = QueryFactory.CreateNewCollectionResultQuery <MessageQueryStrategy, MessageEntity>();

            query.QueryStrategy.WithConversationRsn(conversationRsn);
            query.QueryStrategy.OrderByDatePosted();

            // Retrieve Data
            query = MessageRepository.Retrieve(query);
            IEnumerable <MessageEntity> queryResults = query.Result.ToList();

            var responseData = new ServiceResponseWithResultData <IEnumerable <MessageEntity> >
            {
                State      = ServiceResponseStateType.Succeeded,
                ResultData = queryResults
            };

            // Complete the response
            ServiceResponseWithResultData <IEnumerable <MessageEntity> > response = CompleteResponse(responseData);

            if (!queryResults.Any())
            {
                response.State = ServiceResponseStateType.EntityNotFound;
            }

            return(response);
        }
예제 #7
0
        public virtual void ReceiveCommand(ICommand <TAuthenticationToken> command)
        {
            Type commandType = command.GetType();

            switch (command.Framework)
            {
            case FrameworkType.Akka:
                Logger.LogInfo(string.Format("A command arrived of the type '{0}' but was marked as coming from the '{1}' framework, so it was dropped.", commandType.FullName, command.Framework));
                return;
            }

            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            bool isRequired;

            if (!ConfigurationManager.TryGetSetting(string.Format("{0}.IsRequired", commandType.FullName), out isRequired))
            {
                isRequired = true;
            }

            RouteHandlerDelegate commandHandler = Routes.GetSingleHandler(command, isRequired);

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
                return;
            }

            Action <IMessage> handler = commandHandler.Delegate;

            handler(command);
        }
예제 #8
0
        /// <summary>
        /// Delete an existing conversation.
        /// </summary>
        public virtual IServiceResponse DeleteConversation(IServiceRequestWithData <Guid, ConversationParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            var responseData = new ServiceResponse();

            var command = new DeleteConversation
            {
                Rsn = serviceRequest.Data.ConversationRsn
            };

            try
            {
                CommandPublisher.Publish(command);

                responseData.State = ServiceResponseStateType.Succeeded;
            }
            catch (Exception)
            {
                responseData.State = ServiceResponseStateType.Unknown;
            }

            // Complete the response
            return(CompleteResponse(responseData));
        }
예제 #9
0
        /// <summary>
        /// Get all <see cref="ConversationSummaryEntity">conversations</see>.
        /// </summary>
        public virtual IServiceResponseWithResultData <IEnumerable <ConversationSummaryEntity> > Get(IServiceRequest <Guid> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            // Define Query
            ICollectionResultQuery <ConversationSummaryQueryStrategy, ConversationSummaryEntity> query = QueryFactory.CreateNewCollectionResultQuery <ConversationSummaryQueryStrategy, ConversationSummaryEntity>();

            query.QueryStrategy.WithNoDeletedConversations();

            // Retrieve Data
            query = ConversationSummaryRepository.Retrieve(query);
            IEnumerable <ConversationSummaryEntity> queryResults = query.Result;

            var responseData = new ServiceResponseWithResultData <IEnumerable <ConversationSummaryEntity> >
            {
                State      = ServiceResponseStateType.Succeeded,
                ResultData = queryResults
            };

            // Complete the response
            ServiceResponseWithResultData <IEnumerable <ConversationSummaryEntity> > response = CompleteResponse(responseData);

            return(response);
        }
예제 #10
0
        /// <summary>
        /// Executes the provided <paramref name="action"/> passing it the provided <paramref name="command"/>,
        /// then calls <see cref="AggregateRepository{TAuthenticationToken}.PublishEvent"/>
        /// </summary>
        protected virtual void Execute <TCommand>(Action <TCommand> action, TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            Type baseType = GetType().BaseType;

            UnitOfWork.Add(this, baseType != null && baseType.Name == typeof(AkkaSnapshotAggregateRoot <,>).Name);
            try
            {
                AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);
                CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
                action(command);

                UnitOfWork.Commit();

                Sender.Tell(true, Self);
            }
            catch (Exception exception)
            {
                Logger.LogError("Executing an Akka.net request failed.", exception: exception, metaData: new Dictionary <string, object> {
                    { "Type", GetType() }, { "Command", command }
                });
                Sender.Tell(false, Self);
                throw;
            }
        }
예제 #11
0
        /// <summary>
        /// Update the name of an existing conversation.
        /// </summary>
        public virtual IServiceResponse UpdateConversation(IServiceRequestWithData <Guid, UpdateConversationParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            var responseData = new ServiceResponse
            {
                State = ServiceResponseStateType.FailedValidation
            };

            if (string.IsNullOrWhiteSpace(serviceRequest.Data.Name))
            {
                return(CompleteResponse(responseData));
            }

            var command = new UpdateConversation
            {
                Rsn  = serviceRequest.Data.ConversationRsn,
                Name = serviceRequest.Data.Name
            };

            try
            {
                CommandPublisher.Publish(command);

                responseData.State = ServiceResponseStateType.Succeeded;
            }
            catch (Exception)
            {
                responseData.State = ServiceResponseStateType.Unknown;
            }

            // Complete the response
            return(CompleteResponse(responseData));
        }
예제 #12
0
        /// <summary>
        /// The default command handler that
        /// check if the <see cref="ICommand{TAuthenticationToken}"/> has already been processed by this framework,
        /// checks if the <see cref="ICommand{TAuthenticationToken}"/> is required,
        /// finds the handler from the provided <paramref name="routeManager"/>.
        /// </summary>
        /// <param name="command">The <see cref="ICommand{TAuthenticationToken}"/> to process.</param>
        /// <param name="routeManager">The <see cref="RouteManager"/> to get the <see cref="ICommandHandler{TAuthenticationToken,TCommand}"/> from.</param>
        /// <param name="framework">The current framework.</param>
        /// <returns>
        /// True indicates the <paramref name="command"/> was successfully handled by a handler.
        /// False indicates the <paramref name="command"/> wasn't handled, but didn't throw an error, so by convention, that means it was skipped.
        /// Null indicates the command<paramref name="command"/> wasn't handled as it was already handled.
        /// </returns>
        public virtual bool?DefaultReceiveCommand(ICommand <TAuthenticationToken> command, RouteManager routeManager, string framework)
        {
            Type commandType = command.GetType();

            if (command.Frameworks != null && command.Frameworks.Contains(framework))
            {
                // if this is the only framework in the list, then it's fine to handle as it's just pre-stamped, if there is more than one framework, then exit.
                if (command.Frameworks.Count() != 1)
                {
                    Logger.LogInfo("The provided command has already been processed in Azure.", string.Format("{0}\\DefaultReceiveCommand({1})", GetType().FullName, commandType.FullName));
                    return(null);
                }
            }

            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(commandType);

            RouteHandlerDelegate commandHandler = routeManager.GetSingleHandler(command, isRequired);

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
                return(false);
            }

            Action <IMessage> handler = commandHandler.Delegate;

            handler(command);
            return(true);
        }
예제 #13
0
        /// <summary>
        /// The default event handler that
        /// check if the <see cref="IEvent{TAuthenticationToken}"/> has already been processed by this framework,
        /// checks if the <see cref="IEvent{TAuthenticationToken}"/> is required,
        /// finds the handler from the provided <paramref name="routeManager"/>.
        /// </summary>
        /// <param name="event">The <see cref="IEvent{TAuthenticationToken}"/> to process.</param>
        /// <param name="routeManager">The <see cref="RouteManager"/> to get the <see cref="IEventHandler{TAuthenticationToken,TCommand}"/> from.</param>
        /// <param name="framework">The current framework.</param>
        /// <returns>
        /// True indicates the <paramref name="event"/> was successfully handled by a handler.
        /// False indicates the <paramref name="event"/> wasn't handled, but didn't throw an error, so by convention, that means it was skipped.
        /// Null indicates the <paramref name="event"/> wasn't handled as it was already handled.
        /// </returns>
        public virtual bool?DefaultReceiveEvent(IEvent <TAuthenticationToken> @event, RouteManager routeManager, string framework)
        {
            Type eventType = @event.GetType();

            if (@event.Frameworks != null && @event.Frameworks.Contains(framework))
            {
                // if this is the only framework in the list, then it's fine to handle as it's just pre-stamped, if there is more than one framework, then exit.
                if (@event.Frameworks.Count() != 1)
                {
                    Logger.LogInfo("The provided event has already been processed in Azure.", string.Format("{0}\\DefaultReceiveEvent({1})", GetType().FullName, eventType.FullName));
                    return(null);
                }
            }

            CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(eventType);

            IEnumerable <Action <IMessage> > handlers = routeManager.GetHandlers(@event, isRequired).Select(x => x.Delegate).ToList();

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (!handlers.Any())
            {
                Logger.LogDebug(string.Format("The event handler for '{0}' is not required.", eventType.FullName));
                return(false);
            }

            foreach (Action <IMessage> handler in handlers)
            {
                handler(@event);
            }
            return(true);
        }
예제 #14
0
        public virtual void DefaultReceiveCommand(ICommand <TAuthenticationToken> command, RouteManager routeManager, string framework)
        {
            Type commandType = command.GetType();

            if (command.Frameworks != null && command.Frameworks.Contains(framework))
            {
                Logger.LogInfo("The provided command has already been processed in Azure.", string.Format("{0}\\DefaultReceiveCommand({1})", GetType().FullName, commandType.FullName));
                return;
            }

            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            bool isRequired = BusHelper.IsEventRequired(commandType);

            RouteHandlerDelegate commandHandler = routeManager.GetSingleHandler(command, isRequired);

            // This check doesn't require an isRequired check as there will be an exception raised above and handled below.
            if (commandHandler == null)
            {
                Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName));
                return;
            }

            Action <IMessage> handler = commandHandler.Delegate;

            handler(command);
        }
        public virtual void Save_ValidEvent_EventCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger     = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            var eventStore = CreateEventStore(new DefaultEventBuilder <Guid>(), new EventDeserialiser <Guid>(), logger, new TableStorageEventStoreConnectionStringFactory(new ConfigurationManager(), logger));

            var event1 = new TestEvent
            {
                Rsn           = Guid.NewGuid(),
                Id            = Guid.NewGuid(),
                CorrelationId = correlationIdHelper.GetCorrelationId(),
                Frameworks    = new List <string> {
                    "Test 1"
                },
                TimeStamp = DateTimeOffset.UtcNow
            };
            var event2 = new TestEvent
            {
                Rsn           = Guid.NewGuid(),
                Id            = Guid.NewGuid(),
                CorrelationId = correlationIdHelper.GetCorrelationId(),
                Frameworks    = new List <string> {
                    "Test 2"
                },
                TimeStamp = DateTimeOffset.UtcNow
            };

            // Act
            eventStore.Save <TestEvent>(event1);
            eventStore.Save <TestEvent>(event2);

            // Assert
            var timer = new Stopwatch();
            IList <IEvent <Guid> > events = eventStore.Get <TestEvent>(event1.Id).ToList();

            timer.Stop();
            Console.WriteLine("Load one operation took {0}", timer.Elapsed);
            Assert.AreEqual(1, events.Count);
            Assert.AreEqual(event1.Id, events.Single().Id);
            Assert.AreEqual(event1.Frameworks.Single(), events.Single().Frameworks.Single());

            timer.Restart();
            events = eventStore.Get <TestEvent>(event2.Id).ToList();
            timer.Stop();
            Console.WriteLine("Load one operation took {0}", timer.Elapsed);
            Assert.AreEqual(1, events.Count);
            Assert.AreEqual(event2.Id, events.Single().Id);
            Assert.AreEqual(event2.Frameworks.Single(), events.Single().Frameworks.Single());

            timer.Restart();
            IList <EventData> correlatedEvents = eventStore.Get(event1.CorrelationId).ToList();

            timer.Stop();
            Console.WriteLine("Load several correlated operation took {0}", timer.Elapsed);
            Assert.AreEqual(2, correlatedEvents.Count);
        }
예제 #16
0
        protected override void ReceiveCommand(IMessageReceiver client, BrokeredMessage message)
#endif
        {
            try
            {
                Logger.LogDebug(string.Format("A command message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBodyAsString();
                ICommand <TAuthenticationToken> command = MessageSerialiser.DeserialiseCommand(messageBody);

                CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
#if NET452
                string topicPath = serviceBusReceiver == null ? "UNKNOWN" : serviceBusReceiver.TopicPath;
#endif
#if NETSTANDARD2_0
                string topicPath = client == null ? "UNKNOWN" : client.Path;
#endif
                Logger.LogInfo($"A command message arrived from topic {topicPath} with the {message.MessageId} was of type {command.GetType().FullName}.");

                Type commandType = command.GetType();

                string targetQueueName = commandType.FullName;

                try
                {
                    object rsn = commandType.GetProperty("Rsn").GetValue(command, null);
                    targetQueueName = string.Format("{0}.{1}", targetQueueName, rsn);
                }
                catch
                {
                    Logger.LogDebug(string.Format("A command message arrived with the id '{0}' was of type {1} but with no Rsn property.", message.MessageId, commandType));
                    // Do nothing if there is no rsn. Just use command type name
                }

                CreateQueueAndAttachListenerIfNotExist(targetQueueName);
                EnqueueCommand(targetQueueName, command);

                // remove the original message from the incoming queue
#if NET452
                message.Complete();
#endif
#if NETSTANDARD2_0
                client.CompleteAsync(message.SystemProperties.LockToken).Wait(1500);
#endif

                Logger.LogDebug(string.Format("A command message arrived and was processed with the id '{0}'.", message.MessageId));
            }
            catch (Exception exception)
            {
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("A command message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
#if NET452
                message.Abandon();
#endif
#if NETSTANDARD2_0
                client.AbandonAsync(message.SystemProperties.LockToken).Wait(1500);
#endif
            }
        }
예제 #17
0
 protected void DequeuAndProcessCommand(string queueName)
 {
     while (true)
     {
         try
         {
             ConcurrentQueue <ICommand <TAuthenticationToken> > queue;
             if (QueueTracker.TryGetValue(queueName, out queue))
             {
                 while (!queue.IsEmpty)
                 {
                     ICommand <TAuthenticationToken> command;
                     if (queue.TryDequeue(out command))
                     {
                         try
                         {
                             CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
                         }
                         catch (Exception exception)
                         {
                             Logger.LogError(string.Format("Trying to set the CorrelationId from the command type {1} for a request for the queue '{0}' failed.", queueName, command.GetType()), exception: exception);
                         }
                         try
                         {
                             AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);
                         }
                         catch (Exception exception)
                         {
                             Logger.LogError(string.Format("Trying to set the AuthenticationToken from the command type {1} for a request for the queue '{0}' failed.", queueName, command.GetType()), exception: exception);
                         }
                         try
                         {
                             ReceiveCommand(command);
                         }
                         catch (Exception exception)
                         {
                             Logger.LogError(string.Format("Processing the command type {1} for a request for the queue '{0}' failed.", queueName, command.GetType()), exception: exception);
                             queue.Enqueue(command);
                         }
                     }
                     else
                     {
                         Logger.LogDebug(string.Format("Trying to dequeue a command from the queue '{0}' failed.", queueName));
                     }
                 }
             }
             else
             {
                 Logger.LogDebug(string.Format("Trying to find the queue '{0}' failed.", queueName));
             }
             Thread.Sleep(100);
         }
         catch (Exception exception)
         {
             Logger.LogError(string.Format("Dequeuing and processing a request for the queue '{0}' failed.", queueName), exception: exception);
         }
     }
 }
예제 #18
0
        public virtual IServiceResponseWithResultData <Entities.InventoryItemEntity> GetByRsn(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceGetByRsnParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            IServiceResponseWithResultData <Entities.InventoryItemEntity> results = null;

            OnGetByRsn(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
예제 #19
0
        public virtual IServiceResponseWithResultData <IEnumerable <Entities.OrderEntity> > GetAllOrders(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, OrderServiceGetAllOrdersParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            IServiceResponseWithResultData <IEnumerable <Entities.OrderEntity> > results = null;

            OnGetAllOrders(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
예제 #20
0
        public virtual IServiceResponse Deactivate(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceDeactivateParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            IServiceResponse results = null;

            OnDeactivate(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
예제 #21
0
        public virtual bool?ReceiveCommand(ICommand <TAuthenticationToken> command)
        {
            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            Type commandType = command.GetType();

            bool response   = true;
            bool isRequired = BusHelper.IsEventRequired(commandType);

            IList <Action <IMessage> > handlers;

            if (Routes.TryGetValue(commandType, out handlers))
            {
                if (handlers != null)
                {
                    if (handlers.Count != 1)
                    {
                        throw new MultipleCommandHandlersRegisteredException(commandType);
                    }
                    if (handlers.Count == 1)
                    {
                        handlers.Single()(command);
                    }
                    else if (isRequired)
                    {
                        throw new NoCommandHandlerRegisteredException(commandType);
                    }
                    else
                    {
                        response = false;
                    }
                }
                else if (isRequired)
                {
                    throw new NoCommandHandlerRegisteredException(commandType);
                }
                else
                {
                    response = false;
                }
            }
            else if (isRequired)
            {
                throw new NoCommandHandlerRegisteredException(commandType);
            }
            else
            {
                response = false;
            }
            return(response);
        }
        protected override void ReceiveEvent(IMessageReceiver client, BrokeredMessage message)
#endif
        {
            try
            {
                Logger.LogDebug(string.Format("An event message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBodyAsString();
                IEvent <TAuthenticationToken> @event = MessageSerialiser.DeserialiseEvent(messageBody);

                CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
                Logger.LogInfo(string.Format("An event message arrived with the id '{0}' was of type {1}.", message.MessageId, @event.GetType().FullName));

                Type eventType = @event.GetType();

                string targetQueueName = eventType.FullName;

                try
                {
                    object rsn = eventType.GetProperty("Rsn").GetValue(@event, null);
                    targetQueueName = string.Format("{0}.{1}", targetQueueName, rsn);
                }
                catch
                {
                    Logger.LogDebug(string.Format("An event message arrived with the id '{0}' was of type {1} but with no Rsn property.", message.MessageId, eventType));
                    // Do nothing if there is no rsn. Just use @event type name
                }

                CreateQueueAndAttachListenerIfNotExist(targetQueueName);
                EnqueueEvent(targetQueueName, @event);

                // remove the original message from the incoming queue
#if NET452
                message.Complete();
#endif
#if NETSTANDARD2_0
                client.CompleteAsync(message.SystemProperties.LockToken).Wait(1500);
#endif

                Logger.LogDebug(string.Format("An event message arrived and was processed with the id '{0}'.", message.MessageId));
            }
            catch (Exception exception)
            {
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("An event message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
#if NET452
                message.Abandon();
#endif
#if NETSTANDARD2_0
                client.AbandonAsync(message.SystemProperties.LockToken).Wait(1500);
#endif
            }
        }
예제 #23
0
        // Run every 15 minutes in release mode
        public static void Run([TimerTrigger("0 1/15 * * * *")] TimerInfo myTimer, Microsoft.Extensions.Logging.ILogger _logger, ExecutionContext context)
#endif
        {
            if (CommandPublisher == null)
            {
                PreapreOnce(context);
            }

            CorrelationIdHelper.SetCorrelationId(Guid.NewGuid());
            CommandPublisher.Publish(new PublishTimeZonesCommand());
            Console.WriteLine($"Published.");
            Logger.LogInfo($"Published.");
        }
예제 #24
0
        public void Add_ValidProjectionView_ProjectionViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettings(), correlationIdHelper);

            var connectionStringFactory = new TestMongoDataStoreConnectionStringFactory();

            TestMongoDataStoreConnectionStringFactory.DatabaseName = string.Format("Test-{0}", new Random().Next(0, 9999));

            var factory = new TestMongoDbDataStoreFactory(logger, connectionStringFactory);
            IMongoCollection <TestEvent> collection = factory.GetTestEventCollection();

            try
            {
                // Arrange
                var dataStore = new MongoDbDataStore <TestEvent>(logger, collection);

                var event1 = new TestEvent
                {
                    Rsn           = Guid.NewGuid(),
                    Id            = Guid.NewGuid(),
                    CorrelationId = correlationIdHelper.GetCorrelationId(),
                    Frameworks    = new List <string> {
                        "Test 1"
                    },
                    TimeStamp = DateTimeOffset.UtcNow
                };

                // Act
                dataStore.Add(event1);

                // Assert
                var timer = new Stopwatch();
                timer.Start();
                TestEvent view = dataStore.SingleOrDefault(e => e.Rsn == event1.Rsn);
                timer.Stop();
                Console.WriteLine("Load operation took {0}", timer.Elapsed);
                Assert.IsNotNull(view);
                Assert.AreEqual(event1.Id, view.Id);
            }
            finally
            {
                // Clean-up
                collection.Database.Client.DropDatabase(TestMongoDataStoreConnectionStringFactory.DatabaseName);
            }
        }
예제 #25
0
            protected virtual void ExecuteReceive(ICommand <TAuthenticationToken> command)
            {
                try
                {
                    AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);
                    CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
                    CommandHandlerResolver.Send(command);

                    Sender.Tell(true);
                }
                catch
                {
                    Sender.Tell(false);
                    throw;
                }
            }
예제 #26
0
            /// <summary>
            /// Passes the provided <paramref name="event"/> to <see cref="EventHandlerResolver"/> via <see cref="IEventPublisher{TAuthenticationToken}.Publish{TEvent}(TEvent)"/>
            /// then calls <see cref="ActorRefImplicitSenderExtensions.Tell"/>.
            /// </summary>
            protected virtual void ExecuteReceive(IEvent <TAuthenticationToken> @event)
            {
                try
                {
                    AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken);
                    CorrelationIdHelper.SetCorrelationId(@event.CorrelationId);
                    EventHandlerResolver.Publish(@event);

                    Sender.Tell(true);
                }
                catch
                {
                    Sender.Tell(false);
                    throw;
                }
            }
예제 #27
0
        /// <summary>
        /// Query for all the events that match the provided CorrelationId.
        /// </summary>
        /// <param name="serviceRequest">A <see cref="IServiceRequestWithData{TAuthenticationToken,TData}">service-request</see> that contains the CorrelationId.</param>
        /// <returns>A collection of <see cref="EventData">event data</see></returns>
        protected virtual IServiceResponseWithResultData <IEnumerable <EventData> > GetEventData(IServiceRequestWithData <TSingleSignOnToken, Guid> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            OnGetEventData(serviceRequest);
            IEnumerable <EventData> results = EventStore.Get(serviceRequest.Data);

            results = OnGotEventData(serviceRequest, results);

            return(new ServiceResponseWithResultData <IEnumerable <EventData> >
            {
                State = ServiceResponseStateType.Succeeded,
                ResultData = results,
                CorrelationId = CorrelationIdHelper.GetCorrelationId()
            });
        }
예제 #28
0
파일: CoreHost.cs 프로젝트: tuga1975/CQRS
        /// <summary>
        /// Prepare the host before registering handlers and starting the host.
        /// </summary>
        protected virtual void Prepare()
        {
            PrepareSecurityProtocol();
            // https://alexandrebrisebois.wordpress.com/2013/03/24/why-are-webrequests-throttled-i-want-more-throughput/
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.DefaultConnectionLimit = 1000;

            new StartUp(ConfigureDefaultDependencyResolver).Initialise();
            EventBus   = DependencyResolver.Current.Resolve <IEventReceiver <TAuthenticationToken> >();
            CommandBus = DependencyResolver.Current.Resolve <ICommandReceiver <TAuthenticationToken> >();
            Guid correlationId = Guid.NewGuid();

            CorrelationIdHelper = DependencyResolver.Current.Resolve <ICorrelationIdHelper>();
            CorrelationIdHelper.SetCorrelationId(correlationId);

            Logger = DependencyResolver.Current.Resolve <ILogger>();
        }
        /// <summary>
        /// Logically delete an existing instance of the <see cref="Entities.OrderEntity"/>
        /// </summary>
        public IServiceResponse DeleteOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            UnitOfWorkService.SetCommitter(this);
            Entities.OrderEntity item = serviceRequest.Data;

            var locatedItem = OrderRepository.Load(item.Rsn, false);

            if (locatedItem == null)
            {
                return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> {
                    State = ServiceResponseStateType.FailedValidation
                }));
            }

            if (locatedItem.IsLogicallyDeleted)
            {
                return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> {
                    State = ServiceResponseStateType.FailedValidation
                }));
            }

            var command = new DeleteOrderCommand(item.Rsn);
            ServiceResponseStateType?serviceResponseStateType = null;

            OnDeleteOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType);
            if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded)
            {
                return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> {
                    State = serviceResponseStateType.Value
                }));
            }

            CommandSender.Send(command);
            OnDeletedOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType);
            if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded)
            {
                return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> {
                    State = serviceResponseStateType.Value
                }));
            }

            UnitOfWorkService.Commit(this);
            return(CompleteResponse(new ServiceResponse()));
        }
예제 #30
0
        public virtual void RegisterHandler <TMessage>(RouteManager routeManger, Action <TMessage> handler, Type targetedType, bool holdMessageLock = true)
            where TMessage : IMessage
        {
            Action <TMessage> registerableHandler = handler;

            if (!holdMessageLock)
            {
                registerableHandler = message =>
                {
                    Task.Factory.StartNew(() =>
                    {
                        CorrelationIdHelper.SetCorrelationId(message.CorrelationId);
                        handler(message);
                    });
                };
            }

            routeManger.RegisterHandler(registerableHandler, targetedType);
        }