예제 #1
0
        public async Task RouteAsync(RouteContext context)
        {
            // Build a request model from the request
            IInputFormatter            inputFormatter = new JsonInputFormatter();
            IEnumerable <IValueParser> valueParsers   = new List <IValueParser> {
                new RouteValueParser(context.RouteData)
            };
            RequestModelActivator modelActivator = new RequestModelActivator(
                context.HttpContext,
                inputFormatter,
                valueParsers
                );
            TRequest requestModel = await modelActivator.CreateRequestModelAsync <TRequest>();

            // Run the request through our command pipeline
            IHandlerResult pipelineResult = _pipeline.Dispatch(context.HttpContext, requestModel);

            // If the request was handled by our pipeline then write the response out
            if (pipelineResult.IsHandled)
            {
                // Serialize the response model
                IOutputFormatter outputFormatter = new JsonOutputFormatter();
                ResponseWriter   responseWriter  = new ResponseWriter(context.HttpContext, outputFormatter);
                await responseWriter.SerializeResponseAsync(pipelineResult);

                // Let OWIN know our middleware handled the request
                context.IsHandled = true;
            }
        }
예제 #2
0
        private IActionResult Remap(IHandlerResult result)
        {
            switch (result)
            {
            case IDataHandlerResult <object> dhr:
                return(this.Ok(dhr.Data));

            case IDataHandlerResult <int> dhr:
                return(this.Ok(dhr.Data));

            case IDataHandlerResult <bool> dhr:
                return(this.Ok(dhr.Data));

            case IPagedDataHandlerResult <object> pdhr:
                return(new OkPagedResult <IReadOnlyCollection <object> >(pdhr.Items, pdhr.Count));

            case ICreatedHandlerResult <int> chr:
                return(this.StatusCode(StatusCodes.Status201Created, chr.Data));

            case ICreatedHandlerResult <object> chr:
                return(this.StatusCode(StatusCodes.Status201Created, chr.Data));

            case InternalServerErrorHandlerResult isehr:
                return(ErrorResult(isehr.ErrorMessage, () => this.StatusCode(500), sr => this.StatusCode(412, sr)));

            default:
                throw new KeyNotFoundException($"Unknown handler result '{result.GetType()}' encountered.");
            }
        }
        private async Task SendResult <T>(long chatId, IHandlerResult <T> result)
        {
            switch (result)
            {
            case ValidationFailedHandlerResult <T> validationFailedHandlerResult:
                await _telegram.SendTextMessageAsync(chatId, validationFailedHandlerResult.Message);

                break;
            }
        }
예제 #4
0
        public async Task <IHandlerResult> Handle(TRequest query, CancellationToken cancellationToken)
        {
            IHandlerResult canHandle = await this.CanHandleAsync(query, cancellationToken);

            if (canHandle == null)
            {
                return(await this.HandleAsync(query, cancellationToken));
            }

            return(canHandle);
        }
        public void Dispatch_should_only_handle_appropriate_request_methods(string requestMethod, Type expectedResultType)
        {
            // Given a POST FooRequest CommandPipeline
            CommandPipeline <FooRequest> pipeline = new CommandPipeline <FooRequest>(HttpVerb.Post, new TestFooHandler());

            // And an HttpContext for a GET operation
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Method = requestMethod;

            // When I try to dispatch a FooRequest
            FooRequest     request       = new FooRequest();
            IHandlerResult handlerResult = pipeline.Dispatch(httpContext, request);

            // Then the pipeline should not handle the request
            handlerResult.Should().BeOfType(expectedResultType);
        }
예제 #6
0
        public IHandlerResult Execute(IReadOnlyDictionary <string, string> tokens, IReadOnlyList <IHandlerResult> results, JObject json)
        {
            Stopwatch watch = Stopwatch.StartNew();

            try
            {
                string         targetName = json["name"].ToString();
                IHandlerResult result     = results.FirstOrDefault(x => x.Name == targetName);
                if (result is ExecuteHandlerResult xr)
                {
                    xr.Kill();
                }

                return(new GenericHandlerResult(watch.Elapsed, true, null));
            }
            finally
            {
                watch.Stop();
            }
        }
예제 #7
0
        public virtual async Task <IHandlerResult> Execute(IPacket <TData> packet, IPlayer player = null)
        {
            IHandlerResult handlerResult = null;
            object         result        = null;
            var            reflector     = handlers[packet.Command].Reflector;
            var            parameters    = reflector.ParameterReflectors;

            if (parameters.Length > 0)
            {
                var args = Array.ConvertAll(parameters, r => GetParameter(packet, r, player));
                result = reflector.Invoke(this, args);
            }
            else
            {
                result = reflector.Invoke(this);
            }
            switch (result)
            {
            case Task <StatusDescriptor> codeTask:
                handlerResult = new THandlerResult {
                    Status = await codeTask
                };
                break;

            case Task <IHandlerResult> resultTask:
                handlerResult = await resultTask;
                break;

            case Task emptyTask:
                await emptyTask;
                handlerResult = new THandlerResult();
                break;

            default: throw new FormatException($"Command:{packet.Command} invoke invaild return type : {result.GetType()}");
            }
            return(handlerResult);
        }
        /// <summary>
        /// Creates an appropriate HttpResponse from our command handler result
        /// </summary>
        /// <param name="handlerResult">The command handler result that we need to create ah HttpResponse from</param>
        public async Task SerializeResponseAsync(IHandlerResult handlerResult)
        {
            // Set the status code on the response
            var httpResponseResult = handlerResult as IHttpResponseResult;
            var status             = httpResponseResult?.Status ?? HttpStatusCode.OK;

            _httpContext.Response.StatusCode = (int)status;

            // If the response type is is null or Unit, then don't do anything since we have nothing to serialize
            if ((handlerResult.Response ?? Unit.Result) == Unit.Result)
            {
                return;
            }

            // Create a context so that our formatter knows where to serialize the response
            var formatterContext = new OutputFormatterWriteContext(
                _httpContext,
                _responseWriterFactory,
                handlerResult.ResponseType,
                handlerResult.Response);

            // Use our writer to write a reponse body
            await _outputFormatter.WriteAsync(formatterContext);
        }
