Пример #1
0
        public object CreateObjectFieldResultScope(object entity, RequestPath path)
        {
            // special case - Union
            if (TypeDef.Kind == TypeKind.Union)
            {
                if (entity is UnionBase ub)
                {
                    entity = ub.Value;
                }
                if (entity == null)
                {
                    return(null);
                }
            }
            var entType = entity.GetType();
            var mapping = TypeDef.FindMapping(entType);

            if (mapping == null)
            {
                throw new FatalServerException($"FATAL: failed to find mapping for entity type {entType} in the type {TypeDef.Name}. ");
            }
            var scope = new OutputObjectScope(path, entity, mapping);

            AllResultScopes.Add(scope);
            var newCount = Interlocked.Increment(ref _requestContext.Metrics.OutputObjectCount);

            // check total count against quota
            if (newCount > _requestContext.Quota.MaxOutputObjects)
            {
                this.ThrowObjectCountExceededQuota();
            }
            return(scope);
        }
Пример #2
0
        public void RegisterHandlers(IIMOwinOptions options, Assembly[] hostAssemblies)
        {
            // memoized
            if (Interlocked.Increment(ref _alreadyRegistered) != 0) return;

            var contractTypes = hostAssemblies
                .SelectMany(x =>
                {
                    try
                    {
                        return x.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        return ex.Types.Where(t => t != null);
                    }
                })
                .Where(x => typeof (IMOwinBehaviorContract).IsAssignableFrom(x))
                .Where(x => !x.IsAbstract);

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                if (classType.GetConstructors().All(x => x.GetParameters().Length != 0))
                {
                    throw new InvalidOperationException(string.Format("Type needs parameterless constructor, class:{0}", classType.FullName));
                }
                // ignore
                if (classType.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) return;

                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    // property
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_")))
                        continue;

                    // ignore
                    if (methodInfo.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) 
                        continue;

                    var methodName = methodInfo.Name;
                    // ignore default methods
                    if (methodName == "Equals" || methodName == "GetHashCode" || methodName == "GetType" || methodName == "ToString") 
                        continue;

                    // create handler
                    var handler = new OperationHandler(classType, methodInfo);
                    lock (_handlers)
                    {
                        var path = new RequestPath(className, methodName);
                        // 簡単化のため duplicate entry ⇒ fail
                        if (_handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        _handlers.Add(path, handler);
                    }
                }
            });
        }
Пример #3
0
        public override string Execute(InfoBase json)
        {
            bool   connect = false;
            string xml     = string.Empty;

            try
            {
                //组建参数字典
                Dictionary <string, string> Para = new Dictionary <string, string>();
                //Para.Add("key", ShareData.QAkye);
                //Para.Add("info", json.Contents);
                //Para.Add("userid", ShareData.QAuserid);

                string     path    = RequestPath.CreatePathApi("/turing/turing/turing");
                RpArticles newList = HTMLHelper.Get <RpArticles>(path, Para, ref connect, ShareData.baiduapikey);
                if (newList.code == "200" && newList != null)
                {
                    newList.xmlmsg = json;
                    xml            = new replyImageText().ReplyExecute(newList);
                }
            }
            catch (Exception ex)
            {
                TracingHelper.Error(ex, typeof(DeepQA), ex.Message);
            }
            return(xml);
        }
Пример #4
0
        public override string Execute(InfoBase json)
        {
            bool   connect = false;
            string xml     = string.Empty;

            try
            {
                //组建参数字典
                Dictionary <string, string> Para = new Dictionary <string, string>();
                Para.Add("num", "4");
                Para.Add("rand", "1");

                string     path    = RequestPath.CreatePathApi("/txapi/weixin/wxhot");
                RpArticles newList = HTMLHelper.Get <RpArticles>(path, Para, ref connect, ShareData.baiduapikey);
                if (newList.code == "200" && newList != null)
                {
                    newList.xmlmsg = json;
                    xml            = new replyImageText().ReplyExecute(newList);
                }
            }
            catch (Exception ex)
            {
                TracingHelper.Error(ex, typeof(TouTiao), ex.Message);
            }
            return(xml);
        }
Пример #5
0
        protected string[] GetControllerAndAction()
        {
            var result      = new string[2];
            var requestPath = RequestPath.Split('/');

            if (requestPath.Length > 1)
            {
                result[0] = requestPath[0];
                result[1] = requestPath[1];
            }
            else
            {
                var route = GetRoute(requestPath[0]);
                if (route == null)
                {
                    result[0] = ConfigurationManager.AppSettings["Host.App.Mvc.DefaultController"].ToString();
                    result[1] = requestPath[0];
                }
                else
                {
                    result[0] = requestPath[0];
                    result[1] = ConfigurationManager.AppSettings["Host.App.Mvc.DefaultAction"].ToString();
                }
            }
            return(result);
        }
Пример #6
0
        public HttpRequestWrapper(HttpListenerRequest request, string basepath)
        {
            this.Request  = request;
            this.basePath = basepath.ToRoute();
            this.Parts    = RequestPath.Split('/');

            RequestMethod = (HTTP)Enum.Parse(typeof(HTTP), Request.HttpMethod.ToUpper());
        }
