Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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;
            }
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
0
        public void Send <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            ICommandValidator <TAuthenticationToken, TCommand> commandValidator = null;

            try
            {
                commandValidator = DependencyResolver.Resolve <ICommandValidator <TAuthenticationToken, TCommand> >();
            }
            catch (Exception exception)
            {
                Logger.LogDebug("Locating an ICommandValidator failed.", string.Format("{0}\\Handle({1})", GetType().FullName, command.GetType().FullName), exception);
            }

            if (commandValidator != null && !commandValidator.IsCommandValid(command))
            {
                Logger.LogInfo("The provided command is not valid.", string.Format("{0}\\Handle({1})", GetType().FullName, command.GetType().FullName));
                return;
            }

            if (command.AuthenticationToken == null)
            {
                command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            command.CorrelationId = CorrelationIdHelper.GetCorrelationId();

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseCommand(command)));
            Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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);
            }
        }
Exemplo n.º 12
0
        public virtual IServiceResponse Deactivate(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceDeactivateParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            IServiceResponse results = null;

            OnDeactivate(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
Exemplo n.º 13
0
        public virtual IServiceResponseWithResultData <IEnumerable <Entities.UserEntity> > GetAll(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, UserServiceGetAllParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            IServiceResponseWithResultData <IEnumerable <Entities.UserEntity> > results = null;

            OnGetAll(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
Exemplo n.º 14
0
        public virtual IServiceResponseWithResultData <Entities.InventoryItemEntity> GetByRsn(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceGetByRsnParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            IServiceResponseWithResultData <Entities.InventoryItemEntity> results = null;

            OnGetByRsn(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
Exemplo n.º 15
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);
         }
     }
 }
Exemplo n.º 16
0
        public virtual IServiceResponseWithResultData <IEnumerable <Entities.InventoryItemSummaryEntity> > GetAll(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceGetAllParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            IServiceResponseWithResultData <IEnumerable <Entities.InventoryItemSummaryEntity> > results = null;

            OnGetAll(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
Exemplo n.º 17
0
        public virtual IServiceResponse CheckIn(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceCheckInParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);
            IServiceResponse results = null;

            OnCheckIn(serviceRequest, ref results);
            return(CompleteResponse(results));
        }
Exemplo n.º 18
0
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            Type eventType = @event.GetType();

            if (@event.Frameworks != null && @event.Frameworks.Contains("Built-In"))
            {
                Logger.LogInfo("The provided event has already been processed by the Built-In bus.", string.Format("{0}\\PrepareAndValidateEvent({1})", GetType().FullName, eventType.FullName));
                return;
            }

            if (@event.AuthenticationToken == null || @event.AuthenticationToken.Equals(default(TAuthenticationToken)))
            {
                @event.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            @event.CorrelationId = CorrelationIdHelper.GetCorrelationId();

            if (string.IsNullOrWhiteSpace(@event.OriginatingFramework))
            {
                @event.TimeStamp            = DateTimeOffset.UtcNow;
                @event.OriginatingFramework = "Built-In";
            }

            var frameworks = new List <string>();

            if (@event.Frameworks != null)
            {
                frameworks.AddRange(@event.Frameworks);
            }
            frameworks.Add("Built-In");
            @event.Frameworks = frameworks;

            bool isRequired;

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

            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("An event handler for '{0}' is not required.", eventType.FullName));
            }

            foreach (Action <IMessage> handler in handlers)
            {
                IList <IEvent <TAuthenticationToken> > events;
                if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                {
                    events.Add(@event);
                }
                handler(@event);
            }
        }
Exemplo n.º 19
0
 protected virtual void PrepareCommand <TCommand>(TCommand command)
     where TCommand : ICommand <TAuthenticationToken>
 {
     if (command.AuthenticationToken == null)
     {
         command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
     }
     command.CorrelationId = CorrelationIdHelper.GetCorrelationId();
 }
Exemplo n.º 20
0
        public virtual InvoicesQueryStrategy WithRsn(Guid rsn)
        {
            QueryPredicate = And(IsNotLogicallyDeleted());
            QueryPredicate = And(WithPermissionScopeUser(AuthenticationTokenHelper.GetAuthenticationToken()));
            QueryPredicate = And(BuildQueryPredicate(WithRsn, rsn));

            OnWithRsn(rsn);

            return(this);
        }
Exemplo n.º 21
0
        public virtual OrderQueryStrategy WithOrderId(int orderId)
        {
            QueryPredicate = And(IsNotLogicallyDeleted());
            QueryPredicate = And(WithPermissionScopeUser(AuthenticationTokenHelper.GetAuthenticationToken()));
            QueryPredicate = And(BuildQueryPredicate(WithOrderId, orderId));

            OnWithOrderId(orderId);

            return(this);
        }
Exemplo n.º 22
0
        public virtual void Send <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            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;
            }

            ICommandValidator <TAuthenticationToken, TCommand> commandValidator = null;

            try
            {
                commandValidator = DependencyResolver.Resolve <ICommandValidator <TAuthenticationToken, TCommand> >();
            }
            catch (Exception exception)
            {
                Logger.LogDebug("Locating an ICommandValidator failed.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName), exception);
            }

            if (commandValidator != null && !commandValidator.IsCommandValid(command))
            {
                Logger.LogInfo("The provided command is not valid.", string.Format("{0}\\Handle({1})", GetType().FullName, commandType.FullName));
                return;
            }

            if (command.AuthenticationToken == null)
            {
                command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            command.CorrelationId = CorrelationIdHelper.GetCorrelationId();

            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);
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            if (@event.AuthenticationToken == null)
            {
                @event.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            @event.CorrelationId = CorrelationIdHelper.GetCorrelationId();
            @event.TimeStamp     = DateTimeOffset.UtcNow;

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event)));
            Logger.LogInfo(string.Format("An event was published with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
        }
Exemplo n.º 25
0
        public IServiceResponseWithResultData <Entities.UserEntity> CreateUser(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.UserEntity> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            UnitOfWorkService.SetCommitter(this);
            Entities.UserEntity item = serviceRequest.Data;
            item.Rsn = Guid.NewGuid();

            var command = new CreateUserCommand(item.Rsn, item.Name);

            OnCreateUser(serviceRequest, command);
            CommandSender.Send(command);
            OnCreatedUser(serviceRequest, command);

            UnitOfWorkService.Commit(this);
            return(CompleteResponse(new ServiceResponseWithResultData <Entities.UserEntity>(item)));
        }
Exemplo n.º 26
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()
            });
        }
        /// <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()));
        }
