public void RouteToHandler(ICommand command)
        {
            //optype set in logger context information about the logical operation that the system is executing
            //is used to group log messages togheter and to correlate child log to a logical operation.
            _logger.SetOpType("command", command.GetType().FullName + " Id:" + command.Id);
            
            _logger.Info("[queue] processing command " + command.ToString());

            var commandType = command.GetType();
            
            //get the executor function from the catalog, and then simply execute the command.
            var commandinvoker = _commandHandlerCatalog.GetExecutorFor(commandType);
            try
            {
                commandinvoker.Invoke(command);
                _logger.Info("[queue] command handled " + command.ToString());
            }
            catch (System.Exception ex)
            {
                //TODO log or do something better instead of retrhowing exception
                _logger.Error("[queue] Command error " + ex.Message, ex);
                throw;
            }
            finally 
            {
                _logger.RemoveOpType();
            }
            
        }
Example #2
0
        public void Execute(ICommand command)
        {
            var commandQueue = _commandQueueRouter.Route(command);
            if (commandQueue == null)
            {
                throw new Exception("Could not route the command to an appropriate command queue.");
            }

            var waitHandle = new ManualResetEvent(false);
            var commandAsyncResult = new CommandAsyncResult(waitHandle);

            _commandAsyncResultManager.Add(command.Id, commandAsyncResult);
            commandQueue.Enqueue(command);
            waitHandle.WaitOne(command.MillisecondsTimeout);
            _commandAsyncResultManager.Remove(command.Id);

            if (!commandAsyncResult.IsCompleted)
            {
                throw new CommandTimeoutException(command.Id, command.GetType());
            }
            else if (commandAsyncResult.Exception != null)
            {
                throw new CommandExecuteException(command.Id, command.GetType(), commandAsyncResult.Exception);
            }
            else if (commandAsyncResult.ErrorMessage != null)
            {
                throw new CommandExecuteException(command.Id, command.GetType(), commandAsyncResult.ErrorMessage);
            }
        }
Example #3
0
        public IDictionary<OptionAttribute, PropertyInfo> GetCommandOptions(ICommand command)
        {
            var result = new Dictionary<OptionAttribute, PropertyInfo>();

            foreach (PropertyInfo propInfo in command.GetType().GetProperties())
            {
                if (!command.IncludedInHelp(propInfo.Name))
                {
                    continue;
                }

                foreach (OptionAttribute attr in propInfo.GetCustomAttributes(typeof(OptionAttribute), inherit: true))
                {
                    if (!propInfo.CanWrite && !TypeHelper.IsMultiValuedProperty(propInfo))
                    {
                        // If the property has neither a setter nor is of a type that can be cast to ICollection<> then there's no way to assign 
                        // values to it. In this case throw.
                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("OptionInvalidWithoutSetter"), command.GetType().FullName + "." + propInfo.Name));
                    }
                    result.Add(attr, propInfo);
                }
            }

            return result;
        }
Example #4
0
        public string GetCommandTopic(ICommand command)
        {
            if (_commandTopics.ContainsKey(command.GetType()))
                return _commandTopics[command.GetType()];

            return command.GetType().Namespace;
        }
Example #5
0
 /// <summary>
 /// Executes the supplied command asynchronously.
 /// </summary>
 /// <param name="command">The command to execute.</param>
 public static void Excute(ICommand command)
 {
     Task.Factory
         .StartNew(() =>
                       {
                           Log.Debug(string.Format("Executing '{0}'.", command.GetType()));
                           command.Execute();
                       }, TaskCreationOptions.LongRunning)
         .ContinueWith(task => Log.Fatal(string.Format("'{0}', failed.", command.GetType()), task.Exception), TaskContinuationOptions.OnlyOnFaulted);
 }
        public virtual void Publish(ICommand command)
        {
            Logger.Verbose("Authorizing command {0}", command.GetType().Name);

            commandAuthorizer.Authorize(command);

            Logger.Verbose("Publishing command {0}", command.GetType().Name);

            commandRetry.Retry(TryPublish, command);
        }
        /// <summary>
        /// Dispatch the command
        /// </summary>
        /// <param name="command">Command to invoke</param>
        public void Dispatch(ICommand command)
        {
            if (command == null) throw new ArgumentNullException("command");

            var handlerType = typeof(IHandlerOf<>).MakeGenericType(command.GetType());
            var method = handlerType.GetMethod("Invoke", new Type[] { command.GetType() });

            var handler = _serviceLocator.Resolve(handlerType);
            var decorated = Decorate(command.GetType(), handler);

            // workaround so that TargetInvocationException is not thrown.
            ((dynamic) decorated).Invoke((dynamic)command);
        }
 public void Dispatch(ICommand cmd)
 {
     try
     {
         this.bus.Dispatch(cmd);
         this.Log(cmd.GetType().FullName, this.ToJson(cmd), this.SerializeObject(cmd), true);
     }
     catch (Exception ex)
     {
         var str = new string(ex.ToString().Take(499).ToArray());
         this.Log(cmd.GetType().FullName, str, this.SerializeObject(cmd), false);
         throw;
     }
 }
        private void AuthorizeCommand(ICommand command)
        {
            var authorizeAttribute = Attribute.GetCustomAttributes(command.GetType())
               .FirstOrDefault(x => x is AuthorizeAttribute) as AuthorizeAttribute;

            if (authorizeAttribute == null || currentUser.IsInRole(authorizeAttribute.Roles))
            {
                return;
            }

            string message = String.Format("User {0} attempted to execute command {1} which requires roles {2}", currentUser, command.GetType().Name, authorizeAttribute);

            throw new UnauthorizedAccessException(message);
        }
 public void Publish(ICommand command)
 {
     try
     {
         Logger.Verbose("Publishing command {0}", command.GetType().Name);
         publisher.Publish(command);
         Logger.Verbose("Completed publishing command {0}", command.GetType().Name);
     }
     catch (Exception ex)
     {
         Logger.Error("Error: {0}", ex.Message);
         throw;
     }
 }
