Exemple #1
0
        private SwaggerApi FormatMethodDescription(RestPath restPath, Dictionary <string, SwaggerModel> models)
        {
            var verbs   = new List <string>();
            var summary = restPath.Summary ?? restPath.RequestType.GetDescription();
            var notes   = restPath.Notes;

            verbs.AddRange(restPath.AllowsAllVerbs
                ? new[] { "GET", "POST", "PUT", "DELETE" }
                : restPath.AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));

            var routePath   = restPath.Path.Replace("*", "");
            var requestType = restPath.RequestType;

            var md = new SwaggerApi
            {
                Path        = routePath,
                Description = summary,
                Operations  = verbs.Map(verb => new SwaggerOperation
                {
                    Method         = verb,
                    Nickname       = requestType.Name,
                    Summary        = summary,
                    Notes          = notes,
                    Parameters     = ParseParameters(verb, requestType, models, routePath),
                    ResponseClass  = GetResponseClass(restPath, models),
                    ErrorResponses = GetMethodResponseCodes(requestType)
                })
            };

            return(md);
        }
Exemple #2
0
        public void Can_Register_NewApi_Routes_From_Assembly()
        {
            var routes = new ServiceRoutes();

            routes.AddFromAssembly(typeof(NewApiRestServiceWithAllVerbsImplemented).Assembly);

            RestPath restWithAllMethodsRoute =
                (from r in routes
                 where r.Path == "/NewApiRequestDto"
                 select r).FirstOrDefault();

            Assert.That(restWithAllMethodsRoute, Is.Not.Null);

            Assert.That(restWithAllMethodsRoute.AllowedVerbs.Contains("GET"));
            Assert.That(restWithAllMethodsRoute.AllowedVerbs.Contains("POST"));
            Assert.That(restWithAllMethodsRoute.AllowedVerbs.Contains("PUT"));
            Assert.That(restWithAllMethodsRoute.AllowedVerbs.Contains("DELETE"));
            Assert.That(restWithAllMethodsRoute.AllowedVerbs.Contains("PATCH"));

            RestPath restWithAllMethodsRoute2 =
                (from r in routes
                 where r.Path == "/NewApiRequestDto2"
                 select r).FirstOrDefault();

            Assert.That(restWithAllMethodsRoute2, Is.Not.Null);

            Assert.That(restWithAllMethodsRoute2.AllowedVerbs.Contains("GET"));
            Assert.That(restWithAllMethodsRoute2.AllowedVerbs.Contains("POST"));
            Assert.That(restWithAllMethodsRoute2.AllowedVerbs.Contains("PUT"));
            Assert.That(restWithAllMethodsRoute2.AllowedVerbs.Contains("DELETE"));
            Assert.That(restWithAllMethodsRoute2.AllowedVerbs.Contains("PATCH"));
        }
Exemple #3
0
        public void Can_deserialize_SimpleType_in_middle_of_path()
        {
            var restPath = new RestPath(typeof(SimpleType), "/simple/{Name}/some-other-literal");
            var request = restPath.CreateRequest("/simple/HelloWorld!/some-other-literal") as SimpleType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Name, Is.EqualTo("HelloWorld!"));
        }
        public void Can_deserialize_SimpleType_path()
        {
            var restPath = new RestPath(typeof(SimpleType), new RestServiceAttribute("/simple/{Name}"));
            var request  = restPath.CreateRequest("/simple/HelloWorld!") as SimpleType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Name, Is.EqualTo("HelloWorld!"));
        }
        public void Can_deserialize_SimpleType_in_middle_of_path()
        {
            var restPath = new RestPath(typeof(SimpleType), "/simple/{Name}/some-other-literal");
            var request  = restPath.CreateRequest("/simple/HelloWorld!/some-other-literal") as SimpleType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Name, Is.EqualTo("HelloWorld!"));
        }
Exemple #6
0
        public void Can_deserialize_SimpleType_path()
        {
            var restPath = new RestPath(typeof(SimpleType), new RestServiceAttribute("/simple/{Name}"));
            var request = restPath.CreateRequest("/simple/HelloWorld!") as SimpleType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Name, Is.EqualTo("HelloWorld!"));
        }
        // Entry point for HttpListener and .NET Core
        public static IHttpHandler GetHandler(IHttpRequest httpReq)
        {
            var appHost = HostContext.AppHost;

            foreach (var rawHttpHandler in appHost.RawHttpHandlersArray)
            {
                var handler = rawHttpHandler(httpReq);
                if (handler != null)
                {
                    return(handler);
                }
            }

            var mode     = appHost.Config.HandlerFactoryPath;
            var pathInfo = httpReq.PathInfo;

            //Default Request /
            if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
            {
                RestPath matchesFallback = appHost.Config.FallbackRestPath?.Invoke(httpReq);
                if (matchesFallback == null || matchesFallback.Priority > 0 ||
                    (matchesFallback.MatchRule == null && !(matchesFallback.Priority < 0))) // is not targeted fallback
                {
                    //e.g. to Process View Engine requests
                    var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
                    if (catchAllHandler != null)
                    {
                        return(catchAllHandler);
                    }
                }

                //If the fallback route can handle it, let it
                if (matchesFallback != null)
                {
                    var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out var contentType);
                    return(new RestHandler {
                        RestPath = matchesFallback, RequestName = matchesFallback.RequestType.GetOperationName(), ResponseContentType = contentType
                    });
                }

                if (mode == null)
                {
                    return(DefaultHttpHandler);
                }

                if (DefaultRootFileName != null)
                {
                    return(StaticFilesHandler);
                }

                return(NonRootModeDefaultHttpHandler);
            }

            return(GetHandlerForPathInfo(httpReq, httpReq.GetPhysicalPath())
                   ?? NotFoundHttpHandler);
        }