Пример #7
0
        public object CreateObjectFieldResultScopes(object rawResult, int rank, RequestPath path)
        {
            if (rawResult == null)
            {
                return(null);
            }

            // check field depth against quota
            if (path.FieldDepth > _requestContext.Quota.MaxDepth)
            {
                this.ThrowFieldDepthExceededQuota();
            }

            switch (rank)
            {
            case 0:
                var typeDef = Field.FieldDef.TypeRef.TypeDef;
                // special cases - Union, Interface; extract actual value from box
                switch (typeDef.Kind)
                {
                case TypeKind.Union:
                    if (rawResult is UnionBase ub)
                    {
                        rawResult = ub.Value;
                    }
                    if (rawResult == null)
                    {
                        return(null);
                    }
                    break;

                case TypeKind.Interface:
                    if (rawResult == null)
                    {
                        return(null);
                    }
                    break;
                }
                var scope = new OutputObjectScope(this, path, rawResult);
                AllResultScopes.Add(scope);
                var newCount = Interlocked.Increment(ref _requestContext.Metrics.OutputObjectCount);
                // check total count against quota
                if (newCount > _requestContext.Quota.MaxOutputObjects)
                {
                    this.ThrowObjectCountExceededQuota();
                }
                return(scope);

            default: // rank > 0, array
                var list   = rawResult as IList;
                var scopes = new object[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    scopes[i] = CreateObjectFieldResultScopes(list[i], rank - 1, path.Append(i));
                }
                return(scopes);
            }
        }
