Beispiel #1
0
        private static void AddUriParameters(MethodBase methodBase, UriTemplate uriTemplate, IReadOnlyList <object> arguments)
        {
            var parameters = methodBase.GetParameters();

            for (var i = 0; i < arguments.Count; ++i)
            {
                if (parameters[i].IsDefined(typeof(ToBodyAttribute)))
                {
                    continue;
                }

                if (IsUriParameterType(parameters[i].ParameterType))
                {
                    uriTemplate.SetParameter(parameters[i].Name, string.Format(CultureInfo.InvariantCulture, "{0}", arguments[i]));
                    continue;
                }

                if (!parameters[i].IsDefined(typeof(ToUriAttribute)))
                {
                    continue;
                }

                if (arguments[i] == null)
                {
                    throw new ArgumentNullException(parameters[i].Name);
                }

                foreach (var property in arguments[i].GetType().GetProperties())
                {
                    uriTemplate.SetParameter(property.Name, string.Format(CultureInfo.InvariantCulture, "{0}", property.GetValue(arguments[i])));
                }
            }
        }
        public Uri GenerateRequestUrl(Type type, string query = "*", int start = 0, int limit = 10)
        {
            string metaTypeName = GetMetaTypeName(type);

            var ftsQueryRequest = new FTSQueryRequest
            {
                Statements = new List <Statement>
                {
                    new Statement {
                        Query = query
                    }
                },
                Start = start,
                Limit = limit
            };

            var ftsQueryRequestString = JsonConvert.SerializeObject(ftsQueryRequest);

            var template = new UriTemplate(BaseAddress + "/" + SearchTemplate);

            template.SetParameter("metaType", metaTypeName);
            template.SetParameter("query", ftsQueryRequestString);

            return(new Uri(template.Resolve()));
        }
Beispiel #3
0
        public void FactMethodName()
        {
            UriTemplate template = new UriTemplate("https://api.github.com/search/code?q={query}{&page,per_page,sort,order}");

            template.SetParameter("query", "1234");
            template.SetParameter("per_page", "19");
            var result = template.Resolve();
        }
Beispiel #4
0
        public void ResolveOptionalAndRequiredQueryParameters()
        {
            UriTemplate template = new UriTemplate("https://api.github.com/search/code?q={query}{&page,per_page,sort,order}");

            template.SetParameter("query", "1234");
            template.SetParameter("per_page", "19");
            var result = template.Resolve();

            Assert.Equal("https://api.github.com/search/code?q=1234&per_page=19", result);
        }
Beispiel #5
0
        public void ShouldAllowUriTemplateWithMultiplePathSegmentParameter()
        {
            var template = new UriTemplate("http://example.org/foo/{bar}/baz/{blar}");

            template.SetParameter("bar", "yo");
            template.SetParameter("blar", "yuck");
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo/yo/baz/yuck", uriString);
        }
Beispiel #6
0
        public void Query_param_with_empty_array()
        {
            UriTemplate template = new UriTemplate("/foo/{foo}/baz{?haz*}");

            template.SetParameter("foo", "1234");
            template.SetParameter("haz", new string[] {});

            string uri = template.Resolve();

            Assert.Equal("/foo/1234/baz", uri);
        }
Beispiel #7
0
        public void Query_param_with_list_array()
        {
            var template = new UriTemplate("/foo/{foo}/baz{?haz}");

            template.SetParameter("foo", "1234");
            template.SetParameter("haz", new[] { "foo", "bar" });

            var uri = template.Resolve();

            Assert.Equal("/foo/1234/baz?haz=foo,bar", uri);
        }
Beispiel #8
0
        public void ShouldAllowUriTemplateToRemoveParameter()
        {
            var template = new UriTemplate("http://example.org/foo{?bar,baz}");

            template.SetParameter("bar", "yo");
            template.SetParameter("baz", "yuck");
            template.ClearParameter("bar");

            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo?baz=yuck", uriString);
        }
Beispiel #9
0
        public void ShouldResolveMatrixParameter()
        {
            var template = new UriTemplate("http://example.org/foo{;lat,lng}");

            double lat = 31.464, lng = 74.386;

            template.SetParameter("lat", lat);
            template.SetParameter("lng", lng);

            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo;lat=31.464;lng=74.386", uriString);
        }