Exemple #8
0
        public void Can_deserialize_ComplexType_path()
        {
            var restPath = new RestPath(typeof(ComplexType),
                new RestServiceAttribute("/Complex/{Id}/{Name}/Unique/{UniqueId}"));
            var request = restPath.CreateRequest(
                "/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547") as ComplexType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Id, Is.EqualTo(5));
            Assert.That(request.Name, Is.EqualTo("Is Alive"));
            Assert.That(request.UniqueId, Is.EqualTo(new Guid("4583B364-BBDC-427F-A289-C2923DEBD547")));
        }
Exemple #9
0
        public void Can_resolve_routes_in_Turkish_Culture()
        {
            var restPath = new RestPath(typeof(LocalizationTest), "/test/{Id}");

            foreach (var varName in new[] { "id", "ID", "Id", "iD" })
            {
                //$"IsVariable({varName}) = {restPath.IsVariable(varName)}".Print();
                Assert.That(restPath.IsVariable(varName));
            }

            var request = restPath.CreateRequest("/test/3");
        }
Exemple #10
0
        public void Does_handle_ignored_routes()
        {
            var restPath       = new RestPath(typeof(IgnoreRoute3), "/ignore/{ignore}/with/{name}");
            var pathComponents = RestPath.GetPathPartsForMatching("/ignore/AnyThing/with/foo");
            var score          = restPath.MatchScore("GET", pathComponents);

            Assert.That(score, Is.GreaterThan(0));

            var request = (IgnoreRoute3)restPath.CreateRequest("/ignore/AnyThing/with/foo");

            Assert.That(request.Name, Is.EqualTo("foo"));
        }
        public void Can_deserialize_ComplexType_path()
        {
            var restPath = new RestPath(typeof(ComplexType),
                                        "/Complex/{Id}/{Name}/Unique/{UniqueId}");
            var request = restPath.CreateRequest(
                "/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547") as ComplexType;

            Assert.That(request, Is.Not.Null);
            Assert.That(request.Id, Is.EqualTo(5));
            Assert.That(request.Name, Is.EqualTo("Is Alive"));
            Assert.That(request.UniqueId, Is.EqualTo(new Guid("4583B364-BBDC-427F-A289-C2923DEBD547")));
        }
        // Entry point for HttpListener and .NET Core
        public static IHttpHandler GetHandler(IHttpRequest httpReq)
        {
            var appHost = HostContext.AppHost;

            foreach (var rawHttpHandler in appHost.RawHttpHandlersArray)
            {
                var handler = rawHttpHandler(httpReq);
                if (handler != null)
                {
                    return(handler);
                }
            }

            var mode     = appHost.Config.HandlerFactoryPath;
            var pathInfo = httpReq.PathInfo;

            //Default Request /
            if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
            {
                //If the fallback route can handle it, let it
                RestPath restPath = appHost.Config.FallbackRestPath?.Invoke(httpReq);
                if (restPath != null)
                {
                    var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out var contentType);
                    return(new RestHandler {
                        RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType
                    });
                }

                //e.g. CatchAllHandler to Process Markdown files
                var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
                if (catchAllHandler != null)
                {
                    return(catchAllHandler);
                }

                if (mode == null)
                {
                    return(DefaultHttpHandler);
                }

                if (DefaultRootFileName != null)
                {
                    return(StaticFilesHandler);
                }

                return(NonRootModeDefaultHttpHandler);
            }

            return(GetHandlerForPathInfo(httpReq, httpReq.GetPhysicalPath())
                   ?? NotFoundHttpHandler);
        }
 private T StringToPoco <T>(string str)
 {
     using (new BasicAppHost().Init())
     {
         NameValueCollection queryString = HttpUtility.ParseQueryString(str);
         var restPath    = new RestPath(typeof(T), "/query", "GET, POST");
         var restHandler = new RestHandler();
         var httpReq     = new MockHttpRequest("query", "GET", "application/json", "query", queryString,
                                               new MemoryStream(), new NameValueCollection());
         httpReq.SetRoute(restPath);
         var request = (T)restHandler.CreateRequestAsync(httpReq, "query").Result;
         return(request);
     }
 }