Example #11
0
        public bool Execute(ICommand command)
        {
            var commandHandler = _commandHandlerProvider.GetCommandHandler(command);

            if (commandHandler == null)
            {
                _logger.ErrorFormat("Command handler not found for {0}", command.GetType().FullName);
                return true;
            }

            try
            {
                _trackingContext.Clear();
                _processingCommandCache.Add(command);
                commandHandler.Handle(_commandContext, command);
                return CommitContextChanges(command);
            }
            catch (Exception ex)
            {
                var commandHandlerType = (commandHandler as ICommandHandlerWrapper).GetInnerCommandHandler().GetType();
                _logger.Error(string.Format("Unknown exception raised when {0} handling {1}, command id:{2}.", commandHandlerType.Name, command.GetType().Name, command.Id), ex);
                _commandAsyncResultManager.TryComplete(command.Id, ex);
            }
            finally
            {
                _trackingContext.Clear();
                _processingCommandCache.TryRemove(command.Id);
            }

            return true;
        }
Example #12
0
        public void Process(ICommand command)
        {
            var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());
            dynamic handler = _context.Resolve(handlerType);

            handler.Handle((dynamic)command);
        }
        public IEnumerable<ICommandValidator> GetValidators(ICommand command)
        {
            if (command == null) throw new ArgumentNullException("command");

            var validatorType = typeof (ICommandValidator<>).MakeGenericType(command.GetType());
            return locator.GetAllInstances(validatorType).Cast<ICommandValidator>();
        }
 public IEnumerable<ICommandHandler> GetHandlers(ICommand command)
 {
     if (command == null) throw new ArgumentNullException("command");
     var commandType = command.GetType();
     var handlerType = typeof (ICommandHandler<>).MakeGenericType(commandType);
     return locator.GetAllInstances(handlerType).Cast<ICommandHandler>();
 }
Example #15
0
 internal CommandContext(ICommand command)
 {
     Command = command;
     CommandType = command.GetType();
     _cancellationTokenSource = new CancellationTokenSource();
     CancellationToken = _cancellationTokenSource.Token;
 }
        public List<ICommand> listReadyCommandsWithTypeFilter(ICommand aktCommandType)
        {
            if (aktCommandType.GetType() == typeof(comSolveKollision))
            {
                return listReadyCommands;
            }
            List<ICommand> listReadyCommandsFilter = new List<ICommand>();

            foreach (ICommand aktCom in listReadyCommands)
            {
                if (aktCom.GetType() == aktCommandType.GetType())
                    listReadyCommandsFilter.Add(aktCom);
            }

            return listReadyCommandsFilter;
        }
        /// <summary>
        /// Gets the property value from the first matched property. The match is made by the name and the type of the specified parameter.
        /// </summary>
        /// <remarks>The property match is done by the name and type, where the name is matched case insensitive and the type of the 
        /// parameter type should be assignable from the property type.</remarks>
        /// <param name="command">The command.</param>
        /// <param name="parameterInfo">The parameter info.</param>
        /// <exception cref="ArgumentNullException">Thrown when <i>command</i> or <i>parameterInfo</i> is null.</exception>
        /// <returns>The value from the first matched property.</returns>
        public static object GetPropertyValueBasedOnParameterInfo(ICommand command, ParameterInfo parameterInfo)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (parameterInfo == null) throw new ArgumentNullException("parameterInfo");

            // Initialize result with the default value based on the type.
            var type = parameterInfo.ParameterType;
            object result = type.IsValueType ? Activator.CreateInstance(type) : null;

            // Get all properties that match name of the specified parameter and where the property type
            // is assignable from the parameter type.
            var query = from prop in command.GetType().GetProperties()
                        where prop.Name.Equals(parameterInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
                              parameterInfo.ParameterType.IsAssignableFrom(prop.PropertyType)
                        select prop;

            // Get the first property, if found.
            var propertyInfo = query.FirstOrDefault();

            // If there is a property found, get the value from it.
            if (propertyInfo != null)
            {
                result = propertyInfo.GetValue(command, null);
            }

            return result;
        }
Example #18
0
        public void Execute(ICommand command)
        {
            var commandHandler = _commandHandleProvider.GetInternalCommandHandle(command.GetType());

            var commandContext = new CommandContext(_repository);

            commandHandler(commandContext, command);

            var aggregateRoots = commandContext.AggregateRoots;

            if (aggregateRoots.Count > 1)
                throw new Exception("one command handler can change just only one aggregateRoot.");

            var aggregateRoot = aggregateRoots.First().Value;

            var domainEvents = aggregateRoot.GetUnCommitEvents();

            var eventStream = BuildEventStream(aggregateRoot, command.CommandId);

            _eventStore.AppendAsync(eventStream);

            if (aggregateRoot.Version % 3 == 0)
                _snapshotStorage.Create(new SnapshotRecord(aggregateRoot.AggregateRootId, aggregateRoot.Version,
                    _binarySerializer.Serialize(aggregateRoot)));

            _eventPublisher.PublishAsync(domainEvents);

            aggregateRoot.Clear();

            Console.WriteLine(aggregateRoot.ToString());

            Console.WriteLine("DomainEvents count is {0}", domainEvents.Count);
        }
