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); }
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); } }
/// <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); }
/// <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); }
/// <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; } }
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); }
/// <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); }
/// <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); }
/// <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)); }
/// <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)); }
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)); }
public virtual IServiceResponse Deactivate(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, InventoryItemServiceDeactivateParameters> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); IServiceResponse results = null; OnDeactivate(serviceRequest, ref results); return(CompleteResponse(results)); }
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)); }
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); } } }
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)); }
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)); }
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); }
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))); }
/// <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())); }
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); } }
/// <summary> /// Create a new instance of the <see cref="Entities.OrderEntity"/> /// </summary> public IServiceResponseWithResultData <Entities.OrderEntity> CreateOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); UnitOfWorkService.SetCommitter(this); Entities.OrderEntity item = serviceRequest.Data; if (item.Rsn == Guid.Empty) { item.Rsn = Guid.NewGuid(); } var command = new CreateOrderCommand(item.Rsn, item.OrderId, item.CustomerId, item.EmployeeId, item.OrderDate, item.RequiredDate, item.ShippedDate, item.ShipViaId, item.Freight, item.ShipName, item.ShipAddress, item.ShipCity, item.ShipRegion, item.ShipPostalCode, item.ShipCountry); OnCreateOrder(serviceRequest, command); CommandSender.Send(command); OnCreatedOrder(serviceRequest, command); UnitOfWorkService.Commit(this); return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity>(item))); }
/// <summary> /// Update an existing instance of the <see cref="Entities.OrderEntity"/> /// </summary> public IServiceResponseWithResultData <Entities.OrderEntity> UpdateOrder(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); if (locatedItem == null) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = ServiceResponseStateType.FailedValidation })); } var command = new UpdateOrderCommand(item.Rsn, item.OrderId, item.CustomerId, item.EmployeeId, item.OrderDate, item.RequiredDate, item.ShippedDate, item.ShipViaId, item.Freight, item.ShipName, item.ShipAddress, item.ShipCity, item.ShipRegion, item.ShipPostalCode, item.ShipCountry); ServiceResponseStateType?serviceResponseStateType = null; OnUpdateOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType); if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = serviceResponseStateType.Value })); } CommandSender.Send(command); OnUpdatedOrder(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 ServiceResponseWithResultData <Entities.OrderEntity>(item))); }
/// <summary> /// Executes the provided <paramref name="action"/> passing it the provided <paramref name="event"/>, /// then calls <see cref="AggregateRepository{TAuthenticationToken}.PublishEvent"/> /// </summary> protected virtual void Execute <TEvent>(Action <TEvent> action, TEvent @event) where TEvent : IEvent <TAuthenticationToken> { UnitOfWork.Add(this); try { AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(@event.CorrelationId); action(@event); 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() }, { "Event", @event } }); Sender.Tell(false, Self); throw; } }
/// <summary> /// Validate the provided <paramref name="serviceRequest">credentials</paramref> are valid. /// </summary> /// <param name="serviceRequest">The user credentials to validate.</param> /// <returns>The users identifier.</returns> public virtual IServiceResponseWithResultData <Guid?> Login(IServiceRequestWithData <Guid, LoginParameters> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); var userLogin = serviceRequest.Data; if (userLogin == null || string.IsNullOrEmpty(userLogin.EmailAddress) || string.IsNullOrEmpty(userLogin.Password)) { return(CompleteResponse(new ServiceResponseWithResultData <Guid?> { State = ServiceResponseStateType.FailedValidation })); } // Define Query ISingleResultQuery <CredentialQueryStrategy, CredentialEntity> query = QueryFactory.CreateNewSingleResultQuery <CredentialQueryStrategy, CredentialEntity>(); string hash = AuthenticationHashHelper.GenerateCredentialHash(userLogin.EmailAddress, userLogin.Password); query.QueryStrategy.WithHash(hash); // Retrieve Data query = CredentialRepository.Retrieve(query, false); CredentialEntity queryResults = query.Result; var responseData = new ServiceResponseWithResultData <Guid?> { State = queryResults == null ? ServiceResponseStateType.FailedAuthentication : ServiceResponseStateType.Succeeded, ResultData = queryResults == null ? (Guid?)null : queryResults.UserRsn }; // Complete the response ServiceResponseWithResultData <Guid?> response = CompleteResponse(responseData); return(response); }
/// <summary> /// Deserialises and processes the <paramref name="messageBody"/> received from the network through the provided <paramref name="receiveEventHandler"/>. /// </summary> /// <param name="messageBody">A serialised <see cref="IMessage"/>.</param> /// <param name="receiveEventHandler">The handler method that will process the <see cref="IEvent{TAuthenticationToken}"/>.</param> /// <param name="messageId">The network id of the <see cref="IMessage"/>.</param> /// <param name="skippedAction">The <see cref="Action"/> to call when the <see cref="IEvent{TAuthenticationToken}"/> is being skipped.</param> /// <param name="lockRefreshAction">The <see cref="Action"/> to call to refresh the network lock.</param> /// <returns>The <see cref="IEvent{TAuthenticationToken}"/> that was processed.</returns> public virtual IEvent <TAuthenticationToken> ReceiveEvent(string messageBody, Func <IEvent <TAuthenticationToken>, bool?> receiveEventHandler, string messageId, Action skippedAction = null, Action lockRefreshAction = null) { IEvent <TAuthenticationToken> @event; try { @event = MessageSerialiser.DeserialiseEvent(messageBody); } catch (JsonSerializationException exception) { JsonSerializationException checkException = exception; bool safeToExit = false; do { if (checkException.Message.StartsWith("Could not load assembly")) { safeToExit = true; break; } } while ((checkException = checkException.InnerException as JsonSerializationException) != null); if (safeToExit) { const string pattern = @"(?<=^Error resolving type specified in JSON ').+?(?='\. Path '\$type')"; Match match = new Regex(pattern).Match(exception.Message); if (match.Success) { string[] typeParts = match.Value.Split(','); if (typeParts.Length == 2) { string classType = typeParts[0]; bool isRequired = BusHelper.IsEventRequired(string.Format("{0}.IsRequired", classType)); if (!isRequired) { if (skippedAction != null) { skippedAction(); } return(null); } } } } throw; } string eventTypeName = @event.GetType().FullName; CorrelationIdHelper.SetCorrelationId(@event.CorrelationId); AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken); Logger.LogInfo(string.Format("An event message arrived with the {0} was of type {1}.", messageId, eventTypeName)); bool canRefresh; if (!ConfigurationManager.TryGetSetting(string.Format("{0}.ShouldRefresh", eventTypeName), out canRefresh)) { canRefresh = false; } if (canRefresh) { if (lockRefreshAction == null) { Logger.LogWarning(string.Format("An event message arrived with the {0} was of type {1} and was destined to support lock renewal, but no action was provided.", messageId, eventTypeName)); } else { lockRefreshAction(); } } // a false response means the action wasn't handled, but didn't throw an error, so we assume, by convention, that this means it was skipped. bool?result = receiveEventHandler(@event); if (result != null && !result.Value) { if (skippedAction != null) { skippedAction(); } } return(@event); }
/// <summary> /// Takes an <see cref="IEvent{TAuthenticationToken}"/> off the queue of <paramref name="queueName"/> /// and calls <see cref="ReceiveEvent"/>. Repeats in a loop until the queue is empty. /// </summary> /// <param name="queueName">The name of the queue process.</param> protected void DequeuAndProcessEvent(string queueName) { SpinWait.SpinUntil ( () => { try { ConcurrentQueue <IEvent <TAuthenticationToken> > queue; if (QueueTracker.TryGetValue(queueName, out queue)) { while (!queue.IsEmpty) { IEvent <TAuthenticationToken> @event; if (queue.TryDequeue(out @event)) { try { CorrelationIdHelper.SetCorrelationId(@event.CorrelationId); } catch (Exception exception) { Logger.LogError(string.Format("Trying to set the CorrelationId from the event type {1} for a request for the queue '{0}' failed.", queueName, @event.GetType()), exception: exception); } try { AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken); } catch (Exception exception) { Logger.LogError(string.Format("Trying to set the AuthenticationToken from the event type {1} for a request for the queue '{0}' failed.", queueName, @event.GetType()), exception: exception); } try { ReceiveEvent(@event); } catch (Exception exception) { Logger.LogError(string.Format("Processing the event type {1} for a request for the queue '{0}' failed.", queueName, @event.GetType()), exception: exception); queue.Enqueue(@event); } } else { Logger.LogDebug(string.Format("Trying to dequeue a event 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); } // Always return false to keep this spinning. return(false); }, sleepInMilliseconds: 1000 ); }