Exemple #14
0
        private T StringToPoco <T>(string str)
        {
            var testAppHost = new TestAppHost(new Container(), GetType().Assembly);
            NameValueCollection queryString = HttpUtility.ParseQueryString(str);
            var restPath    = new RestPath(typeof(T), "/query", "GET, POST");
            var restHandler = new RestHandler()
            {
                RestPath = restPath
            };
            var httpReq = new HttpRequestMock("query", "GET", "application/json", "query", queryString,
                                              new MemoryStream(), new NameValueCollection());
            var request = (T)restHandler.CreateRequest(httpReq, "query");

            return(request);
        }
Exemple #15
0
        private SwaggerApi FormatMethodDescription(RestPath restPath, Dictionary <string, SwaggerModel> models)
        {
            var verbs   = new List <string>();
            var summary = restPath.Summary ?? restPath.RequestType.GetDescription();
            var notes   = restPath.Notes;

            string verbTemp = (typeof(ISpecificRecord).IsAssignableFrom(restPath.RequestType)) ? "POST" : "GET";

            //verbs.AddRange(restPath.AllowsAllVerbs
            //    ? new[] { "GET", "POST", "PUT", "DELETE" }
            //    : restPath.AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            verbs.Add(verbTemp);
            var routePath   = restPath.Path.Replace("*", "");
            var requestType = restPath.RequestType;

            var md = new SwaggerApi
            {
                Path        = routePath,
                Description = summary,
                Operations  = verbs.Map(verb => new SwaggerOperation
                {
                    Method         = verb.ToString(),
                    Nickname       = requestType.Name,
                    Summary        = summary,
                    Notes          = notes,
                    Parameters     = ParseParameters(verb.ToString(), requestType, models, routePath, restPath),
                    ResponseClass  = GetResponseClass(restPath, models),
                    ErrorResponses = GetMethodResponseCodes(requestType)
                })
            };

            //if (_config.UseCticket)
            //{
            //    foreach (var swaggerOperation in md.Operations)
            //    {
            //        swaggerOperation.Parameters.Add(new SwaggerParameter
            //        {
            //            AllowMultiple = false,
            //            Required = false,
            //            Name = "cticket",
            //            Description = "携程登录态",
            //            ParamType = "header",
            //            Type = "string"
            //        });
            //    }
            //}
            return(md);
        }
Exemple #16
0
        public void Can_deserialize_ComplexTypeWithFields_path()
        {
            using (JsConfig.With(new Config {
                IncludePublicFields = true
            }))
            {
                var restPath = new RestPath(typeof(ComplexTypeWithFields),
                                            "/Complex/{Id}/{Name}/Unique/{UniqueId}");
                var request = restPath.CreateRequest(
                    "/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547") as ComplexTypeWithFields;

                Assert.That(request, Is.Not.Null);
                Assert.That(request.Id, Is.EqualTo(5));
                Assert.That(request.Name, Is.EqualTo("Is Alive"));
                Assert.That(request.UniqueId, Is.EqualTo(new Guid("4583B364-BBDC-427F-A289-C2923DEBD547")));
            }
        }
        public void Can_deserialize_TestRequest_QueryStringSerializer_output()
        {
            // Setup
            using (new BasicAppHost(typeof(TestService).Assembly).Init())
            {
                var restPath      = new RestPath(typeof(TestRequest), "/service", "GET");
                var restHandler   = new RestHandler();
                var requestString = "ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}";
                NameValueCollection queryString = HttpUtility.ParseQueryString(requestString);
                var httpReq = new MockHttpRequest("service", "GET", "application/json", "service", queryString, new MemoryStream(), new NameValueCollection());
                httpReq.SetRoute(restPath);
                var request2 = (TestRequest)restHandler.CreateRequestAsync(httpReq, "service").Result;

                Assert.That(request2.ListOfA.Count, Is.EqualTo(1));
                Assert.That(request2.ListOfA.First().ListOfB.Count, Is.EqualTo(2));
            }
        }
		private static void AssertMatch(string definitionPath, string requestPath,
			string firstMatchHashKey, BbcMusicRequest expectedRequest)
		{
			var restPath = new RestPath(typeof(BbcMusicRequest), definitionPath);

			var reqestTestPath = RestPath.GetPathPartsForMatching(requestPath);
			Assert.That(restPath.IsMatch("GET", reqestTestPath), Is.True);

			Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

			var actualRequest = restPath.CreateRequest(requestPath) as BbcMusicRequest;

			Assert.That(actualRequest, Is.Not.Null);
			Assert.That(actualRequest.mbz_guid, Is.EqualTo(expectedRequest.mbz_guid));
			Assert.That(actualRequest.release_type, Is.EqualTo(expectedRequest.release_type));
			Assert.That(actualRequest.content_type, Is.EqualTo(expectedRequest.content_type));
		}