예제 #9
0
        internal IHandlerResult Dispatch(HttpContext context, TRequest requestModel)
        {
            // Check to see if this pipeline handles the request verb
            bool pipelineHandlesVerb = string.Equals(
                context.Request.Method, $"{_verb}",
                StringComparison.OrdinalIgnoreCase
                );

            // Run the command through our command pipeline until it gets handled
            if (pipelineHandlesVerb)
            {
                foreach (var handler in _commandHandlers)
                {
                    IHandlerResult handlerResult = handler.Dispatch(requestModel);
                    if (handlerResult.IsHandled)
                    {
                        return(handlerResult);
                    }
                }
            }

            // Otherwise our pipeline can't handle the request
            return(new NotHandled());
        }
예제 #10
0
 /// <summary>
 /// Converts <see cref="IHandlerResult"/> to <see cref="IActionResult"/>.
 /// </summary>
 /// <param name="result">Service response.</param>
 /// <returns>Returns data wrapped into <see cref="IActionResult"/>.</returns>
 protected IActionResult Send(IHandlerResult result)
 {
     return(this.Remap(result));
 }
 public IHandlerResult OnHandlerExecuted(IHandlerResult handlerResult, Type messageType, object message)
 {
     return handlerResult;
 }
예제 #12
0
 public IHandlerResult OnHandlerExecuted(IHandlerResult handlerResult, Type messageType, object message)
 {
     return(handlerResult);
 }
예제 #13
0
 public IHandlerResult OnHandlerExecuted(IHandlerResult handlerResult, Type messageType, object message)
 {
     this.log.Value.InfoFormat("Processed {0} message. Result {1}", messageType, handlerResult);
     return(handlerResult);
 }
예제 #14
0
 public IHandlerResult OnHandlerExecuted(IHandlerResult handlerResult, Type messageType, object message)
 {
     this.log.Value.InfoFormat("Processed {0} message. Result {1}", messageType, handlerResult);
     return handlerResult;
 }
예제 #15
0
 public static IHandlerResult Join(this IHandlerResult a, IHandlerResult b)
 {
     return(new JoiningHandlerResult(a, b));
 }
예제 #16
0
        /// <summary>
        /// Invokes all chained filters in the order they were applied on the specified message
        /// </summary>
        /// <param name="messageType"></param>
        /// <param name="messageEnvelope"></param>
        /// <returns></returns>
        private IHandlerResult PerformFilters(Type messageType, object messageEnvelope, IHandlerResult handlerResult, Func<IInboundMessageFilter, IHandlerResult> filterFunc)
        {
            Func<Type, IHandlerResult, IHandlerResult> performFilters = (mType, result) =>
            {
                foreach (var filter in this.messageFilters[mType].ToList())
                {
                    try
                    {
                        result = filterFunc(filter);
                        if (!(result is SuccessResult))
                        {
                            return result;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.configuration.Logger.ErrorFormat("Unhandled exception in filter: {0}", ex.ToString());
                        return new RetryResult(ex.ToString());
                    }
                }

                return result;
            };

            // Global Filters
            if (this.messageFilters.ContainsKey(typeof(Object)))
            {
                handlerResult = performFilters(typeof(Object), handlerResult);
            }

            // Scoped Filters
            if (this.messageFilters.ContainsKey(messageType))
            {
                handlerResult = performFilters(messageType, handlerResult);
            }

            return handlerResult;
        }
예제 #17
0
        /// <summary>
        /// Invokes all chained filters in the order they were applied on the specified message
        /// </summary>
        /// <param name="messageType"></param>
        /// <param name="messageEnvelope"></param>
        /// <returns></returns>
        private IHandlerResult PerformFilters(Type messageType, object messageEnvelope, IHandlerResult handlerResult, Func <IInboundMessageFilter, IHandlerResult> filterFunc)
        {
            Func <Type, IHandlerResult, IHandlerResult> performFilters = (mType, result) =>
            {
                foreach (var filter in this.messageFilters[mType].ToList())
                {
                    try
                    {
                        result = filterFunc(filter);
                        if (!(result is SuccessResult))
                        {
                            return(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.configuration.Logger.ErrorFormat("Unhandled exception in filter: {0}", ex.ToString());
                        return(new RetryResult(ex.ToString()));
                    }
                }

                return(result);
            };

            // Global Filters
            if (this.messageFilters.ContainsKey(typeof(Object)))
            {
                handlerResult = performFilters(typeof(Object), handlerResult);
            }

            // Scoped Filters
            if (this.messageFilters.ContainsKey(messageType))
            {
                handlerResult = performFilters(messageType, handlerResult);
            }

            return(handlerResult);
        }
예제 #18
0
 protected async Task <IActionResult> FromResult <T>(IHandlerResult <T> result) =>
 result switch
 {