Example #19
0
        //private static void UpdateCheckedState(StopAstConversion stopCode)
        //{
        //    // this does not work.
        //    foreach (MenuItem item in MainWindow.Instance.GetMainMenuItems())
        //    {
        //        if (!(item.Command is StopMenuCommand))
        //            continue;
        //        var attr = GetAttribute(item.Command);

        //        if (attr.StopCode == stopCode)
        //        {
        //            item.IsCheckable = true;
        //            item.IsChecked = true;
        //        }
        //        else
        //        {
        //            item.IsChecked = false;
        //        }
        //    }
        //}

        private static StopRLMenuCommandAttribute GetAttribute(ICommand command)
        {
            var attr = command.GetType().GetCustomAttributes(typeof(StopRLMenuCommandAttribute), true)
                              .Cast<StopRLMenuCommandAttribute>()
                              .FirstOrDefault();
            return attr;
        }
Example #20
0
        public void Execute(ICommand command)
        {
            var handlerType = typeof(IHandleCommand<>).MakeGenericType(command.GetType());
            dynamic handler = _container.GetInstance(handlerType);

            handler.Handle((dynamic)command);
        }
        public virtual void Execute(ICommand command)
        {
            var context = new CommandContext(command);
            var interceptors = _container.ResolveAll<ICommandServiceInterceptor>().ToList();
            try
            {
               interceptors.ForEach(i => i.OnBeforeBeforeExecutorResolving(context));

                var executor = GetExecutorForCommand(command);
                if (executor == null) throw new ExecutorForCommandNotFoundException(command.GetType());
                context = new CommandContext(command, CommandExecutionState.Resolved);
                interceptors.ForEach(i => i.OnBeforeExecution(context));
                executor.Execute((dynamic) command);
                context = new CommandContext(command, CommandExecutionState.Called);
            }
            catch (Exception ex)
            {
                context = new CommandContext(command, CommandExecutionState.Called, ex);
                throw;
            }
            finally
            {
                interceptors.ForEach(i => i.OnAfterExecution(context));
            }
        }
Example #22
0
 public Type GetByCommand(ICommand commandType)
 => this.HandlerTypes
 .SingleOrDefault(x =>
                  x.GetInterfaces()
                  .First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler <>))
                  .GetGenericArguments()[0] == commandType?.GetType()
                  );
Example #23
0
        /// <summary>
        /// Log command
        /// </summary>
        public void LogCommand(ICommand command)
        {
            try
            {
                // Initialize command TypeName if not already initialized
                if (String.IsNullOrEmpty(command.Metadata.TypeName))
                    command.Metadata.TypeName = command.GetType().FullName;

                var commandDocument = command.ToBsonDocument();

                // Removing _t element (generated by mongodb driver)
                commandDocument.Remove("_t");

                var record = new BsonDocument
                {
                    { "_id", command.Metadata.CommandId },
                    { "Command", commandDocument },
                    { "Handlers", new BsonArray() },
                    { "Events", new BsonArray() }
                };

                Logs.Logs.Insert(record);
            }
            catch(Exception)
            {
                // Catch all errors because logging should not throw errors if unsuccessful
            }
        }
Example #24
0
 public void RegisterProcessingCommand(ICommand command, CommandReturnType commandReturnType, TaskCompletionSource<AsyncTaskResult<CommandResult>> taskCompletionSource)
 {
     if (!_commandTaskDict.TryAdd(command.Id, new CommandTaskCompletionSource { CommandReturnType = commandReturnType, TaskCompletionSource = taskCompletionSource }))
     {
         throw new Exception(string.Format("Duplicate processing command registration, type:{0}, id:{1}", command.GetType().Name, command.Id));
     }
 }
        public bool TrySetValue(ICommand target, IEnumerable<string> values)
        {
            var pi = target.GetType().GetProperty(_propertyName);
            var destinationType = pi.PropertyType;

            if (IsValueRequired == false && values.Count() == 0)
            {
                if (destinationType == typeof(bool))
                    pi.SetValue(target, true, null);
                else if (destinationType.IsValueType)
                    pi.SetValue(target, Activator.CreateInstance(destinationType), null);
                else
                    pi.SetValue(target, null, null);
                return true;
            }
            object value;

            if (!StringConversion.TryConvert(destinationType, values, out value))
                return false;
            try
            {
                pi.SetValue(target, value, null);
                return true;
            }
            catch
            {
            }
            return false;
        }
 public static void Invoke(object self, ICommand<IIdentity> command)
 {
     self.GetType()
         .GetMethods()
         .Where(m => m.Name == "When")
         .Single(m => m.GetParameters()[0].ParameterType == command.GetType())
         .Invoke(self, new object[] { command });
 }
Example #27
0
        /// <summary>
        /// Add a new message to the queue.
        /// </summary>
        /// <param name="command">Command message to add.</param>
        public void AddMessage(
            ICommand command)
        {
            var queue = GetQueueReference(command.GetType().Name);
            var message = new CloudQueueMessage(JsonConvert.SerializeObject(command));

            queue.AddMessage(message);
        }
        public static void RegisterCommand(this ICanBeUpdatedByCommand document, ICommand command)
        {
            document.LastCommand = command.GetType().Name;
            document.LastCommandBy = command.CommandByUser;
            document.LastCommandDate = command.CommandWhen;

            RegisterCompanyCommand(document as IBelongToCompany, command as ICompanyCommand);
        }
        public void Process(ICommand command)
        {
            Type handlerType = typeof(IHandleCommand<>).MakeGenericType(command.GetType());

            dynamic handler = TinyIoCContainer.Current.Resolve(handlerType);

            handler.HandleCommand((dynamic)command);
        }
        public virtual void Publish(ICommand command)
        {
            Type handlerGenericType = typeof(IHandleCommand<>);
            Type handlerType = handlerGenericType.MakeGenericType(new[] { command.GetType() });
            object handler = handlers.Single(handlerType.IsInstanceOfType);

            ((dynamic)handler).Execute((dynamic)command);
        }