Exemple #19
0
        public void Can_deserialize_TestRequest_QueryStringSerializer_output()
        {
            // Setup
            var testAppHost = new TestAppHost(new Container(), typeof(TestService).Assembly);
            var restPath    = new RestPath(typeof(TestRequest), "/service", "GET");
            var restHandler = new RestHandler {
                RestPath = restPath
            };

            var requestString = "ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}";
            NameValueCollection queryString = HttpUtility.ParseQueryString(requestString);
            var httpReq = new HttpRequestMock("service", "GET", "application/json", "service", queryString, new MemoryStream(), new NameValueCollection());

            var request2 = (TestRequest)restHandler.CreateRequest(httpReq, "service");

            Assert.That(request2.ListOfA.Count, Is.EqualTo(1));
            Assert.That(request2.ListOfA.First().ListOfB.Count, Is.EqualTo(2));
        }
Exemple #20
0
        public void Can_Register_Routes_With_Partially_Implemented_REST_Verbs()
        {
            var routes = new ServiceRoutes();

            routes.AddFromAssembly(typeof(RestServiceWithSomeVerbsImplemented).Assembly);

            RestPath restWithAFewMethodsRoute = (from r in routes.RestPaths
                                                 where r.Path == "RestServiceWithSomeVerbsImplemented"
                                                 select r).FirstOrDefault();

            Assert.That(restWithAFewMethodsRoute, Is.Not.Null);

            Assert.That(restWithAFewMethodsRoute.AllowedVerbs.Contains("GET"), Is.True);
            Assert.That(restWithAFewMethodsRoute.AllowedVerbs.Contains("POST"), Is.False);
            Assert.That(restWithAFewMethodsRoute.AllowedVerbs.Contains("PUT"), Is.True);
            Assert.That(restWithAFewMethodsRoute.AllowedVerbs.Contains("DELETE"), Is.False);
            Assert.That(restWithAFewMethodsRoute.AllowedVerbs.Contains("PATCH"), Is.False);
        }
            public static List <SlugRoute> GetOrderedMatchingRules(string withVerb, string forPath)
            {
                var matchingRoutes = new List <SlugRoute>();

                foreach (var definition in Definitions)
                {
                    var pathComponents = RestPath.GetPathPartsForMatching(forPath);
                    definition.Score = definition.RestPath.MatchScore(withVerb, pathComponents);
                    if (definition.Score > 0)
                    {
                        matchingRoutes.Add(definition);
                    }
                }

                var orderedRoutes = matchingRoutes.OrderByDescending(x => x.Score).ToList();

                return(orderedRoutes);
            }
        private static void AssertMatch(string definitionPath, string requestPath, string firstMatchHashKey,
                                        SlugRequest expectedRequest, int expectedScore)
        {
            var restPath        = new RestPath(typeof(SlugRequest), definitionPath);
            var requestTestPath = RestPath.GetPathPartsForMatching(requestPath);

            Assert.That(restPath.IsMatch("GET", requestTestPath), Is.True);

            Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

            var actualRequest = restPath.CreateRequest(requestPath) as SlugRequest;

            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest.Slug, Is.EqualTo(expectedRequest.Slug));
            Assert.That(actualRequest.Version, Is.EqualTo(expectedRequest.Version));
            Assert.That(actualRequest.Options, Is.EqualTo(expectedRequest.Options));
            Assert.That(restPath.MatchScore("GET", requestTestPath), Is.EqualTo(expectedScore));
        }
        private static void AssertMatch(string definitionPath, string requestPath,
                                        string firstMatchHashKey, BbcMusicRequest expectedRequest)
        {
            var restPath = new RestPath(typeof(BbcMusicRequest), definitionPath);

            var reqestTestPath = RestPath.GetPathPartsForMatching(requestPath);

            Assert.That(restPath.IsMatch("GET", reqestTestPath), Is.True);

            Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

            var actualRequest = restPath.CreateRequest(requestPath) as BbcMusicRequest;

            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest.mbz_guid, Is.EqualTo(expectedRequest.mbz_guid));
            Assert.That(actualRequest.release_type, Is.EqualTo(expectedRequest.release_type));
            Assert.That(actualRequest.content_type, Is.EqualTo(expectedRequest.content_type));
        }
        private static void AssertMatch(string definitionPath, string requestPath,
                                        string firstMatchHashKey, RackSpaceRequest expectedRequest)
        {
            var restPath = new RestPath(typeof(RackSpaceRequest), definitionPath);

            var reqestTestPath = RestPath.GetPathPartsForMatching(requestPath);

            Assert.That(restPath.IsMatch("GET", reqestTestPath), Is.True);

            Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

            var actualRequest = restPath.CreateRequest(requestPath) as RackSpaceRequest;

            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest.version, Is.EqualTo(expectedRequest.version));
            Assert.That(actualRequest.id, Is.EqualTo(expectedRequest.id));
            Assert.That(actualRequest.resource_type, Is.EqualTo(expectedRequest.resource_type));
            Assert.That(actualRequest.action, Is.EqualTo(expectedRequest.action));
        }