Beispiel #10
0
        public void ShouldResolveUriTemplateWithNonStringParameter()
        {
            var template = new UriTemplate("http://example.org/foo/{bar}/baz{?lat,lng}");

            double lat = 31.464, lng = 74.386;

            template.SetParameter("bar", "yo");
            template.SetParameter("lat", lat);
            template.SetParameter("lng", lng);

            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo/yo/baz?lat=31.464&lng=74.386", uriString);
        }
Beispiel #11
0
        public void ShouldAllowListAndSingleValueInQueryParam()
        {
            var template = new UriTemplate("http://example.org{/id*}{?fields,token}");

            template.SetParameter("id", new List <string> {
                "person", "albums"
            });
            template.SetParameter("fields", new List <string> {
                "id", "name", "picture"
            });
            template.SetParameter("token", "12345");
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/person/albums?fields=id,name,picture&token=12345", uriString);
        }
Beispiel #12
0
        //2.0 operations don't have a path so....
        private OperationPath20 NormalizeOperationPath(NormalizationApiOperation op)
        {
            var pathBuilder = new StringBuilder('/');

            var basePath = NormalizeBasePath(op.BasePath);

            if (!string.IsNullOrWhiteSpace(basePath))
            {
                pathBuilder.Append(basePath);
            }
            if (!string.IsNullOrWhiteSpace(op.Path))
            {
                var opPath = op.Path;
                if (opPath.StartsWith("/", StringComparison.InvariantCultureIgnoreCase))
                {
                    opPath = opPath.Length == 1 ? string.Empty : opPath.Substring(1);
                }
                pathBuilder.Append(opPath);
            }

            var path = pathBuilder.ToString();

            var versionParam = op.Parameters.FirstOrDefault(x => x.Name.IndexOf(Constants.ParameterName_Version, StringComparison.InvariantCultureIgnoreCase) >= 0);

            if (versionParam != null)
            {
                var template = new UriTemplate(path, true);
                template.SetParameter(versionParam.Name, op.ApiVersion);
                path = template.Resolve();
                op.Parameters.Remove(versionParam);
            }

            return(new OperationPath20(path));
        }
Beispiel #13
0
        /// <summary>
        /// Parameterize the link to construct a URI.
        /// </summary>
        /// <param name="parameters">Parameters to substitute into the template, if any.</param>
        /// <returns>A constructed URI.</returns>
        /// <remarks>This method ensures that templates containing parameters cannot be accidentally
        /// used as URIs.</remarks>
        public string GetUri(IDictionary <string, object> parameters = null)
        {
            if (Template == null)
            {
                throw new InvalidOperationException("Attempted to process an empty URI template.");
            }

            var template = new UriTemplate(Template);

            if (parameters != null)
            {
                var missing = parameters.Select(p => p.Key).Except(template.GetParameterNames());
                if (missing.Any())
                {
                    throw new ArgumentException($"The URI template `{Template}` does not contain parameter: `{string.Join("`, `", missing)}`.");
                }

                foreach (var parameter in parameters)
                {
                    var value = parameter.Value is DateTime time
                        ? time.ToString("O")
                        : parameter.Value;

                    template.SetParameter(parameter.Key, value);
                }
            }

            return(template.Resolve());
        }