Example #31
0
        public void Execute(ICommand command)
        {
            Contract.Requires<ArgumentNullException>(command != null);

            var type = command.GetType();
            if (_handlers.ContainsKey(type))
                _handlers[type](command);
        }
Example #32
0
            public override string ToString()
            {
                ICommand command = Command;
                
                if (command == null)
                    command = AsyncCommand;

                return command?.GetType().ToString();
            }
 private void HandleMessageMapping(ConcurrentDictionary <Type, List <Guid> > data, ICommand cmd)
 {
     try
     {
         var mapValue = this._commandMappingProvider.Find(cmd);
         foreach (var item in mapValue)
         {
             data.AddOrUpdate(item.Value, AddValue(new List <Guid>(), item.Key), (a, b) => AddValue(b, item.Key));
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, $"执行缓存映射错误,无法正确进行缓存,类型:{cmd?.GetType().Name}");
     }
 }
Example #34
0
 public void Execute(ICommand command, CommandAction commandAction = CommandAction.Default)
 {
     try
     {
         Logger.WriteLine($"Executing Command: {command?.GetType().FullName}");
         command.Execute(commandAction);
     }
     catch (TestExecutionException ex)
     {
         if (!HandleException(ex))
         {
             throw;
         }
     }
 }
Example #35
0
        public bool HandleCommand(ICommand cmd)
        {
            if (cmd is LockStateChangedCommand chCmd)
            {
                lock (_ownersLock)
                {
                    if (!chCmd.Locked)
                    {
                        _owners[chCmd.Index] = LockOwner.None;
                    }
                    else if (!_owners.ContainsKey(chCmd.Index) || _owners[chCmd.Index] == LockOwner.None)
                    {
                        _owners[chCmd.Index] = LockOwner.Other;
                    }
                }

                return(true);
            }

            if (cmd is LockObtainedCommand obCmd)
            {
                lock (_ownersLock)
                {
                    _owners[obCmd.Index] = LockOwner.This;

                    GotLock(obCmd.Index);
                }

                return(true);
            }

            lock (_jobLock)
            {
                if (_currentJob == null)
                {
                    // TODO - send error?
                    return(false);
                }

                // The atem sends this 'error' while we are not allowed/able to download the asset. we should keep retrying the same start until it succeeds
                // Note: perhaps this means that someone else has the lock, but we have the lock which will become valid once their transfer completes?
                if (cmd is DataTransferErrorCommand errCmd && _currentId == errCmd.TransferId)
                {
                    // This can happen sometimes, and we should retry until it works
                    if (errCmd.ErrorCode == DataTransferError.TryAgain && _currentStartCommand != null)
                    {
                        _connection.QueueCommand(_currentStartCommand);
                        return(true);
                    }

                    // The asset was not found, or some unknown error meaning we should fail and move on
                    if (_currentJob != null)
                    {
                        if (errCmd.ErrorCode != DataTransferError.NotFound)
                        {
                            // We don't know the error, so abort the transfer
                            _connection.QueueCommand(new DataTransferAbortCommand
                            {
                                TransferId = _currentId
                            });
                        }

                        ReleaseLock(_currentJob.StoreId);
                        _currentJob.Fail();

                        _currentStartCommand = null;
                        _currentJob          = null;
                    }

                    // Try and get next job started
                    DequeueAndRun();
                    return(true);
                }

                if (cmd is DataTransferCompleteCommand completeCmd && _currentId != completeCmd.TransferId)
                {
                    // TODO - should we try and start our job?
                    return(false);
                }

                if (!AcceptedCommands.Contains(cmd.GetType()) || !_currentJob.StartedAt.HasValue)
                {
                    return(false);
                }

                var res = _currentJob.OnMessage(cmd, _connection);
                switch (res)
                {
                case DataTransferStatus.OK:
                    break;     // Job is still working away

                case DataTransferStatus.Success:

                    ReleaseLock(_currentJob.StoreId);

                    _currentStartCommand = null;
                    _currentJob          = null;

                    DequeueAndRun();

                    break;

                case DataTransferStatus.Unknown:
                    // Command was not handled, this is probably ok
                    // TODO - we should track the time of the last handled command so we can check for stuck transfers
                    return(false);
                }

                return(true);
            }
        }
        public CommandResponse Dispatch(ICommand command)
        {
            try
            {
                m_commandDispatcher.Dispatch(command);

                return(new CommandResponse
                {
                    CommandStatus = CommandStatusEnum.Succeeded,
                    ContainsException = false,
                });
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("There was an error while attempting to handle a command of type '{0}'.", command.GetType()), ex);
                return(new CommandResponse
                {
                    CommandStatus = CommandStatusEnum.Failed,
                    ContainsException = true,
                    Exception = ex.ToString(),
                    Message = ex.Message
                });
            }
        }
        void Wait(ICommand command)
        {
            Type t = command.GetType();

#if !NETFX_CORE
            if (t.IsGenericType)
            {
#else
            if (t.IsGenericType())
            {
#endif
                Type genericType = t.GetGenericArguments()[0];

                GetType().GetMethod("Wait2", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).
                MakeGenericMethod(genericType).Invoke(this, new object[] { command });
            }
            else
            {
                Wait1(command);
            }
        }

        void Wait1(ICommand command)
        {
            ((AsyncCommand)command).executeTask.Wait(TimeSpan.FromSeconds(latencyTime));
        }

        void Wait2 <T>(ICommand command)
        {
            ((AsyncCommand <T>)command).executeTask.Wait(TimeSpan.FromSeconds(latencyTime));
        }

#if !NETFX_CORE
        bool executingAsyncMethod = false;
        AsyncCommand <int> asyncTestCommand;

        Task AsyncExecuteMethod(int timeout)
        {
            return(Task.Factory.StartNew(() => {
                for (int i = 0; i < 10; i++)
                {
                    if (asyncTestCommand.ShouldCancel)
                    {
                        break;
                    }
                    if (timeout == 0)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        Thread.Sleep(timeout);
                    }
                }
                executingAsyncMethod = false;
            }));
        }

        Task AsyncExecuteMethod2(int timeout)
        {
            return(Task.Factory.StartNew(() => {
                for (int i = 0; i < 10; i++)
                {
                    if (asyncTestCommand.IsCancellationRequested)
                    {
                        break;
                    }
                    if (timeout == 0)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        Thread.Sleep(timeout);
                    }
                }
                executingAsyncMethod = false;
            }));
        }