Exemple #25
0
        private string GenerateNickname(string verb, RestPath restPath)
        {
            string nickName = verb.ToLowerInvariant() + restPath.Path;

            var routeAttributes = restPath.RequestType.GetCustomAttributes(typeof(NamedRouteAttribute), true);

            var attr = routeAttributes.FirstOrDefault(
                attrib => ((NamedRouteAttribute)attrib).Verbs == restPath.AllowedVerbs);

            if (attr != null)
            {
                var routeName = ((NamedRouteAttribute)attr).Name;

                if (!string.IsNullOrEmpty(routeName))
                {
                    nickName = routeName;
                }
            }

            return(this.nicknameCleanerRegex.Replace(nickName, string.Empty));
        }
Exemple #26
0
        private T StringToPoco <T>(string str)
        {
            var envKey = Environment.GetEnvironmentVariable("SERVICESTACK_LICENSE");

            if (!string.IsNullOrEmpty(envKey))
            {
                Licensing.RegisterLicense(envKey);
            }
            using (new BasicAppHost().Init())
            {
                NameValueCollection queryString = HttpUtility.ParseQueryString(str);
                var restPath    = new RestPath(typeof(T), "/query", "GET, POST");
                var restHandler = new RestHandler
                {
                    RestPath = restPath
                };
                var httpReq = new MockHttpRequest("query", "GET", "application/json", "query", queryString,
                                                  new MemoryStream(), new NameValueCollection());
                var request = (T)restHandler.CreateRequestAsync(httpReq, "query").Result;
                return(request);
            }
        }