Пример #8
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (ETag != null ? ETag.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RequestPath != null ? RequestPath.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RequestQueryString != null ? RequestQueryString.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RequestMethod != null ? RequestMethod.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #9
0
        private IList <object> CreateObjectScopeList(object rawResult, int rank, RequestPath path)
        {
            var list   = (IEnumerable)rawResult;
            var scopes = new List <object>();
            var index  = 0;

            foreach (var item in list)
            {
                var itemScope = CreateObjectFieldResultScopes(item, rank - 1, path.Append(index++));
                scopes.Add(itemScope);
            }
            return(scopes);
        }
Пример #10
0
        public Task <K> APIRequestAsync <K>(Tuple <string, string>[] getParameters, Tuple <string, string>[] postParameters)
            where K : Response
        {
            RequestPath path = RequestPath.GetRequestPath <K>();
            //TODO: Custom paths? Appropriate subdomain paths? Not sure.
            //Maybe store custom path in the requestpath.path itself?

            Uri            requestUri = GetSlackUri(Path.Combine(APIBaseLocation, path.Path), getParameters);
            HttpWebRequest request    = CreateWebRequest(requestUri);

            //This will handle all of the processing.
            var state = new RequestStateForTask <K>(request, postParameters);

            return(state.Execute());
        }
Пример #11
0
        public async Task <T> SendRequest <T>(string slackKey, ApiRequest <T> apiRequest) where T : ApiResponceBase
        {
            RequestPath path    = RequestPath.GetRequestPath <T>();
            var         request = new RestRequest(SendMessagePath + path.Path);

            request.AddParameter("token", slackKey);
            foreach (var parameter in apiRequest.Parameters)
            {
                request.AddParameter(parameter.Key, parameter.Value);
            }

            var response = await _requestExecutor.Execute <T>(request);

            return(response);
        }
Пример #12
0
        public string Execute(string json)
        {
            bool connect = false;
            //组建参数字典
            Dictionary <string, string> Para = new Dictionary <string, string>();

            Para.Add("corpid", ShareData.qyCorpID);
            Para.Add("corpsecret", ShareData.qySecret);

            string            path      = RequestPath.CreatePathqy(RequestType.qyaccess_token);
            RPGetaccess_token tokenInfo = HTMLHelper.Get <RPGetaccess_token>(path, Para, ref connect);

            if (tokenInfo != null)
            {
                ShareData.qyaccess_token = tokenInfo.access_token;
            }
            return("");
        }
Пример #13
0
        public IActionResult PerviewEmail1()
        {
            var requestPath = new RequestPath();

            requestPath.PathBase = Request.PathBase.ToString();
            requestPath.Host     = Request.Host.ToString();
            requestPath.IsHttps  = Request.IsHttps;
            requestPath.Scheme   = Request.Scheme;
            requestPath.Method   = Request.Method;

            var emailData = new Email("Testing1");

            emailData.RequestPath      = requestPath;
            emailData.ViewData["to"]   = "*****@*****.**";
            emailData.ViewData["Name"] = "Sam";

            return(new EmailViewResult(emailData));
        }
Пример #14
0
        public string Execute(string json)
        {
            bool connect = false;
            //组建参数字典
            Dictionary <string, string> Para = new Dictionary <string, string>();

            Para.Add("grant_type", "client_credential");
            Para.Add("appid", ShareData.wxAppid);
            Para.Add("secret", ShareData.wxSecret);

            string            path      = RequestPath.CreatePath(RequestType.access_token);
            RPGetaccess_token tokenInfo = HTMLHelper.Get <RPGetaccess_token>(path, Para, ref connect);

            if (tokenInfo != null)
            {
                ShareData.wxaccess_token = tokenInfo.access_token;
            }
            return("");
        }
Пример #15
0
 public object CreateObjectFieldResultScopes(object rawResult, int rank, RequestPath path)
 {
     if (rawResult == null)
     {
         return(null);
     }
     // check field depth against quota
     if (path.FieldDepth > _requestContext.Quota.MaxDepth)
     {
         this.ThrowFieldDepthExceededQuota();
     }
     if (rank > 0)
     {
         return(CreateObjectScopeList(rawResult, rank, path));
     }
     else
     {
         return(CreateObjectFieldResultScope(rawResult, path));
     }
 }
Пример #16
0
        public async Task <IActionResult> SendEmail2()
        {
            var requestPath = new RequestPath();

            requestPath.PathBase = Request.PathBase.ToString();
            requestPath.Host     = Request.Host.ToString();
            requestPath.IsHttps  = Request.IsHttps;
            requestPath.Scheme   = Request.Scheme;
            requestPath.Method   = Request.Method;

            var emailData = new Email("~/Views/AnotherFolder/Testing2.cshtml");

            emailData.RequestPath      = requestPath;
            emailData.ViewData["to"]   = "*****@*****.**";
            emailData.ViewData["Name"] = "Sam";

            await _emailService.SendAsync(emailData);

            return(View());
        }
Пример #17
0
        void GetPath(bool forcePath = false)
        {
            if (!forcePath && !pathTimer.IsReady(false))
            {
                gotValidPath = false;
                PlayAnim(AnimationType.Idle);
                return;
            }

            currentPathNodeCount = path.Count - index;
            shortPathNodeCount   = Mathf.Min(shortPathNodeCount, currentPathNodeCount);

            RequestPath.GetPath_Avoidance(rb.position, Target, path, resolution, col);

            currentPathNodeCount = path.Count;
            shortPathNodeCount   = Mathf.Min(shortPathNodeCount, currentPathNodeCount);

            index        = 0;
            gotValidPath = path.Count > 0;
            pathTimer.ForceUpdate();
        }
Пример #18
0
        public virtual int _GetUniqueIdentifier()
        {
            var hashCode = 399326290;

            hashCode = hashCode * -1521134295 + (RequestPath?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Message?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (RequestId?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (RequestMethod?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (ElapsedMsecs?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (IP?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Service?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Operation?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (StatusCode?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Timestamp?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Username?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (RequestUri?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (ClientId?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (ClientName?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (ProductName?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (RequestLogKey?.GetHashCode() ?? 0);
            return(hashCode);
        }
Пример #19
0
        public string Execute(string type)
        {
            bool   connect = false;
            string path    = string.Empty;

            try
            {
                //组建参数字典
                Dictionary <string, string> Para = new Dictionary <string, string>();
                Para.Add("access_token", ShareData.qyaccess_token);
                path = RequestPath.CreatePathqy(RequestType.Ip_list);
                RPGetIp_list IpListInfo = HTMLHelper.Get <RPGetIp_list>(path, Para, ref connect);
                if (IpListInfo == null || IpListInfo.errcode != null)
                {
                    //重新请求access_token
                    new qyGetAccess_token().Execute("");
                }
            }
            catch (Exception ex)
            {
                TracingHelper.Error(ex, typeof(GetIp_list), path + ex.ToString());
            }
            return("");
        }
Пример #20
0
        public override string Execute(InfoBase json)
        {
            bool connect = false;

            try
            {
                //组建参数字典
                Dictionary <string, string> Para = new Dictionary <string, string>();
                Para.Add("access_token", ShareData.wxaccess_token);

                string       path       = RequestPath.CreatePath(RequestType.Ip_list);
                RPGetIp_list IpListInfo = HTMLHelper.Get <RPGetIp_list>(path, Para, ref connect);
                if (IpListInfo == null && IpListInfo.errcode != null)
                {
                    //重新请求access_token
                    //new GetAccess_token().Execute("");
                }
            }
            catch (Exception ex)
            {
                TracingHelper.Error(ex, typeof(Getjoke), ex.Message);
            }
            return("");
        }
Пример #21
0
        private string GetOperationName()
        {
            var parts = RequestPath.Split('/');

            return(parts.Last());
        }
Пример #22
0
        // TODO:very long method, refactoring...
        public static async Task ProcessRequest(IDictionary<string, object> environment)
        {
            try
            {
                var path = environment["owin.RequestPath"] as string;

                // verb check
                var method = environment["owin.RequestMethod"];
                var verb = AcceptVerbs.Get;
                if (StringComparer.OrdinalIgnoreCase.Equals(method, "GET"))
                {
                    verb = AcceptVerbs.Get;
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(method, "POST"))
                {
                    verb = AcceptVerbs.Post;
                }
                else
                {
                    EmitMethodNotAllowed(environment);
                    return;
                }

                var keyBase = path.Trim('/').Split('/');
                if (keyBase.Length != 2)
                {
                    EmitNotFound(environment);
                    return;
                }

                // extract "extension" for media type
                var extStart = keyBase[1].LastIndexOf(".");
                var ext = "";
                if (extStart != -1)
                {
                    ext = keyBase[1].Substring(extStart + 1);
                    keyBase[1] = keyBase[1].Substring(0, keyBase[1].Length - ext.Length - 1);
                }

                // {ClassName, MethodName}
                var key = new RequestPath(keyBase[0], keyBase[1]);

                OperationHandler handler;
                if (handlers.TryGetValue(key, out handler))
                {
                    // verb check
                    if (!options.DefaultAcceptVerb.HasFlag(verb))
                    {
                        EmitMethodNotAllowed(environment);
                        return;
                    }

                    // Extract parameter
                    ILookup<string, string> requestParameter;
                    var queryString = environment["owin.RequestQueryString"] as string;
                    using (var sr = new StreamReader((environment["owin.RequestBody"] as Stream)))
                    {
                        var str = sr.ReadToEnd();
                        requestParameter = str.Split('&')
                            .Concat(queryString.Split('&'))
                            .Select(xs => xs.Split('='))
                            .Where(xs => xs.Length == 2)
                            .ToLookup(xs => Uri.UnescapeDataString(xs[0]), xs => Uri.UnescapeDataString(xs[1]), StringComparer.OrdinalIgnoreCase);
                    }

                    // Parameter binding
                    var methodParameters = new object[handler.Arguments.Length];
                    for (int i = 0; i < handler.Arguments.Length; i++)
                    {
                        var item = handler.Arguments[i];

                        var values = requestParameter[item.Name];
                        var count = values.Count();
                        if (count == 0 && !item.ParameterType.IsArray)
                        {
                            if (item.IsOptional)
                            {
                                methodParameters[i] = item.DefaultValue;
                                continue;
                            }
                            else if (item.ParameterType.IsClass || item.ParameterType.IsNullable())
                            {
                                methodParameters[i] = null;
                                continue;
                            }
                            else
                            {
                                EmitBadRequest(environment);
                                await EmitStringMessage(environment, "Lack of Parameter:" + item.Name).ConfigureAwait(false);
                                return;
                            }
                        }
                        else if (!item.ParameterType.IsArray)
                        {
                            var conv = AllowRequestType.GetConverter(item.ParameterType);
                            if (conv == null) throw new InvalidOperationException("critical:register code is broken");

                            object pValue;
                            if (conv(values.First(), out pValue))
                            {
                                methodParameters[i] = pValue;
                                continue;
                            }
                            else if (item.IsOptional)
                            {
                                methodParameters[i] = item.DefaultValue;
                                continue;
                            }
                            else if (item.ParameterType.IsClass || item.ParameterType.IsNullable())
                            {
                                methodParameters[i] = null;
                                continue;
                            }
                            else
                            {
                                EmitBadRequest(environment);
                                await EmitStringMessage(environment, "Mismatch Parameter Type:" + item.Name).ConfigureAwait(false);
                                return;
                            }
                        }


                        var arrayConv = AllowRequestType.GetArrayConverter(item.ParameterType);
                        if (arrayConv == null) throw new InvalidOperationException("critical:register code is broken");

                        methodParameters[i] = arrayConv(values);
                        continue;
                    }

                    // Operation execute
                    bool isVoid = true;
                    object result = null;
                    switch (handler.HandlerBodyType)
                    {
                        case HandlerBodyType.Action:
                            handler.MethodActionBody(environment, methodParameters);
                            break;
                        case HandlerBodyType.Func:
                            isVoid = false;
                            result = handler.MethodFuncBody(environment, methodParameters);
                            break;
                        case HandlerBodyType.AsyncAction:
                            var actionTask = handler.MethodAsyncActionBody(environment, methodParameters);
                            await actionTask.ConfigureAwait(false);
                            break;
                        case HandlerBodyType.AsyncFunc:
                            isVoid = false;
                            var funcTask = handler.MethodAsyncFuncBody(environment, methodParameters);
                            await funcTask.ConfigureAwait(false);
                            var extractor = taskResultExtractors[funcTask.GetType()];
                            result = extractor(funcTask);
                            break;
                        default:
                            throw new InvalidOperationException("critical:register code is broken");
                    }

                    if (!isVoid)
                    {
                        var requestHeader = environment["owin.RequestHeaders"] as IDictionary<string, string[]>;
                        string[] accepts;

                        // select formatter
                        var formatter = options.DefaultFormatter;
                        if (ext != "")
                        {
                            formatter = new[] { options.DefaultFormatter }.Concat(options.SpecifiedFormatters)
                                .FirstOrDefault(x => x.Ext == ext);

                            if (formatter == null)
                            {
                                EmitNotAcceptable(environment);
                                return;
                            }
                        }
                        else if (requestHeader.TryGetValue("Accept", out accepts))
                        {
                            // TODO:parse accept header q, */*, etc...
                            var contentType = accepts[0];
                            formatter = new[] { options.DefaultFormatter }.Concat(options.SpecifiedFormatters)
                                .FirstOrDefault(x => contentType.Contains(x.MediaType));

                            if (formatter == null)
                            {
                                formatter = options.DefaultFormatter; // through...
                            }
                        }

                        // append header
                        var responseHeader = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
                        responseHeader["Content-Type"] = new[] { formatter.MediaType };

                        var responseStream = environment["owin.ResponseBody"] as Stream;
                        formatter.Serialize(responseStream, result);
                    }

                    EmitOK(environment);
                    return;
                }
                else
                {
                    EmitNotFound(environment);
                    return;
                }
            }
            catch
            {
                EmitInternalServerError(environment);
                throw;
            }
        }
Пример #23
0
        public static void RegisterHandler(Assembly[] hostAssemblies)
        {
            if (Interlocked.Increment(ref alreadyRegistered) != 0) return;

            var contractTypes = hostAssemblies
                .SelectMany(x => x.GetTypes())
                .Where(x => typeof(LightNodeContract).IsAssignableFrom(x));

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) continue; // as property

                    var methodName = methodInfo.Name;

                    // ignore default methods
                    if (methodName == "Equals"
                     || methodName == "GetHashCode"
                     || methodName == "GetType"
                     || methodName == "ToString")
                    {
                        continue;
                    }

                    var handler = new OperationHandler();

                    handler.MethodName = methodName;
                    handler.Arguments = methodInfo.GetParameters();
                    handler.ReturnType = methodInfo.ReturnType;

                    foreach (var argument in handler.Arguments)
                    {
                        if (!AllowRequestType.IsAllowType(argument.ParameterType))
                        {
                            throw new InvalidOperationException(string.Format("parameter is not allowed, class:{0} method:{1} paramName:{2} paramType:{3}",
                                className, methodName, argument.Name, argument.ParameterType.FullName));
                        }
                    }

                    // prepare lambda parameters
                    var envArg = Expression.Parameter(typeof(IDictionary<string, object>), "environment");
                    var envBind = Expression.Bind(typeof(LightNodeContract).GetProperty("Environment"), envArg);
                    var args = Expression.Parameter(typeof(object[]), "args");
                    var parameters = methodInfo.GetParameters()
                        .Select((x, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), x.ParameterType))
                        .ToArray();

                    // Task or Task<T>
                    if (typeof(Task).IsAssignableFrom(handler.ReturnType))
                    {
                        // (object[] args) => new X().M((T1)args[0], (T2)args[1])...
                        var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], Task>>(
                            Expression.Call(
                                Expression.MemberInit(Expression.New(classType), envBind),
                                methodInfo,
                                parameters),
                            envArg, args);

                        if (handler.ReturnType.IsGenericType && handler.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
                        {
                            handler.HandlerBodyType = HandlerBodyType.AsyncFunc;
                            handler.MethodAsyncFuncBody = lambda.Compile();

                            lock (taskResultExtractors)
                            {
                                if (!taskResultExtractors.ContainsKey(handler.ReturnType))
                                {
                                    // (object task) => (object)((Task<>).Result)
                                    var taskParameter = Expression.Parameter(typeof(object), "task");
                                    var resultLambda = Expression.Lambda<Func<object, object>>(
                                        Expression.Convert(
                                            Expression.Property(
                                                Expression.Convert(taskParameter, handler.ReturnType),
                                                "Result"),
                                            typeof(object)),
                                        taskParameter);

                                    var compiledResultLambda = resultLambda.Compile();

                                    taskResultExtractors[handler.ReturnType] = compiledResultLambda;
                                }
                            }
                        }
                        else
                        {
                            handler.HandlerBodyType = HandlerBodyType.AsyncAction;
                            handler.MethodAsyncActionBody = lambda.Compile();
                        }
                    }
                    else if (handler.ReturnType == typeof(void)) // of course void
                    {
                        // (object[] args) => { new X().M((T1)args[0], (T2)args[1])... }
                        var lambda = Expression.Lambda<Action<IDictionary<string, object>, object[]>>(
                            Expression.Call(
                                Expression.MemberInit(Expression.New(classType), envBind),
                                methodInfo,
                                parameters),
                            envArg, args);

                        handler.HandlerBodyType = HandlerBodyType.Action;
                        handler.MethodActionBody = lambda.Compile();
                    }
                    else // return T
                    {
                        // (object[] args) => (object)new X().M((T1)args[0], (T2)args[1])...
                        var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], object>>(
                            Expression.Convert(
                                Expression.Call(
                                    Expression.MemberInit(Expression.New(classType), envBind),
                                    methodInfo,
                                    parameters)
                            , typeof(object)),
                            envArg, args);

                        handler.HandlerBodyType = HandlerBodyType.Func;
                        handler.MethodFuncBody = lambda.Compile();
                    }

                    lock (handlers)
                    {
                        // fail duplicate entry
                        var path = new RequestPath(className, methodName);
                        if (handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        handlers.Add(path, handler);
                    }
                }
            });
        }
Пример #24
0
        OperationHandler SelectHandler(IDictionary<string, object> environment, out AcceptVerbs verb, out string ext)
        {
            // out default
            verb = AcceptVerbs.Get;
            ext = "";

            // verb check
            var method = environment["owin.RequestMethod"];
            if (StringComparer.OrdinalIgnoreCase.Equals(method, "GET"))
            {
                verb = AcceptVerbs.Get;
            }
            else if (StringComparer.OrdinalIgnoreCase.Equals(method, "POST"))
            {
                verb = AcceptVerbs.Post;
            }
            else
            {
                environment.EmitMethodNotAllowed();
                return null;
            }

            // extract path
            var path = environment["owin.RequestPath"] as string;
            var keyBase = path.Trim('/').Split('/');
            if (keyBase.Length != 2)
            {
                environment.EmitNotFound();
                return null;
            }

            // extract "extension" for media type
            var extStart = keyBase[1].LastIndexOf(".");
            if (extStart != -1)
            {
                ext = keyBase[1].Substring(extStart + 1);
                keyBase[1] = keyBase[1].Substring(0, keyBase[1].Length - ext.Length - 1);
            }

            // {ClassName, MethodName}
            var key = new RequestPath(keyBase[0], keyBase[1]);

            OperationHandler handler;
            if (handlers.TryGetValue(key, out handler))
            {
                return handler;
            }
            else
            {
                environment.EmitNotFound();
                return null;
            }
        }
Пример #25
0
        public HttpResponseMessage GetResponse()
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(FullURL);
#endif

            #region Local Variables
            WebRequestPostContentType postContentType = PostContentType;
            String     strPostContent = PostContent;
            HttpClient httpClient     = new HttpClient();
            httpClient.BaseAddress = new Uri(BaseURL);
            HttpResponseMessage httpResponse = null;
            #endregion Local Variables

            #region Resolve Headers
            foreach (KeyValuePair <String, String> kvp in Headers)
            {
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation(kvp.Key, kvp.Value);
            }
            #endregion Resolve Headers

            #region Resolve URL Path
            String strParam = URLParamsString;
            RequestPath = RequestPath.Replace('\\', '/');
            String urlPath = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") || strParam == "" ? "" : "/", strParam != "" ? "?" : "", strParam);
            #endregion Resolve URL Path

            switch (RequestType)
            {
            case WebRequestType.GET_OFFSET:
            case WebRequestType.GET_PAGE:
            case WebRequestType.POST_OFFSET:
            case WebRequestType.POST_PAGE:
                Int32   limit = 100, offset = 0, page = 0, maxPages = 20, maxChildren = 0;
                JObject jObjectMerged = new JObject(), jObjectTemp;
                Dictionary <string, string> dictPostContent = null;    //Used for POST_OFFSET and POST_PAGE

                #region Initialization by Request Type
                switch (RequestType)
                {
                case WebRequestType.GET_OFFSET:
                    if (UrlParams.ContainsKey(LimitField))
                    {
                        Int32.TryParse(UrlParams[LimitField], out limit);
                    }
                    else
                    {
                        UrlParams.Add(LimitField, limit.ToString());
                    }

                    if (UrlParams.ContainsKey(OffsetField))
                    {
                        Int32.TryParse(UrlParams[OffsetField], out offset);
                    }
                    else
                    {
                        UrlParams.Add(OffsetField, offset.ToString());
                    }
                    break;

                case WebRequestType.GET_PAGE:
                    if (UrlParams.ContainsKey(LimitField))
                    {
                        Int32.TryParse(UrlParams[LimitField], out limit);
                    }
                    else
                    {
                        UrlParams.Add(LimitField, limit.ToString());
                    }

                    if (UrlParams.ContainsKey(PageField))
                    {
                        Int32.TryParse(UrlParams[PageField], out page);
                    }
                    else
                    {
                        UrlParams.Add(PageField, page.ToString());
                    }
                    break;

                case WebRequestType.POST_OFFSET:
                    dictPostContent = new Dictionary <string, string>
                    {
                        { LimitField, Limit.ToString() },
                        { OffsetField, offset.ToString() }
                    };
                    break;

                case WebRequestType.POST_PAGE:
                    dictPostContent = new Dictionary <string, string>
                    {
                        { LimitField, Limit.ToString() },
                        { PageField, page.ToString() }
                    };
                    break;
                }
                #endregion Initialization by Request Type

                do
                {
                    #region Loop Initialization
                    switch (RequestType)
                    {
                    case WebRequestType.GET_OFFSET:
                        UrlParams[OffsetField] = offset.ToString();
                        break;

                    case WebRequestType.GET_PAGE:
                        UrlParams[PageField] = page.ToString();
                        break;

                    case WebRequestType.POST_OFFSET:
                        dictPostContent[OffsetField] = offset.ToString();
                        break;

                    case WebRequestType.POST_PAGE:
                        dictPostContent[PageField] = page.ToString();
                        break;
                    }
                    #endregion Loop Initialization

                    strParam = URLParamsString;
                    urlPath  = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") ? "" : "/", strParam != "" ? "?" : "", strParam);

                    #region Get the Response by Request Type
                    switch (RequestType)
                    {
                    case WebRequestType.GET_OFFSET:
                    case WebRequestType.GET_PAGE:
                        httpResponse = httpClient.GetAsync(urlPath).Result;
                        break;

                    case WebRequestType.POST_OFFSET:
                    case WebRequestType.POST_PAGE:
                        FormUrlEncodedContent postContent = new FormUrlEncodedContent(dictPostContent);
                        httpResponse = httpClient.PostAsync(urlPath, postContent).Result;
                        break;
                    }
                    #endregion Get the Response by Request Type

                    #region Break out if StatusCode is not OK
                    if (httpResponse.StatusCode != HttpStatusCode.OK)
                    {
                        break;
                    }
                    #endregion Break out if StatusCode is not OK

                    String strResponse = httpResponse.Content.ReadAsStringAsync().Result;
                    if (strResponse.StartsWith("[") && strResponse.EndsWith("]"))
                    {
                        strResponse = $"{{\"root\":{strResponse}}}";
                    }
                    jObjectTemp = JObject.Parse(strResponse);
                    IEnumerable <JToken> allTokens = jObjectTemp.SelectTokens("*");
                    maxChildren = allTokens.Select(t => t.Count()).Max();
                    jObjectMerged.Merge(jObjectTemp);
                    page++;
                    offset += limit;
                } while (maxChildren > 1 && maxChildren >= limit && page <= maxPages);

                httpResponse.Content = new StringContent(jObjectMerged.ToString(), Encoding.UTF8, "application/json");
                break;

            case WebRequestType.CANCEL:
                httpClient.CancelPendingRequests();
                break;

            case WebRequestType.DELETE:
                httpResponse = httpClient.DeleteAsync(urlPath).Result;
                break;

            case WebRequestType.GET:
            default:
                httpResponse = httpClient.GetAsync(urlPath).Result;
                break;

            case WebRequestType.POST:
            case WebRequestType.PUT:
            case WebRequestType.SEND:
                #region Resolve MediaType
                String mediaType;

                switch (postContentType)
                {
                case WebRequestPostContentType.STRING:
                case WebRequestPostContentType.FORM_URL_ENCODED:
                default:
                    mediaType = "text/plain";
                    break;

                case WebRequestPostContentType.JSON:
                    mediaType = "application/json";
                    break;

                case WebRequestPostContentType.XML:
                case WebRequestPostContentType.SOAP:
                case WebRequestPostContentType.SOAP_STRING:
                    mediaType = "text/xml";
                    break;
                }
                #endregion Resolve MediaType

                #region Resolve Content
                HttpContent content;

                switch (postContentType)
                {
                case WebRequestPostContentType.XML:
                case WebRequestPostContentType.JSON:
                case WebRequestPostContentType.STRING:
                default:
                    content = new StringContent(strPostContent, Encoding.UTF8, mediaType);
                    break;

                case WebRequestPostContentType.FORM_URL_ENCODED:
                    Dictionary <String, String> formData = strPostContent.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(part => part.Split('='))
                                                           .ToDictionary(split => split[0], split => split[1]);
                    content = new FormUrlEncodedContent(formData);
                    break;

                case WebRequestPostContentType.SOAP:
                case WebRequestPostContentType.SOAP_STRING:
                    content = new StringContent(String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
                            <s:Body>
                                {0}
                            </s:Body>
                        </s:Envelope>", strPostContent), Encoding.UTF8, mediaType);
                    break;
                }
                #endregion Resolve Content

                switch (RequestType)
                {
                case WebRequestType.POST:
                    httpResponse = httpClient.PostAsync(urlPath, content).Result;
                    break;

                case WebRequestType.PUT:
                    httpResponse = httpClient.PutAsync(urlPath, content).Result;
                    break;

                case WebRequestType.SEND:
                    HttpRequestMessage httpContent = new HttpRequestMessage(HttpMethod.Post, urlPath)
                    {
                        Content = content, Version = HttpVersion.Version11
                    };
                    httpResponse = httpClient.SendAsync(httpContent).Result;
                    break;
                }
                break;
            }

            return(httpResponse);
        }
Пример #26
0
 private RavenBotRequest(RequestPath requestPath)
 {
     this.requestPath = requestPath;
     this.socket      = new TcpClient();
 }
Пример #27
0
 public static RavenBotRequest Create(string requestUrl)
 {
     return(new RavenBotRequest(RequestPath.Parse(requestUrl)));
 }
Пример #28
0
        IBitSet _valuesMask; //indicates if there's a value

        // creates root scope
        public OutputObjectScope()
        {
            Path = new RequestPath();
        }
Пример #29
0
 public OutputObjectScope(IFieldContext sourceFieldContext, RequestPath path, object entity)
 {
     SourceFieldContext = sourceFieldContext;
     Path   = path;
     Entity = entity;
 }
Пример #30
0
        // get handler
        private OperationHandler SelectHandler(string requestUri, IDictionary<string, object> environment, out AcceptVerbs verb)
        {
            verb = AcceptVerbs.Unknown;
            // regex優先 regex指定していない場合containsで判断
            var mapped = _options.BehaviorRouter.Instance.FirstOrDefault(rule => rule.RequestUriRegex != null ? rule.RequestUriRegex.IsMatch(requestUri) : requestUri.Contains(rule.RequestUri));
            if (mapped == null) return null;
            var key = new RequestPath(mapped.ClassName, mapped.MethodName);

            if (!_handlers.Any(kvp => kvp.Key.Equals(key))) return null;

            var handler = _handlers.First(kvp => kvp.Key.Equals(key)).Value;
            var method = environment["owin.RequestMethod"] as string;

            if (StringComparer.OrdinalIgnoreCase.Equals(method, "GET"))
                verb = AcceptVerbs.Get;
            else if (StringComparer.OrdinalIgnoreCase.Equals(method, "POST"))
                verb = AcceptVerbs.Post;
            else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PUT"))
                verb = AcceptVerbs.Put;
            else if (StringComparer.OrdinalIgnoreCase.Equals(method, "DELETE"))
                verb = AcceptVerbs.Delete;
            else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PATCH"))
                verb = AcceptVerbs.Patch;

            return handler;
        }
        /// <summary>
        /// Defines what browser should be used by sender.
        /// </summary>
        private void Button_Browse_Click(object sender, EventArgs e)
        {
            if (sender == Button_ModsDirectory)
            {
                // Browse for mods directory
                string browseMods = RequestPath.ModsDirectory();

                if (browseMods != string.Empty)
                {
                    TextBox_ModsDirectory.Text = browseMods;
                }

                if (TextBox_GameDirectory.Text != string.Empty)
                {
                    if (Literal.IsPathSubdirectory(browseMods, Path.GetDirectoryName(TextBox_GameDirectory.Text)) ||
                        browseMods == Path.GetDirectoryName(TextBox_GameDirectory.Text))
                    {
                        // If the mods directory is inside the game directory, warn the user
                        Label_Warning_ModsDirectoryInvalid.ForeColor = Color.Tomato;
                    }
                    else
                    {
                        Label_Warning_ModsDirectoryInvalid.ForeColor = SystemColors.ControlDark;
                    }
                }
            }
            else if (sender == Button_GameDirectory)
            {
                // Browse for game executables
                string browseGame = RequestPath.GameExecutable();

                if (browseGame != string.Empty)
                {
                    TextBox_GameDirectory.Text = browseGame;
                }

                if (TextBox_ModsDirectory.Text != string.Empty)
                {
                    if (Literal.IsPathSubdirectory(Path.GetDirectoryName(browseGame), TextBox_ModsDirectory.Text) ||
                        Path.GetDirectoryName(browseGame) == TextBox_ModsDirectory.Text)
                    {
                        // If the mods directory is inside the game directory, warn the user
                        Label_Warning_ModsDirectoryInvalid.ForeColor = Color.Tomato;
                    }
                    else
                    {
                        Label_Warning_ModsDirectoryInvalid.ForeColor = SystemColors.ControlDark;
                    }
                }
            }
            else if (sender == Button_EmulatorExecutable)
            {
                // Browse for emulator executables
                string browseEmulator = RequestPath.EmulatorExecutable();

                if (browseEmulator != string.Empty)
                {
                    TextBox_EmulatorExecutable.Text = browseEmulator;
                }
            }
            else if (sender == Button_SaveData)
            {
                // Browse for save data
                string browseSave = RequestPath.SaveData();

                if (browseSave != string.Empty)
                {
                    TextBox_SaveData.Text = browseSave;
                }
            }
        }
Пример #32
0
        // cache all methods
        public IReadOnlyCollection<KeyValuePair<string, OperationInfo>> RegisterHandler(Assembly[] hostAssemblies)
        {
            if (Interlocked.Increment(ref alreadyRegistered) != 0) return new KeyValuePair<string, OperationInfo>[0];

            var contractTypes = hostAssemblies
                .SelectMany(x =>
                {
                    try
                    {
                        return x.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        return ex.Types.Where(t => t != null);
                    }
                })
                .Where(x => typeof(LightNodeContract).IsAssignableFrom(x))
                .Where(x => !x.IsAbstract);

            Parallel.ForEach(contractTypes, classType =>
            {
                var className = classType.Name;
                if (!classType.GetConstructors().Any(x => x.GetParameters().Length == 0))
                {
                    throw new InvalidOperationException(string.Format("Type needs parameterless constructor, class:{0}", classType.FullName));
                }
                if (classType.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) return; // ignore

                foreach (var methodInfo in classType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) continue; // as property
                    if (methodInfo.GetCustomAttribute<IgnoreOperationAttribute>(true) != null) continue; // ignore

                    var methodName = methodInfo.Name;

                    // ignore default methods
                    if (methodName == "Equals"
                     || methodName == "GetHashCode"
                     || methodName == "GetType"
                     || methodName == "ToString")
                    {
                        continue;
                    }

                    var sw = Stopwatch.StartNew();

                    // create handler
                    var handler = new OperationHandler(options, classType, methodInfo);
                    lock (handlers)
                    {
                        // fail duplicate entry
                        var path = new RequestPath(className, methodName);
                        if (handlers.ContainsKey(path))
                        {
                            throw new InvalidOperationException(string.Format("same class and method is not allowed, class:{0} method:{1}", className, methodName));
                        }
                        handlers.Add(path, handler);
                    }

                    sw.Stop();
                    options.Logger.RegisiterOperation(handler.ClassName, handler.MethodName, sw.Elapsed.TotalMilliseconds);
                }
            });

            // return readonly operation info
            return handlers.Select(x => new KeyValuePair<string, OperationInfo>(x.Key.ToString(), new OperationInfo(x.Value))).ToList().AsReadOnly();
        }
Пример #33
0
 protected string GetContentPath()
 {
     return(Path.Combine(Helper.GetApplicationRootPath(), RequestPath.Replace('/', '\\')));
 }
Пример #34
0
        public string Execute(string json)
        {
            //妈的,没权限尼玛~  报错40016.谁知道没有这权限啊。草
            bool connect = false;
            //建立菜单集合
            Menu MenuList = new Menu();

            //第一个主菜单
            MenuInfo m1 = new MenuInfo();

            m1.type = Buttontype.click;
            m1.name = "今日头条";
            m1.key  = "rrr";


            MenuList.button.Add(m1);

            //第二个主菜单
            MenuInfo m2 = new MenuInfo();

            m2.name = "菜单";

            //建立第二主》子菜单
            MenuInfo sub21 = new MenuInfo();

            sub21.type = Buttontype.view;
            sub21.name = "搜索";
            sub21.url  = "http://www.baidu.com/";
            MenuInfo sub22 = new MenuInfo();

            sub22.type = Buttontype.scancode_waitmsg;
            sub22.name = "扫码带提示";
            sub22.key  = "V1001_TODAY_MUSIC";
            MenuInfo sub23 = new MenuInfo();

            sub23.type = Buttontype.pic_photo_or_album;
            sub23.name = "拍照或者相册发图";
            sub23.key  = "V1001_TODAY_MUSIC";
            MenuInfo sub24 = new MenuInfo();

            sub24.type = Buttontype.location_select;
            sub24.name = "发送位置";
            sub24.key  = "V1001_TODAY_MUSIC";

            m2.sub_button.Add(sub21);
            m2.sub_button.Add(sub22);
            m2.sub_button.Add(sub23);
            m2.sub_button.Add(sub24);


            MenuList.button.Add(m2);


            string RqJson = JsonHelper.Serialize(MenuList);
            //组建参数字典
            Dictionary <string, string> Para = new Dictionary <string, string>();

            Para.Add("access_token", ShareData.wxaccess_token);
            Para.Add("body", RqJson);


            string path       = RequestPath.CreatePath(RequestType.createMenu);
            RPBase IpListInfo = HTMLHelper.Post <RPBase>(path, Para, ref connect);

            if (IpListInfo != null)
            {
            }
            return("");
        }
Пример #35
0
        //HashSet<string> _keys = new HashSet<string>();

        public OutputObjectScope(RequestPath path, object entity, ObjectTypeMapping mapping)
        {
            Path    = path;
            Entity  = entity;
            Mapping = mapping;
        }
Пример #36
0
        OperationHandler SelectHandler(IDictionary<string, object> environment, IOperationCoordinator coorinator, out AcceptVerbs verb, out string ext)
        {
            // out default
            verb = AcceptVerbs.Get;
            ext = "";
            var path = environment["owin.RequestPath"] as string;
            var method = environment["owin.RequestMethod"] as string;

            // extract path
            var keyBase = path.Trim('/').Split('/');
            if (keyBase.Length != 2)
            {
                goto NOT_FOUND;
            }

            // extract "extension" for media type
            var extStart = keyBase[1].LastIndexOf(".");
            if (extStart != -1)
            {
                ext = keyBase[1].Substring(extStart + 1);
                keyBase[1] = keyBase[1].Substring(0, keyBase[1].Length - ext.Length - 1);
            }

            // {ClassName, MethodName}
            var key = new RequestPath(keyBase[0], keyBase[1]);

            OperationHandler handler;
            if (handlers.TryGetValue(key, out handler))
            {
                // verb check
                if (StringComparer.OrdinalIgnoreCase.Equals(method, "GET"))
                {
                    verb = AcceptVerbs.Get;
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(method, "POST"))
                {
                    verb = AcceptVerbs.Post;
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PUT"))
                {
                    verb = AcceptVerbs.Put;
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(method, "DELETE"))
                {
                    verb = AcceptVerbs.Delete;
                }
                else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PATCH"))
                {
                    verb = AcceptVerbs.Patch;
                }
                else
                {
                    goto VERB_MISSING;
                }

                if (!handler.AcceptVerb.HasFlag(verb))
                {
                    goto VERB_MISSING;
                }

                return handler; // OK
            }
            else
            {
                goto NOT_FOUND;
            }

            VERB_MISSING:
            coorinator.OnProcessInterrupt(options, environment, InterruptReason.MethodNotAllowed, "MethodName:" + method);
            options.Logger.MethodNotAllowed(OperationMissingKind.MethodNotAllowed, path, method);
            if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ThrowException)
            {
                throw new MethodNotAllowedException(OperationMissingKind.MethodNotAllowed, path, method);
            }
            else
            {
                environment.EmitMethodNotAllowed();
                if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails)
                {
                    environment.EmitStringMessage("MethodNotAllowed:" + method);
                }
                return null;
            }

            NOT_FOUND:
            coorinator.OnProcessInterrupt(options, environment, InterruptReason.OperationNotFound, "SearchedPath:" + path);
            options.Logger.OperationNotFound(OperationMissingKind.OperationNotFound, path);
            if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ThrowException)
            {
                throw new OperationNotFoundException(OperationMissingKind.MethodNotAllowed, path);
            }
            else
            {
                environment.EmitNotFound();
                if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails)
                {
                    environment.EmitStringMessage("OperationNotFound:" + path);
                }
                return null;
            }
        }