Example #38
0
        private object GetHandler <TResult>(ICommand <TResult> query)
        {
            var handlerType = typeof(ICommandHandler <,>).MakeGenericType(query.GetType(), typeof(TResult));

            return(_serviceProvider.GetService(handlerType));
        }
Example #39
0
 public void AddCommand(ICommand command)
 {
     if (command is ColorCommand colorCommand)
     {
         Color(colorCommand.Easing, colorCommand.StartTime, colorCommand.EndTime, colorCommand.StartValue, colorCommand.EndValue);
     }
     else if (command is FadeCommand fadeCommand)
     {
         Fade(fadeCommand.Easing, fadeCommand.StartTime, fadeCommand.EndTime, fadeCommand.StartValue, fadeCommand.EndValue);
     }
     else if (command is ScaleCommand scaleCommand)
     {
         Scale(scaleCommand.Easing, scaleCommand.StartTime, scaleCommand.EndTime, scaleCommand.StartValue, scaleCommand.EndValue);
     }
     else if (command is VScaleCommand vScaleCommand)
     {
         ScaleVec(vScaleCommand.Easing, vScaleCommand.StartTime, vScaleCommand.EndTime, vScaleCommand.StartValue, vScaleCommand.EndValue);
     }
     else if (command is ParameterCommand parameterCommand)
     {
         Parameter(parameterCommand.Easing, parameterCommand.StartTime, parameterCommand.EndTime, parameterCommand.StartValue);
     }
     else if (command is MoveCommand moveCommand)
     {
         Move(moveCommand.Easing, moveCommand.StartTime, moveCommand.EndTime, moveCommand.StartValue, moveCommand.EndValue);
     }
     else if (command is MoveXCommand moveXCommand)
     {
         MoveX(moveXCommand.Easing, moveXCommand.StartTime, moveXCommand.EndTime, moveXCommand.StartValue, moveXCommand.EndValue);
     }
     else if (command is MoveYCommand moveYCommand)
     {
         MoveY(moveYCommand.Easing, moveYCommand.StartTime, moveYCommand.EndTime, moveYCommand.StartValue, moveYCommand.EndValue);
     }
     else if (command is RotateCommand rotateCommand)
     {
         Rotate(rotateCommand.Easing, rotateCommand.StartTime, rotateCommand.EndTime, rotateCommand.StartValue, rotateCommand.EndValue);
     }
     else if (command is LoopCommand loopCommand)
     {
         StartLoopGroup(loopCommand.StartTime, loopCommand.LoopCount);
         foreach (var cmd in loopCommand.Commands)
         {
             AddCommand(cmd);
         }
         EndGroup();
     }
     else if (command is TriggerCommand triggerCommand)
     {
         StartTriggerGroup(triggerCommand.TriggerName, triggerCommand.StartTime, triggerCommand.EndTime, triggerCommand.Group);
         foreach (var cmd in triggerCommand.Commands)
         {
             AddCommand(cmd);
         }
         EndGroup();
     }
     else
     {
         throw new NotSupportedException($"Failed to add command: No support for adding command of type {command.GetType().FullName}");
     }
 }
Example #40
0
 /// <summary>
 /// Handles commands.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <returns>Task&lt;IList&lt;IEvent&gt;&gt;.</returns>
 /// <exception cref="System.InvalidOperationException"></exception>
 public virtual Task <IList <IEvent> > HandleCommand(ICommand command)
 => throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.InvalidCommand, command?.GetType().Name, GetType().Name));
