Esempio n. 1
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (!context.Controller.ViewData.ModelState.IsValid)
            {
                ValidationFailedResult().ExecuteResult(context);
                return;
            }

            var validator = Container.GetInstance <ICommandValidator <TCommand> >();

            if (!validator.IsValid(Command))
            {
                foreach (var failedRule in validator.FailedRules)
                {
                    context.Controller.ViewData.ModelState.AddModelError(failedRule.GetType().Name, failedRule.ToString());
                }
                ValidationFailedResult().ExecuteResult(context);

                return;
            }

            ICommandHandlerResult result = null;

            var handler = Container.GetInstance <ICommandHandler <TCommand> >();

            result = handler.Handle(Command);
            if (result is Success)
            {
                Success().ExecuteResult(context);
                return;
            }
            CommandFailedResult(result).ExecuteResult(context);
        }
Esempio n. 2
0
        /// <summary>
        /// 发布命令,命令只允许一个消费者,如果存在多个,则会有异常
        /// </summary>
        /// <typeparam name="TCommand">信息类型</typeparam>
        /// <param name="command">信息</param>
        /// <param name="communication">上下文通讯</param>
        public virtual ICommandHandlerResult Send <TCommand>(TCommand command, HandlerCommunication communication) where TCommand : ICommand
        {
            var commandType = command.GetType();

            this.OnCommandValidating(command, commandType);

            if (communication == null)
            {
                communication = new HandlerCommunication();
            }

            var element = this.FindCommandExcutingElement(command, communication);

            try
            {
                /*先保存命令*/
                this.HandlerCommandToStorage(element.CommandContext, command);
                ICommandHandlerResult handlerResult = null;
                var roots = this.HanderCommand(element, command, communication, ref handlerResult);
                if (roots == null || roots.Length == 0)
                {
                    communication.HandlerResult = handlerResult;
                    return(handlerResult);
                }

                if (handlerResult != null && handlerResult.Status != CommandHandlerStatus.Success)
                {
                    communication.HandlerResult = handlerResult;
                    return(handlerResult);
                }

                var eventArray  = new List <KeyValuePair <Type, IEvent[]> >(roots.Length);
                var eventSource = new List <IEvent[]>(roots.Length);
                foreach (var root in roots)
                {
                    var array = root.Change(root.Version + root.GetChangeCounts());
                    eventSource.Add(array);
                    var item = new KeyValuePair <Type, IEvent[]>(root.GetType(), array);
                    eventArray.Add(item);
                }

                /*先保存事件*/
                this.HandlerEventToStorage(element.CommandContext, eventArray);

                /*再发布事件*/
                this.HandlerEventToPublish(element.CommandContext, eventSource);

                communication.HandlerResult = handlerResult;
                return(handlerResult);
            }
            catch
            {
                throw;
            }
            finally
            {
                OnReturningWhenHandlerExecuted(element.CommandContext);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 获取处理结果的消息内容
        /// </summary>
        /// <returns></returns>
        protected string HandlerMerssage(ICommandHandlerResult result, string message = null)
        {
            if (result == null || result.Message.IsNullOrEmpty())
            {
                return(message);
            }

            return(result.Message);
        }
Esempio n. 4
0
        private static async Task <HandlerResponse> InvokeActionAsyncCore(CommandHandlerContext context, CancellationToken cancellationToken)
        {
            Contract.Requires(context != null);
            Contract.Requires(context.Descriptor != null);

            CommandHandlerDescriptor handlerDescriptor = context.Descriptor;

            try
            {
                object result = await handlerDescriptor.ExecuteAsync(context, cancellationToken);

                // This is cached in a local for performance reasons. ReturnType is a virtual property on CommandHandlerDescriptor,
                // or else we'd want to cache this as part of that class.
                bool isDeclaredTypeHandlerResult = typeof(ICommandHandlerResult).IsAssignableFrom(handlerDescriptor.ReturnType);
                if (result == null && isDeclaredTypeHandlerResult)
                {
                    // If the return type of the action descriptor is IHandlerResult, it's not valid to return null
                    throw Error.InvalidOperation(Resources.DefaultHandlerInvoker_NullHandlerResult);
                }

                if (isDeclaredTypeHandlerResult || handlerDescriptor.ReturnType == typeof(object))
                {
                    ICommandHandlerResult actionResult = result as ICommandHandlerResult;

                    if (actionResult == null && isDeclaredTypeHandlerResult)
                    {
                        // If the return type of the action descriptor is IHandlerResult, it's not valid to return an
                        // object that doesn't implement IHandlerResult
                        throw Error.InvalidOperation(Resources.DefaultHandlerInvoker_InvalidHandlerResult, result.GetType());
                    }

                    if (actionResult != null)
                    {
                        HandlerResponse response = await actionResult.ExecuteAsync(cancellationToken);

                        if (response == null)
                        {
                            throw Error.InvalidOperation(Resources.DefaultHandlerInvoker_NullHandlerResponse);
                        }

                        HandlerResponse.EnsureResponseHasRequest(response, context.Request);
                        return(response);
                    }
                }

                // This is a non-IHandlerResult, so run the converter
                return(handlerDescriptor.ResultConverter.Convert(context, result));
            }
            catch (HandlerResponseException handlerResponseException)
            {
                HandlerResponse response = handlerResponseException.Response;
                HandlerResponse.EnsureResponseHasRequest(response, context.Request);

                return(response);
            }
        }
Esempio n. 5
0
        public ExceptionFilterResult(CommandHandlerContext context, IExceptionFilter[] filters, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, ICommandHandlerResult innerResult)
        {
            Contract.Requires(context != null);
            Contract.Requires(filters != null);
            Contract.Requires(exceptionLogger != null);
            Contract.Requires(exceptionHandler != null);
            Contract.Requires(innerResult != null);

            this.context          = context;
            this.filters          = filters;
            this.exceptionLogger  = exceptionLogger;
            this.exceptionHandler = exceptionHandler;
            this.innerResult      = innerResult;
        }
Esempio n. 6
0
        public ExceptionFilterResult(CommandHandlerContext context, IExceptionFilter[] filters, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, ICommandHandlerResult innerResult)
        {
            Contract.Requires(context != null);
            Contract.Requires(filters != null);
            Contract.Requires(exceptionLogger != null);
            Contract.Requires(exceptionHandler != null);
            Contract.Requires(innerResult != null);

            this.context = context;
            this.filters = filters;
            this.exceptionLogger = exceptionLogger;
            this.exceptionHandler = exceptionHandler;
            this.innerResult = innerResult;
        }
Esempio n. 7
0
        private static async Task <HandlerResponse> HandleAsyncCore(IExceptionHandler handler, ExceptionHandlerContext context, CancellationToken cancellationToken)
        {
            Contract.Assert(handler != null);
            Contract.Assert(context != null);

            await handler.HandleAsync(context, cancellationToken);

            ICommandHandlerResult result = context.Result;

            if (result == null)
            {
                return(null);
            }

            HandlerResponse response = await result.ExecuteAsync(cancellationToken);

            if (response == null)
            {
                throw Error.ArgumentNull(Resources.TypeMethodMustNotReturnNull, typeof(ICommandHandlerResult).Name, "ExecuteAsync");
            }

            return(response);
        }
Esempio n. 8
0
        /// <summary>
        /// 处理结果是否为ok,
        /// 返回true的条件是看<see cref="CommandHandlerStatus.Success"/>或<see cref="CommandHandlerStatus.Idempotent"/>或<see cref="CommandHandlerStatus.NothingChanged"/>
        /// 返回false的条件是看<see cref="CommandHandlerStatus.Fail"/>或<see cref="CommandHandlerStatus.NotExists"/>或<see cref="CommandHandlerStatus.PoorInventory"/>或handlerResult==null
        /// </summary>
        /// <param name="handlerResult">命令处理结果</param>
        /// <returns></returns>
        public static bool Ok(this ICommandHandlerResult handlerResult)
        {
            if (handlerResult == null)
            {
                throw new ArgumentNullException("handlerResult");
            }

            switch (handlerResult.Status)
            {
            case CommandHandlerStatus.Success:
            case CommandHandlerStatus.Idempotent:
            case CommandHandlerStatus.NothingChanged:
                return(true);

            case CommandHandlerStatus.Fail:
            case CommandHandlerStatus.NotExists:
            case CommandHandlerStatus.PoorInventory:
                return(false);

            default:
                return(false);
            }
        }
Esempio n. 9
0
        public ActionResult EditEmployee(EmployeeModel model)
        {
            var employee = this.permissionQuery.GetEmployeeUsingAggId(model.AggregateId);

            if (employee == null)
            {
                this.ModelState.AddModelError("UserName", "不存在该员工");
                return(this.View(model));
            }

            if (this.Me.GroupSort != GroupSort.Super && model.DepartmentId != this.Me.DepartmentId)
            {
                this.ModelState.AddModelError("DepartmentId", "你不能修改别人部门的员工信息");
                return(this.View(model));
            }

            ICommandHandlerResult handler = null;

            if (employee.NickName.IsNotEquals(model.NickName))
            {
                handler = this.commandBus.Send(new ChangeEmployeeNickNameCommand(model.AggregateId)
                {
                    NickName = model.NickName,
                });

                if (!handler.Ok())
                {
                    this.ModelState.AddModelError("NickName", this.HandlerMerssage(handler, "更新昵称失败"));
                    return(this.View(model));
                }
            }

            if (employee.GroupSort != model.GroupSort)
            {
                if (this.Me.AggregateId == model.AggregateId)
                {
                    this.ModelState.AddModelError("GroupSort", "你不可以修改自己的身份");
                    return(this.View(model));
                }

                var check = this.CheckCurrentOperator(model.GroupSort);
                if (check.IsNotNullOrEmpty())
                {
                    this.ModelState.AddModelError("GroupSort", check);
                    return(this.View(model));
                }

                handler = this.commandBus.Send(new ChangeEmployeeOwnerCommand(model.AggregateId)
                {
                    DepartmentId = employee.DepartmentId,
                    GroupSort    = model.GroupSort
                });

                if (!handler.Ok())
                {
                    this.ModelState.AddModelError("GroupSort", this.HandlerMerssage(handler, "更新员工身份失败"));
                    return(this.View(model));
                }
            }

            return(this.View(model));
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryHandlerResult"/> class.
 /// </summary>
 /// <param name="retryPolicy">The <see cref="RetryPolicy"/>.</param>
 /// <param name="innerResult">The inner result.</param>
 public RetryHandlerResult(RetryPolicy retryPolicy, ICommandHandlerResult innerResult)
 {
     this.retryPolicy = retryPolicy;
     this.innerResult = innerResult;
 }
Esempio n. 11
0
        /// <summary>
        /// 发布命令,命令只允许一个消费者,如果存在多个,则会有异常
        /// </summary>
        /// <typeparam name="TCommand">信息类型</typeparam>
        /// <param name="element">命令元素</param>
        /// <param name="command">信息</param>
        /// <param name="communication">上下文通讯</param>
        /// <param name="handlerResult">处理结果</param>
        protected IAggregateRoot[] HanderCommand <TCommand>(CommandExcutingElement element, TCommand command, HandlerCommunication communication, ref ICommandHandlerResult handlerResult) where TCommand : ICommand
        {
            if (element.CommandHandler == null)
            {
                return new IAggregateRoot[] { }
            }
            ;

            if (element.AuthorizeFilters != null)
            {
                foreach (var filter in element.AuthorizeFilters)
                {
                    if (!filter.Validate(element.CommandContext, command))
                    {
                        return new IAggregateRoot[] { }
                    }
                    ;
                }
            }

            if (element.LoggerBuilder == null)
            {
                handlerResult = this.MarkCommandHandlerInvoke(command, element, communication);

                foreach (var t in element.CommandContext.Items)
                {
                    communication[t.Key] = t.Value;
                }
            }
            else
            {
                element.CommandContext.Items["LoggerBuilder"] = element.LoggerBuilder;
                try
                {
                    handlerResult = this.MarkCommandHandlerInvoke(command, element, communication);
                    foreach (var t in element.CommandContext.Items)
                    {
                        communication[t.Key] = t.Value;
                    }
                }
                catch (ParameterException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new ParameterException(ex.ParameterName, "处理出错,请稍后重试", ex);
                }
                catch (InvalidException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new InvalidException("处理出错,请稍后重试", ex);
                }
                catch (DomainException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new DomainException("处理出错,请稍后重试", ex);
                }
                catch (StreamStorageException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new StreamStorageException(ex.Message, ex);
                }
                catch (RepositoryExcutingException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new RepositoryExcutingException(ex.Message, ex);
                }
                catch (RepeatExcutingException ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new RepeatExcutingException(ex.Message, ex);
                }
                catch (ResourcePoorException ex)
                {
                    throw new ResourcePoorException(ex.Message, ex);
                }
                catch (Exception ex)
                {
                    this.OnCommandHandlerError(element, command, ex);
                    throw new Exception(ex.Message, ex);
                }
            }

            /*处理聚合根事件*/
            var roots = element.CommandContext.GetChangeAggregateRoot();

            if (roots == null || roots.Length <= 0)
            {
                return new IAggregateRoot[] { }
            }
            ;

            var list = new List <IAggregateRoot>(roots.Length);

            foreach (var root in roots)
            {
                if (root.CanCommit())
                {
                    list.Add(root);
                }
            }

            return(list.ToArray());
        }
Esempio n. 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryHandlerResult"/> class.
 /// </summary>
 /// <param name="retryPolicy">The <see cref="RetryPolicy"/>.</param>
 /// <param name="innerResult">The inner result.</param>
 public RetryHandlerResult(RetryPolicy retryPolicy, ICommandHandlerResult innerResult)
 {
     this.retryPolicy = retryPolicy;
     this.innerResult = innerResult;
 }