Exemple #27
0
        private MethodDescription FormateMethodDescription(
            RestPath restPath,
            Dictionary <string, SwaggerModel> models)
        {
            var verbs   = new List <string>();
            var summary = restPath.Summary;
            var notes   = restPath.Notes;

            if (restPath.AllowsAllVerbs)
            {
                verbs.AddRange(new[] { "GET", "POST", "PUT", "DELETE" });
            }
            else
            {
                verbs.AddRange(
                    restPath.AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }

            var md = new MethodDescription
            {
                Path        = restPath.Path,
                Description = summary,
                Operations  = verbs.Select(
                    verb =>
                    new MethodOperation
                {
                    HttpMethod     = verb,
                    Nickname       = this.GenerateNickname(verb, restPath),
                    Summary        = summary,
                    Notes          = notes,
                    Parameters     = ParseParameters(verb, restPath.RequestType, models),
                    ResponseClass  = GetResponseClass(restPath, models),
                    ErrorResponses = GetMethodResponseCodes(restPath.RequestType)
                }).ToList()
            };

            return(md);
        }
Exemple #28
0
 public void Can_match_lowercase_http_method()
 {
     var restPath = new RestPath(typeof (ComplexType), "/Complex/{Id}/{Name}/Unique/{UniqueId}", "PUT");
     var withPathInfoParts = RestPath.GetPathPartsForMatching("/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547");
     Assert.That(restPath.IsMatch("put", withPathInfoParts));
 }
 public static void SetRoute(this IRequest req, RestPath route)
 {
     req.Items[Keywords.Route] = route;
 }
Exemple #30
0
        public void Can_deserialize_ComplexTypeWithFields_path()
        {
            using (JsConfig.With(includePublicFields: true))
            {
                var restPath = new RestPath(typeof(ComplexTypeWithFields),
                    "/Complex/{Id}/{Name}/Unique/{UniqueId}");
                var request = restPath.CreateRequest(
                    "/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547") as ComplexTypeWithFields;

                Assert.That(request, Is.Not.Null);
                Assert.That(request.Id, Is.EqualTo(5));
                Assert.That(request.Name, Is.EqualTo("Is Alive"));
                Assert.That(request.UniqueId, Is.EqualTo(new Guid("4583B364-BBDC-427F-A289-C2923DEBD547")));
            }
        }
Exemple #31
0
        private List <SwaggerParameter> ParseParameters(string verb, Type operationType, IDictionary <string, SwaggerModel> models, string route, RestPath restPath = null)
        {
            var hasDataContract = PlatformExtensions.HasAttribute <DataContractAttribute>(operationType);



            var paramAttrs                 = new Dictionary <string, ApiMemberAttribute[]>();
            var allowableParams            = new List <ApiAllowableValuesAttribute>();
            var defaultOperationParameters = new List <SwaggerParameter>();

            var hasApiMembers = false;

            if (operationType.Namespace != null && operationType.Namespace.Contains("System") && restPath != null)
            {
                var paramerters     = restPath.ServiceMethod.GetParameters();
                var paramAttributes = restPath.ServiceMethod.AllCustomAttributes <SwaggerParamAttribute>();
                foreach (var par in paramerters)
                {
                    var customParam = paramAttributes.FirstOrDefault(r => r.Name.Equals(par.Name));
                    var required    = true;
                    if (par.IsOptional)
                    {
                        required = false;
                    }
                    else if (customParam != null)
                    {
                        required = customParam.Required;
                    }
                    var inPath    = (route ?? "").ToLower().Contains("{" + operationType.Name.ToLower() + "}");
                    var paramType = inPath
                        ? "path"
                        : verb == HttpMethods.Post || verb == HttpMethods.Put
                            ? "form"
                            : "query";
                    if (verb != HttpMethods.Post && verb != HttpMethods.Put)
                    {
                        defaultOperationParameters.Add(new SwaggerParameter
                        {
                            Type          = operationType.Name.ToLower(),
                            AllowMultiple = false,
                            Description   = customParam != null ? customParam.Description : string.Empty,
                            Name          = par.Name,
                            ParamType     = paramType,
                            Required      = required,
                            Enum          = null,
                        });
                    }
                }
            }
            else
            {
                var properties = operationType.GetProperties();
                foreach (var property in properties)
                {
                    if (property.HasAttribute <IgnoreDataMemberAttribute>())
                    {
                        continue;
                    }

                    var attr = hasDataContract
                        ? property.FirstAttribute <DataMemberAttribute>()
                        : null;

                    var propertyName = attr != null && attr.Name != null
                        ? attr.Name
                        : property.Name;

                    var apiMembers = property.AllAttributes <ApiMemberAttribute>();
                    if (apiMembers.Length > 0)
                    {
                        hasApiMembers = true;
                    }

                    paramAttrs[propertyName] = apiMembers;
                    var allowableValuesAttrs = property.AllAttributes <ApiAllowableValuesAttribute>();
                    allowableParams.AddRange(allowableValuesAttrs);

                    if (hasDataContract && attr == null)
                    {
                        continue;
                    }

                    var inPath    = (route ?? "").ToLower().Contains("{" + propertyName.ToLower() + "}");
                    var paramType = inPath
                        ? "path"
                        : verb == HttpMethods.Post || verb == HttpMethods.Put
                            ? "form"
                            : "query";

                    if (verb != HttpMethods.Post && verb != HttpMethods.Put)
                    {
                        defaultOperationParameters.Add(new SwaggerParameter
                        {
                            Type          = GetSwaggerTypeName(property.PropertyType),
                            AllowMultiple = false,
                            Description   = property.GetDescription(),
                            Name          = propertyName,
                            ParamType     = paramType,
                            Required      = true,
                            Enum          = GetEnumValues(allowableValuesAttrs.FirstOrDefault()),
                        });
                    }
                }
            }


            if (restPath != null)
            {
                //Header
                var headerAttributes = restPath.ServiceMethod.AllCustomAttributes <SwaggerHeaderAttribute>();
                foreach (var header in headerAttributes)
                {
                    defaultOperationParameters.Add(new SwaggerParameter
                    {
                        AllowMultiple = false,
                        Required      = header.Required,
                        Name          = header.Name,
                        Description   = header.Description,
                        ParamType     = "header",
                        Type          = "string"
                    });
                }

                //File
                var fileAttributes = restPath.ServiceMethod.AllCustomAttributes <SwaggerFileAttribute>();
                foreach (var file in fileAttributes)
                {
                    defaultOperationParameters.Add(new SwaggerParameter
                    {
                        AllowMultiple = false,
                        Required      = file.Required,
                        Name          = file.Name,
                        Description   = file.Description,
                        ParamType     = "formData",
                        Type          = "file"
                    });
                }
            }

            var methodOperationParameters = defaultOperationParameters;

            if (hasApiMembers)
            {
                methodOperationParameters = new List <SwaggerParameter>();
                foreach (var key in paramAttrs.Keys)
                {
                    var apiMembers = paramAttrs[key];
                    foreach (var member in apiMembers)
                    {
                        if ((member.Verb == null || string.Compare(member.Verb, verb, StringComparison.OrdinalIgnoreCase) == 0) &&
                            !string.Equals(member.ParameterType, "model") &&
                            methodOperationParameters.All(x => x.Name != (member.Name ?? key)))
                        {
                            methodOperationParameters.Add(new SwaggerParameter
                            {
                                Type          = member.DataType ?? SwaggerType.String,
                                AllowMultiple = member.AllowMultiple,
                                Description   = member.Description,
                                Name          = member.Name ?? key,
                                ParamType     = member.GetParamType(_config, member.Name ?? key, member.Verb ?? verb),
                                Required      = member.IsRequired,
                                Enum          = GetEnumValues(allowableParams.FirstOrDefault(attr => attr.Name == (member.Name ?? key)))
                            });
                        }
                    }
                }
            }

            if (!DisableAutoDtoInBodyParam)
            {
                if (!HttpMethods.Get.EqualsIgnoreCase(verb) && !HttpMethods.Delete.EqualsIgnoreCase(verb) &&
                    !methodOperationParameters.Any(p => "body".EqualsIgnoreCase(p.ParamType)))
                {
                    ParseModel(models, operationType, route, verb);
                    methodOperationParameters.Add(new SwaggerParameter
                    {
                        ParamType = "body",
                        Name      = "body",
                        Type      = GetSwaggerTypeName(operationType, route, verb),
                        Required  = true
                    });
                }
            }
            return(methodOperationParameters);
        }
Exemple #32
0
        private static void AssertMatch(string definitionPath, string requestPath,
            string firstMatchHashKey, RackSpaceRequest expectedRequest)
        {
            var restPath = new RestPath(typeof(RackSpaceRequest), definitionPath);

            var reqestTestPath = RestPath.GetPathPartsForMatching(requestPath);
            Assert.That(restPath.IsMatch("GET", reqestTestPath), Is.True);

            Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

            var actualRequest = restPath.CreateRequest(requestPath) as RackSpaceRequest;

            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest.version, Is.EqualTo(expectedRequest.version));
            Assert.That(actualRequest.id, Is.EqualTo(expectedRequest.id));
            Assert.That(actualRequest.resource_type, Is.EqualTo(expectedRequest.resource_type));
            Assert.That(actualRequest.action, Is.EqualTo(expectedRequest.action));
        }