Example #41
0
        /// <summary>
        /// Receives <see cref="EventData"/> from the command bus.
        /// </summary>
        protected virtual void ReceiveCommand(PartitionContext context, EventData eventData)
        {
            DateTimeOffset startedAt     = DateTimeOffset.UtcNow;
            Stopwatch      mainStopWatch = Stopwatch.StartNew();
            string         responseCode  = "200";
            // Null means it was skipped
            bool?              wasSuccessfull            = true;
            string             telemetryName             = string.Format("Cqrs/Handle/Command/{0}", eventData.SequenceNumber);
            ISingleSignOnToken authenticationToken       = null;
            Guid?              guidAuthenticationToken   = null;
            string             stringAuthenticationToken = null;
            int?intAuthenticationToken = null;

            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/EventHub" }
            };
            object value;

            if (eventData.Properties.TryGetValue("Type", out value))
            {
                telemetryProperties.Add("MessageType", value.ToString());
            }
            TelemetryHelper.TrackMetric("Cqrs/Handle/Command", CurrentHandles++, telemetryProperties);
            // Do a manual 10 try attempt with back-off
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Logger.LogDebug(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}'.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));
                    string messageBody = Encoding.UTF8.GetString(eventData.GetBytes());

                    ICommand <TAuthenticationToken> command = AzureBusHelper.ReceiveCommand(messageBody, ReceiveCommand,
                                                                                            string.Format("partition key '{0}', sequence number '{1}' and offset '{2}'", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset),
                                                                                            ExtractSignature(eventData),
                                                                                            SigningTokenConfigurationKey,
                                                                                            () =>
                    {
                        wasSuccessfull = null;
                        telemetryName  = string.Format("Cqrs/Handle/Command/Skipped/{0}", eventData.SequenceNumber);
                        responseCode   = "204";
                        // Remove message from queue
                        context.CheckpointAsync(eventData);
                        Logger.LogDebug(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but processing was skipped due to command settings.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));
                        TelemetryHelper.TrackEvent("Cqrs/Handle/Command/Skipped", telemetryProperties);
                    }
                                                                                            );

                    if (wasSuccessfull != null)
                    {
                        if (command != null)
                        {
                            telemetryName       = string.Format("{0}/{1}", command.GetType().FullName, command.Id);
                            authenticationToken = command.AuthenticationToken as ISingleSignOnToken;
                            if (AuthenticationTokenIsGuid)
                            {
                                guidAuthenticationToken = command.AuthenticationToken as Guid?;
                            }
                            if (AuthenticationTokenIsString)
                            {
                                stringAuthenticationToken = command.AuthenticationToken as string;
                            }
                            if (AuthenticationTokenIsInt)
                            {
                                intAuthenticationToken = command.AuthenticationToken as int?;
                            }

                            var telemeteredMessage = command as ITelemeteredMessage;
                            if (telemeteredMessage != null)
                            {
                                telemetryName = telemeteredMessage.TelemetryName;
                            }

                            telemetryName = string.Format("Cqrs/Handle/Command/{0}", telemetryName);
                        }
                        // Remove message from queue
                        context.CheckpointAsync(eventData);
                    }
                    Logger.LogDebug(string.Format("A command message arrived and was processed with the partition key '{0}', sequence number '{1}' and offset '{2}'.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));

                    wasSuccessfull = true;
                    responseCode   = "200";
                    return;
                }
                catch (UnAuthorisedMessageReceivedException exception)
                {
                    TelemetryHelper.TrackException(exception, null, telemetryProperties);
                    // Indicates a problem, unlock message in queue
                    Logger.LogError(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but was not authorised.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset), exception: exception);
                    wasSuccessfull = false;
                    responseCode   = "401";
                    telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                    telemetryProperties.Add("ExceptionMessage", exception.Message);
                }
                catch (NoHandlersRegisteredException exception)
                {
                    TelemetryHelper.TrackException(exception, null, telemetryProperties);
                    // Indicates a problem, unlock message in queue
                    Logger.LogError(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but no handlers were found to process it.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset), exception: exception);
                    wasSuccessfull = false;
                    responseCode   = "501";
                    telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                    telemetryProperties.Add("ExceptionMessage", exception.Message);
                }
                catch (NoHandlerRegisteredException exception)
                {
                    TelemetryHelper.TrackException(exception, null, telemetryProperties);
                    // Indicates a problem, unlock message in queue
                    Logger.LogError(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but no handler was found to process it.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset), exception: exception);
                    wasSuccessfull = false;
                    responseCode   = "501";
                    telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                    telemetryProperties.Add("ExceptionMessage", exception.Message);
                }
                catch (Exception exception)
                {
                    // Indicates a problem, unlock message in queue
                    Logger.LogError(string.Format("A command message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but failed to be process.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset), exception: exception);

                    switch (i)
                    {
                    case 0:
                    case 1:
                        // 10 seconds
                        Thread.Sleep(10 * 1000);
                        break;

                    case 2:
                    case 3:
                        // 30 seconds
                        Thread.Sleep(30 * 1000);
                        break;

                    case 4:
                    case 5:
                    case 6:
                        // 1 minute
                        Thread.Sleep(60 * 1000);
                        break;

                    case 7:
                    case 8:
                        // 3 minutes
                        Thread.Sleep(3 * 60 * 1000);
                        break;

                    case 9:
                        telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                        telemetryProperties.Add("ExceptionMessage", exception.Message);
                        break;
                    }
                    wasSuccessfull = false;
                    responseCode   = "500";
                }
                finally
                {
                    // Eventually just accept it
                    context.CheckpointAsync(eventData);

                    TelemetryHelper.TrackMetric("Cqrs/Handle/Command", CurrentHandles--, telemetryProperties);

                    mainStopWatch.Stop();
                    if (guidAuthenticationToken != null)
                    {
                        TelemetryHelper.TrackRequest
                        (
                            telemetryName,
                            guidAuthenticationToken,
                            startedAt,
                            mainStopWatch.Elapsed,
                            responseCode,
                            wasSuccessfull == null || wasSuccessfull.Value,
                            telemetryProperties
                        );
                    }
                    else if (intAuthenticationToken != null)
                    {
                        TelemetryHelper.TrackRequest
                        (
                            telemetryName,
                            intAuthenticationToken,
                            startedAt,
                            mainStopWatch.Elapsed,
                            responseCode,
                            wasSuccessfull == null || wasSuccessfull.Value,
                            telemetryProperties
                        );
                    }
                    else if (stringAuthenticationToken != null)
                    {
                        TelemetryHelper.TrackRequest
                        (
                            telemetryName,
                            stringAuthenticationToken,
                            startedAt,
                            mainStopWatch.Elapsed,
                            responseCode,
                            wasSuccessfull == null || wasSuccessfull.Value,
                            telemetryProperties
                        );
                    }
                    else
                    {
                        TelemetryHelper.TrackRequest
                        (
                            telemetryName,
                            authenticationToken,
                            startedAt,
                            mainStopWatch.Elapsed,
                            responseCode,
                            wasSuccessfull == null || wasSuccessfull.Value,
                            telemetryProperties
                        );
                    }

                    TelemetryHelper.Flush();
                }
            }
        }