Exemplo n.º 28
0
        protected virtual void PrepareCommand <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            if (command.AuthenticationToken == null)
            {
                command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            command.CorrelationId = CorrelationIdHelper.GetCorrelationId();

            if (string.IsNullOrWhiteSpace(command.OriginatingFramework))
            {
                command.OriginatingFramework = "Akka";
            }
            IList <string> frameworks = new List <string>(command.Frameworks);

            frameworks.Add("Akka");
            command.Frameworks = frameworks;
        }
Exemplo n.º 29
0
        public virtual void ReceiveCommand(ICommand <TAuthenticationToken> command)
        {
            CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
            AuthenticationTokenHelper.SetAuthenticationToken(command.AuthenticationToken);

            Type commandType = command.GetType();

            bool isRequired;

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

            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 if (isRequired)
                {
                    throw new NoCommandHandlerRegisteredException(commandType);
                }
            }
            else if (isRequired)
            {
                throw new NoCommandHandlerRegisteredException(commandType);
            }
        }
Exemplo n.º 30
0
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            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;
            }

            if (@event.AuthenticationToken == null)
            {
                @event.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            @event.CorrelationId = CorrelationIdHelper.GetCorrelationId();
            @event.TimeStamp     = DateTimeOffset.UtcNow;

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

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

            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)
            {
                IList <IEvent <TAuthenticationToken> > events;
                if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                {
                    events.Add(@event);
                }
                handler(@event);
            }
        }