Beispiel #14
0
        private static async Task <IList <JToken> > SimpleSearchAsyncCore(HttpClient httpClient, string apiDomain, string serviceType, string realm, string rawSearchExpression)
        {
            IList <JToken> pages = new List <JToken>();

            httpClient.DefaultRequestHeaders.Remove("Accept");
            httpClient.DefaultRequestHeaders.Add("Accept", "application/hal+json");

            /// Check, whether simple search is supported:
            var    registryServiceVersion         = "0";
            string defaultSimpleSearchUriTemplate = $"https://{apiDomain}/apis/{serviceType};version=0;realm={realm}/searches/simple?search={{search}}{{&offset,limit,sort}}";
            string simpleSearchUriTemplate        = await PlatformTools.PlatformToolsAsync.FindInRegistry(httpClient, apiDomain, serviceType, registryServiceVersion, "search:simple-search", defaultSimpleSearchUriTemplate, realm);

            UriTemplate simpleSearchUrlTemplate = new UriTemplate(simpleSearchUriTemplate);

            simpleSearchUrlTemplate.SetParameter("search", rawSearchExpression);
            Uri simpleSearchResultPageUrl = new Uri(simpleSearchUrlTemplate.Resolve());

            httpClient.DefaultRequestHeaders.Remove("Accept");
            httpClient.DefaultRequestHeaders.Add("Accept", "application/hal+json");

            // Page through the result:
            do
            {
                using (HttpResponseMessage simpleSearchResultPage = await httpClient.GetAsync(simpleSearchResultPageUrl))
                {
                    HttpStatusCode simpleSearchStatus = simpleSearchResultPage.StatusCode;
                    if (HttpStatusCode.OK == simpleSearchStatus)
                    {
                        string rawSearchResult = await simpleSearchResultPage.Content.ReadAsStringAsync();

                        JObject searchResult    = JObject.Parse(rawSearchResult);
                        var     embeddedResults = searchResult.Properties().FirstOrDefault(it => "_embedded".Equals(it.Name));

                        if (null != embeddedResults)
                        {
                            pages.Add(embeddedResults);
                        }
                        else
                        {
                            Console.WriteLine($"No results found for search expression '{rawSearchExpression}'.");
                            return(pages);
                        }

                        // If we have more results, follow the next link and get the next page:
                        dynamic linkToNextPage = searchResult.SelectToken("_links.next");
                        simpleSearchResultPageUrl
                            = null != linkToNextPage
                                ? new Uri(linkToNextPage.href.ToString())
                                : null;
                    }
                    else
                    {
                        Console.WriteLine($"Search failed for search expression '{rawSearchExpression}'.");
                        return(pages);
                    }
                }
            }while (null != simpleSearchResultPageUrl);

            return(pages);
        }
Beispiel #15
0
        static string ResolveLink(ILinked entity, string link, IDictionary <string, object> parameters = null)
        {
            Link linkItem;

            if (!entity.Links.TryGetValue(link, out linkItem))
            {
                throw new NotSupportedException("The requested link isn't available.");
            }

            var expression = linkItem.GetUri();
            var template   = new UriTemplate(expression);

            if (parameters != null)
            {
                var missing = parameters.Select(p => p.Key).Except(template.GetParameterNames()).ToArray();
                if (missing.Any())
                {
                    throw new ArgumentException("The URI template '" + expression + "' does not contain parameter: " + string.Join(",", missing));
                }

                foreach (var parameter in parameters)
                {
                    var value = parameter.Value is DateTime
                        ? ((DateTime)parameter.Value).ToString("O")
                        : parameter.Value;

                    template.SetParameter(parameter.Key, value);
                }
            }

            return(template.Resolve());
        }