Example #42
0
 public string GetResultText <TReq, TRes>(ICommand <TReq, TRes> command, TRes result) => $"Korisnik je izvrsio komandu {command.GetType().Name}, server je odgovorio: {JsonConvert.SerializeObject(result)};";
Example #43
0
 public CommandTypeInfo(ICommand command)
 {
     Command = command;
     CommandType = command.GetType();
 }
Example #44
0
 /// <summary>
 /// Initializes a new instance <see cref="UnhandledCommandException"/>
 /// </summary>
 /// <param name="command"><see cref="ICommand"/> that wasn't handled</param>
 public UnhandledCommandException(ICommand command) : base(string.Format(ExceptionStrings.UnhandledCommandException, command.GetType()))
 {
     Command = command;
 }
Example #45
0
 private void ActualCommandProcessing(ICommand command)
 {
     _commandMeter.Mark(command.GetType().Name);
 }
Example #46
0
        private Executor GetExecutorInfo(ICommand command, ICommandHandler handler)
        {
            var commandHandlerName = string.Format("{0}+{1}", command.GetType().FullName, handler.GetType().FullName);

            return(Executors.GetOrAdd(commandHandlerName, CreateExecutor(command, handler)));
        }
Example #47
0
        private async Task <TResult> ExecuteCommandWithHandlers <TResult>(ICommand <TResult> command, ICommandDispatchContext dispatchContext, CancellationToken cancellationToken)
        {
            IReadOnlyCollection <IPrioritisedCommandHandler> handlers = _commandRegistry.GetPrioritisedCommandHandlers(command);

            if (handlers == null || handlers.Count == 0)
            {
                throw new MissingCommandHandlerRegistrationException(command.GetType(),
                                                                     "No command actors registered for execution of command");
            }
            TResult result = default(TResult);

            int handlerIndex = 0;

            foreach (IPrioritisedCommandHandler handlerTemplate in handlers)
            {
                object baseHandler = null;
                try
                {
                    baseHandler = _commandHandlerFactory.Create(handlerTemplate.CommandHandlerType);
                    if (baseHandler == null)
                    {
                        throw new UnableToExecuteHandlerException($"A handler of type {handlerTemplate.CommandHandlerType} is registered but resolution returned null. Please check IoC configuration.");
                    }

                    if (baseHandler is ICommandHandler handler)
                    {
                        result = await _commandHandlerExecuter.ExecuteAsync(handler, command, result, cancellationToken);
                    }
                    else
                    {
                        if (baseHandler is IPipelineAwareCommandHandler chainHandler)
                        {
                            PipelineAwareCommandHandlerResult <TResult> chainResult =
                                await _pipelineAwareCommandHandlerExecuter.ExecuteAsync(chainHandler, command, result, cancellationToken);

                            result = chainResult.Result;
                            if (chainResult.ShouldStop)
                            {
                                break;
                            }
                        }
                        else
                        {
                            throw new UnableToExecuteHandlerException("Unexpected result type");
                        }
                    }
                }
                catch (Exception ex)
                {
                    bool shouldContinue =
                        await _commandExecutionExceptionHandler.HandleException(ex, baseHandler, handlerIndex, command,
                                                                                dispatchContext);

                    if (!shouldContinue)
                    {
                        break;
                    }
                }
                handlerIndex++;
            }

            return(result);
        }
Example #48
0
 private void Log(ActionType actionType, ICommand command)
 {
     Debug.Log($"{DateTime.Now.ToShortTimeString ()} {actionType.ToString()}({command.GetType ().Name}):\n{command.ToString ()}");
 }
 private bool TryEnqueueCommand(ICommand command)
 {
     try
     {
         _retryCommandQueue.Enqueue(command);
         return(true);
     }
     catch (Exception ex)
     {
         var errorMessage = string.Format("Exception raised when tring to enqueue the command to the retry command queue. commandType{0}, commandId:{1}", command.GetType().Name, command.Id);
         _logger.Error(errorMessage, ex);
         return(false);
     }
 }
Example #50
0
        public async Task <AsyncTaskResult <CommandResult> > ExecuteAsync(ICommand command, CommandReturnType commandReturnType)
        {
            try
            {
                Ensure.NotNull(_commandResultProcessor, "commandResultProcessor");
                var taskCompletionSource = new TaskCompletionSource <AsyncTaskResult <CommandResult> >();
                _commandResultProcessor.RegisterProcessingCommand(command, commandReturnType, taskCompletionSource);

                var result = await _sendMessageService.SendMessageAsync(Producer, "command", command.GetType().Name, BuildCommandMessage(command, true), command.AggregateRootId, command.Id, command.Items).ConfigureAwait(false);

                if (result.Status == AsyncTaskStatus.Success)
                {
                    return(await taskCompletionSource.Task.ConfigureAwait(false));
                }
                _commandResultProcessor.ProcessFailedSendingCommand(command);
                return(new AsyncTaskResult <CommandResult>(result.Status, result.ErrorMessage));
            }
            catch (Exception ex)
            {
                return(new AsyncTaskResult <CommandResult>(AsyncTaskStatus.Failed, ex.Message));
            }
        }