Exemple #33
0
        private static void AssertMatch(string definitionPath, string requestPath, string firstMatchHashKey,
                                        SlugRequest expectedRequest, int expectedScore)
        {
            var restPath = new RestPath(typeof(SlugRequest), definitionPath);
            var requestTestPath = RestPath.GetPathPartsForMatching(requestPath);
            Assert.That(restPath.IsMatch("GET", requestTestPath), Is.True);

            Assert.That(firstMatchHashKey, Is.EqualTo(restPath.FirstMatchHashKey));

            var actualRequest = restPath.CreateRequest(requestPath) as SlugRequest;
            Assert.That(actualRequest, Is.Not.Null);
            Assert.That(actualRequest.Slug, Is.EqualTo(expectedRequest.Slug));
            Assert.That(actualRequest.Version, Is.EqualTo(expectedRequest.Version));
            Assert.That(actualRequest.Options, Is.EqualTo(expectedRequest.Options));
            Assert.That(restPath.MatchScore("GET", requestTestPath), Is.EqualTo(expectedScore));
        }
        // Entry point for ASP.NET
        public IHttpHandler GetHandler(HttpContext ctx, string requestType, string url, string pathTranslated)
        {
            var appHost = HostContext.AppHost;

            DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated;
            var httpReq = new Host.AspNet.AspNetRequest(ctx.Request.RequestContext.HttpContext, url.SanitizedVirtualPath());

            foreach (var rawHttpHandler in appHost.RawHttpHandlersArray)
            {
                var handler = rawHttpHandler(httpReq);
                if (handler != null)
                {
                    return(handler);
                }
            }

            var pathInfo = httpReq.PathInfo;

            //WebDev Server auto requests '/default.aspx' so re-correct path to different default document
            var mode = appHost.Config.HandlerFactoryPath;

            if (mode == null && (url == "/default.aspx" || url == "/Default.aspx"))
            {
                pathInfo = "/";
            }

            //Default Request /
            if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
            {
                RestPath matchesFallback = appHost.Config.FallbackRestPath?.Invoke(httpReq);
                if (matchesFallback == null || matchesFallback.Priority > 0 ||
                    (matchesFallback.MatchRule == null && !(matchesFallback.Priority < 0))) // is not targeted fallback
                {
                    //e.g. to Process View Engine requests
                    var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
                    if (catchAllHandler != null)
                    {
                        return(catchAllHandler);
                    }
                }

                //If the fallback route can handle it, let it
                if (matchesFallback != null)
                {
                    var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out var contentType);
                    return(new RestHandler {
                        RestPath = matchesFallback, RequestName = matchesFallback.RequestType.GetOperationName(), ResponseContentType = contentType
                    });
                }

                if (mode == null)
                {
                    return(DefaultHttpHandler);
                }

                if (DefaultRootFileName != null)
                {
                    return(StaticFilesHandler);
                }

                return(NonRootModeDefaultHttpHandler);
            }

            return(GetHandlerForPathInfo(httpReq, pathTranslated)
                   ?? NotFoundHttpHandler);
        }
        /// <summary>
        /// Is user allowed to use service.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            GXAmiUser user;
            OrmLiteConnectionFactory f = authService.TryResolve <IDbConnectionFactory>() as OrmLiteConnectionFactory;

            //Connection factory is null when we are configure server at first time.
            if (f == null || f.ConnectionString == null)
            {
                return(true);
            }
            try
            {
                using (IDbConnection Db = f.OpenDbConnection())
                {
                    lock (Db)
                    {
                        if (!GuruxAMI.Service.GXManagementService.IsDatabaseCreated(Db))
                        {
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                            string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (string.Compare(target, typeof(GXIsDatabaseCreatedRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXCreateTablesRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXDropTablesRequest).Name, true) == 0)
                            {
                                user    = new GXAmiUser("gurux", "gurux", UserAccessRights.SuperAdmin);
                                user.Id = 1;
                                InitUser(authService, user);
                                return(true);
                            }
                            return(false);
                        }
                        List <GXAmiUser> users = Db.Select <GXAmiUser>(q => q.Name == userName && q.Password == password);
                        if (users.Count != 1)
                        {
                            //If known DC try to get new tasks, add new task, mark task claimed or add device exception.
                            Guid guid;
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                            string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (items != null && items.Length != 0)
                            {
                                if (string.Compare(target, typeof(GXEventsRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsRegisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsUnregisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskDeleteRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskUpdateRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksClaimRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTraceLevelRequest).Name, true) == 0)
                                {
                                    //If DC register first time and starts to listen events.
                                    if (IsGuid(userName, out guid))
                                    {
                                        //If known DC wants to listen events.
                                        List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                        if (list.Count == 1)
                                        {
                                            IAuthSession s = authService.GetSession(false);
                                            s.Id              = userName;
                                            s.UserAuthId      = Guid.NewGuid().ToString();
                                            s.UserName        = userName;
                                            s.IsAuthenticated = true;
                                            s.Roles           = new List <string>();
                                            s.Roles.Add("0");
                                            return(true);
                                        }
                                        return(false);
                                    }
                                    return(false);
                                }
                                else if (string.Compare(target, typeof(GXDataCollectorUpdateRequest).Name, true) == 0 &&
                                         IsGuid(userName, out guid))
                                {
                                    if (guid == Guid.Empty)
                                    {
                                        /* TODO:
                                         * IAuthSession s = authService.GetSession(false);
                                         * s.Id = userName;
                                         * s.UserAuthId = Guid.NewGuid().ToString();
                                         * s.UserName = userName;
                                         * s.IsAuthenticated = true;
                                         * s.Roles = new List<string>();
                                         * s.Roles.Add("0");
                                         * */
                                        return(true);
                                    }
                                    //If DC updates itself.
                                    List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id              = userName;
                                        s.UserAuthId      = Guid.NewGuid().ToString();
                                        s.UserName        = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles           = new List <string>();
                                        s.Roles.Add("0");
                                        return(true);
                                    }
                                    return(false);
                                }
                                //If data collector wants to get data from itself by Guid.
                                else if (string.Compare(target, typeof(GXDataCollectorsRequest).Name, true) == 0 &&
                                         IsGuid(userName, out guid))
                                {
                                    List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id              = userName;
                                        s.UserAuthId      = Guid.NewGuid().ToString();
                                        s.UserName        = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles           = new List <string>();
                                        s.Roles.Add("0");
                                        return(true);
                                    }
                                    return(false);
                                }
                                return(false);
                            }
                        }
                        user = users[0];
                        InitUser(authService, user);
                    }
                }
            }
            catch (Exception ex)
            {
                GuruxAMI.Server.AppHost.ReportError(ex);
                try
                {
                    if (!System.Diagnostics.EventLog.SourceExists("GuruxAMI"))
                    {
                        System.Diagnostics.EventLog.CreateEventSource("GuruxAMI", "Application");
                    }
                    System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                    appLog.Source = "GuruxAMI";
                    appLog.WriteEntry(ex.Message);
                }
                catch (System.Security.SecurityException)
                {
                    //Security exception is thrown if GuruxAMI source is not exists and it's try to create without administrator privilege.
                    //Just skip this, but errors are not write to eventlog.
                }
                throw ex;
            }
            return(true);
        }
Exemple #36
0
 private static void AssertNoMatch(string definitionPath, string requestPath)
 {
     var restPath = new RestPath(typeof(SlugRequest), definitionPath);
     var requestTestPath = RestPath.GetPathPartsForMatching(requestPath);
     Assert.That(restPath.IsMatch("GET", requestTestPath), Is.False);
 }
Exemple #37
0
 public SlugRoute(string definition)
 {
     this.Definition = definition;
     var parts = definition.SplitOnFirst(' ');
     RestPath = new RestPath(typeof(SlugRequest), path: parts[1], verbs: parts[0] == "ANY" ? null : parts[0]);
 }
Exemple #38
0
 public static void SetRoute(this IRequest req, RestPath route)
 {
     req.Items["__route"] = route;
 }