Beispiel #16
0
        public void FailureSamplesTest(string template, string[] results, TestSet.TestCase testCase)
        {
            var uriTemplate = new UriTemplate(template);

            foreach (var variable in testCase.TestSet.Variables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            string            result = null;
            ArgumentException aex    = null;

            try
            {
                result = uriTemplate.Resolve();
            }
            catch (ArgumentException ex)
            {
                aex = ex;
            }

            if (results[0] == "False")
            {
                Assert.NotNull(aex);
            }
            else
            {
                Assert.Contains(results, x => x == result);
            }
        }
        private static Uri ResolveDocumentationUri(ILinkObject link, string rel)
        {
            var template = new UriTemplate(link.Href.ToString());

            template.SetParameter("rel", rel);

            return(new Uri(template.Resolve()));
        }
Beispiel #18
0
 // This should be moved into URI Template library
 public static void ApplyParametersToTemplate(this UriTemplate uriTemplate, Dictionary <string, object> linkParameters)
 {
     foreach (var parameter in linkParameters)
     {
         if (parameter.Value is IEnumerable <string> )
         {
             uriTemplate.SetParameter(parameter.Key, (IEnumerable <string>)parameter.Value);
         }
         else if (parameter.Value is IDictionary <string, string> )
         {
             uriTemplate.SetParameter(parameter.Key, (IDictionary <string, string>)parameter.Value);
         }
         else
         {
             uriTemplate.SetParameter(parameter.Key, parameter.Value.ToString());
         }
     }
 }
Beispiel #19
0
        public void ShouldHandleEncodingAParametersThatIsAUriWithAUriAsAParameter()
        {
            var template = new UriTemplate("http://example.org/go{?uri}");

            template.SetParameter("uri", "http://example.org/?uri=http%3A%2F%2Fexample.org%2F");
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/go?uri=http%3A%2F%2Fexample.org%2F%3Furi%3Dhttp%253A%252F%252Fexample.org%252F", uriString);
        }
Beispiel #20
0
        public void ShouldHandleUriEncoding()
        {
            var template = new UriTemplate("http://example.org/sparql{?query}");

            template.SetParameter("query", "PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?book ?who WHERE { ?book dc:creator ?who }");
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/sparql?query=PREFIX%20dc%3A%20%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Felements%2F1.1%2F%3E%20SELECT%20%3Fbook%20%3Fwho%20WHERE%20%7B%20%3Fbook%20dc%3Acreator%20%3Fwho%20%7D", uriString);
        }
Beispiel #21
0
        public void LabelExpansionWithDotPrefixAndEmptyKeys()
        {
            var template = new UriTemplate("X{.empty_keys}");

            template.SetParameter("empty_keys", new Dictionary <string, string>());
            var uriString = template.Resolve();

            Assert.Equal("X", uriString);
        }
Beispiel #22
0
        internal static UriTemplate AddParameters(this UriTemplate uriTemplate, IDictionary <string, string> mappedVariables)
        {
            foreach (var variable in mappedVariables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            return(uriTemplate);
        }
Beispiel #23
0
 private void ApplyParameters(UriTemplate uriTemplate)
 {
     foreach (var parameter in _Parameters)
     {
         if (parameter.Value.Value is IEnumerable <string> )
         {
             uriTemplate.SetParameter(parameter.Key, (IEnumerable <string>)parameter.Value.Value);
         }
         else if (parameter.Value.Value is IDictionary <string, string> )
         {
             uriTemplate.SetParameter(parameter.Key, (IDictionary <string, string>)parameter.Value.Value);
         }
         else
         {
             uriTemplate.SetParameter(parameter.Key, parameter.Value.Value.ToString());
         }
     }
 }
Beispiel #24
0
        internal Uri ResolveTemplate(HalLink link, Dictionary <string, object> parameters)
        {
            var template = new UriTemplate(link.Href);

            foreach (var key in parameters.Keys)
            {
                template.SetParameter(key, parameters[key]);
            }
            return(new Uri(template.Resolve(), UriKind.Relative));
        }
Beispiel #25
0
        public void ShouldAllowUriTemplateWithQueryParamsWithOneValue()
        {
            var template = new UriTemplate("http://example.org/foo{?bar,baz}");

            template.SetParameter("baz", "yo");

            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo?baz=yo", uriString);
        }
Beispiel #26
0
        public void ReservedCharacterExpansion()
        {
            UriTemplate template = new UriTemplate("https://foo.com/{?format}");

            template.SetParameter("format", "application/vnd.foo+xml");

            var result = template.Resolve();

            Assert.Equal("https://foo.com/?format=application%2Fvnd.foo%2Bxml", result);
        }
Beispiel #27
0
        public void ShouldSupportUnicodeCharacters()
        {
            UriTemplate template = new UriTemplate("/lookup{?Stra%C3%9Fe}");

            template.SetParameter("Stra%C3%9Fe", "Grüner Weg");

            var result = template.Resolve();


            Assert.Equal("/lookup?Stra%C3%9Fe=Gr%C3%BCner%20Weg", result);
        }
        public static string ResolveTemplate(string uri, string templatedQuery, object queryParams)
        {
            var tmplt = new UriTemplate(uri + templatedQuery);

            foreach (var substitution in queryParams.GetType().GetProperties())
            {
                var value            = substitution.GetValue(queryParams, null);
                var substituionValue = value == null ? null : value.ToString();
                tmplt.SetParameter(substitution.Name, substituionValue);
            }
            return(tmplt.Resolve());
        }
Beispiel #29
0
        public void QueryParametersFromDictionary()
        {
            var template = new UriTemplate("http://example.org/customers{?query*}");

            template.SetParameter("query", new Dictionary <string, string>()
            {
                { "active", "true" },
                { "Country", "Brazil" }
            });
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/customers?active=true&Country=Brazil", uriString);
        }
Beispiel #30
0
        private static UriTemplate SetParameters(UriTemplate template, IEnumerable <KeyValuePair <string, string> > nameValues)
        {
            if (nameValues == null)
            {
                return(template);
            }

            foreach (var pair in nameValues)
            {
                template.SetParameter(pair.Key, pair.Value);
            }

            return(template);
        }