Example #51
0
 public async Task Execute(ICommand command)
 {
     var     handlerType = typeof(ICommandHandler <>).MakeGenericType(command.GetType());
     dynamic handler     = _serviceProvider.GetService(handlerType);
     await handler.HandleAsync((dynamic)command);
 }
Example #52
0
 private static string GetHelpResourceName(ICommand command)
 {
     return($"SortingHat.CLI.Help.{command.GetType().Name}.help");
 }
 private object CreateEvent(ICommand command)
 {
     return(Activator.CreateInstance(typeof(CommandCompletedEvent <>).MakeGenericType(command.GetType()), command.MessageId, null));
 }
Example #54
0
        public CommandResult Dispatch(ICommand command)
        {
            var           handlerType = typeof(ICommandHandler <>).MakeGenericType(new[] { command.GetType() });
            dynamic       handler     = _provider.GetService(handlerType);
            CommandResult result      = handler.Handle((dynamic)command);

            return(result);
        }
Example #55
0
 public CommandMenuItemDef(string title, Bitmap image, string description, bool isFeasible, ICommand command)
     : this((command != null) ? command.GetType().Name : null, title, image, Color.Empty, description, false, isFeasible, command)
 {
 }
Example #56
0
        public virtual void CloseFailure(ICommandContext commandContext)
        {
            if (commandContext.EventDispatcher.Enabled)
            {
                commandContext.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityExceptionEvent(ActivitiEventType.JOB_EXECUTION_FAILURE, job, commandContext.Exception));
            }

            CommandConfig            commandConfig           = commandExecutor.DefaultConfig.TransactionRequiresNew();
            IFailedJobCommandFactory failedJobCommandFactory = commandContext.FailedJobCommandFactory;
            ICommand <object>        cmd = failedJobCommandFactory.GetCommand(job.Id, commandContext.Exception);

            log.LogTrace("Using FailedJobCommandFactory '" + failedJobCommandFactory.GetType() + "' and command of type '" + cmd.GetType() + "'");
            commandExecutor.Execute(commandConfig, cmd);
        }
Example #57
0
        /// <summary>
        /// Parses command line. Instantiates command if not already instantiated.
        /// Cannot change command type without creating new instance of CommandContext
        /// </summary>
        /// <param name="cmdLine">command line to process</param>
        /// <param name="diffAtStart">true if configuration comparison starts from start of command line processing, false if after main
        /// command is executed</param>
        public IEnumerable <Option> ParseCommandLine2(string cmdLine, bool diffAtStart = false, bool logCalls = false)
        {
            var console = LogService.console;

            console.Info($"> {cmdLine}");
            string[] args = ChocolateyOptionSet.SplitArgs(cmdLine);
            ChocolateyConfiguration config = new ChocolateyConfiguration();

            parser = new ChocolateyOptionSet();

            if (diffAtStart)
            {
                original = config.deep_copy();
            }
            if (parser.Parse(args, new ChocolateyStartupCommand(), config, () =>
            {
                console.Info("- logInit called.");
            }
                             ))
            {
                console.Info("chocoArgsParse: return on startup");
                return(parser);
            }

            parser = new ChocolateyOptionSet();

            if (parser.Parse(args, new ChocolateyMainCommand(), config))
            {
                console.Info("chocoArgsParse: return on main");
                return(parser);
            }

            genericArgumentsCount = parser.Count;

            if (args.Length == 0)
            {
                "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "Please run 'choco -?' or 'choco <command> -?' for help menu.");
            }

            InstantiateCommand(config.CommandName, logCalls);
            if (command == null)
            {
                return(parser.Skip(genericArgumentsCount));
            }

            LogService.Instance.adjustLogLevels(config.Debug, config.Verbose, config.Trace);

            if (!diffAtStart)
            {
                original = config.deep_copy();
            }

            string phase = "parse";

            try
            {
                if (!parser.Parse(args.Skip(1), command, config))
                {
                    phase = "validation";
                    command.handle_validation(config);

                    console.Info("config: " + config.CompareWith(original));

                    // GenericRunner.run logic, see after line:
                    // var command = find_command(config, container, isConsole, parseArgs);
                    if (config.Noop)
                    {
                        if (config.RegularOutput)
                        {
                            this.Log().Info("_ {0}:{1} - Noop Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                        }

                        command.noop(config);
                    }
                    else
                    {
                        this.Log().Debug("_ {0}:{1} - Normal Run Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                        command.run(config);
                    }
                }
            }
            catch (ApplicationException ex)
            {
                console.Info($"{phase} failure: " + ex.Message);
            }

            return(parser.Skip(genericArgumentsCount));
        }
Example #58
0
 public string GetRequestText <TReq, TRes>(ICommand <TReq, TRes> command, TReq req) => $"Korisnik izvrsava komandu {command.GetType().Name} sa podacima: {JsonConvert.SerializeObject(req)};";
Example #59
0
 public void RegisterProcessingCommand(ICommand command, CommandReturnType commandReturnType, TaskCompletionSource <CommandResult> taskCompletionSource)
 {
     if (!_commandTaskDict.TryAdd(command.Id, new CommandTaskCompletionSource {
         CommandReturnType = commandReturnType, TaskCompletionSource = taskCompletionSource
     }))
     {
         throw new Exception(string.Format("Duplicate processing command registration, type:{0}, id:{1}", command.GetType().Name, command.Id));
     }
 }
Example #60
0
 public Task SendAsync(ICommand command)
 {
     return(_sendMessageService.SendMessageAsync(Producer, "command", command.GetType().Name, BuildCommandMessage(command, false), command.AggregateRootId, command.Id, command.Items));
 }