예제 #1
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);
            }
        }
예제 #2
0
파일: Link.cs 프로젝트: larenelg/seq-api
        /// <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());
        }
예제 #3
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));
        }
예제 #4
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());
        }
예제 #5
0
        /// <summary>
        /// Binds the <see cref="UriTemplate" />
        /// to the specified <c>params</c> by position.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <param name="baseUri">The base URI.</param>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">template - The expected URI template is not here.</exception>
        /// <exception cref="FormatException"></exception>
        public static Uri BindByPosition(this UriTemplate template, Uri baseUri, params string[] values)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template", "The expected URI template is not here.");
            }

            var keys = template.GetParameterNames();

            for (int i = 0; i < keys.Count(); i++)
            {
                template.AddParameter(keys.ElementAt(i), values.ElementAtOrDefault(i));
            }

            var resolved = template.Resolve();

            if (baseUri != null)
            {
                return(new UriBuilder(baseUri).WithPath(resolved).Uri);
            }
            else
            {
                var isAbsolute = Uri.IsWellFormedUriString(resolved, UriKind.Absolute);
                var isRelative = Uri.IsWellFormedUriString(resolved, UriKind.Relative);
                if (!isAbsolute && !isRelative)
                {
                    throw new FormatException($"The resolved URI template, {resolved}, is in an unknown format.");
                }
                return(isAbsolute ? new Uri(resolved, UriKind.Absolute) : new Uri(resolved, UriKind.Relative));
            }
        }
        public async Task <ApiId[]> GetManagedApis()
        {
            // https://management.azure.com/subscriptions/83e6374a-dfa5-428b-82ef-eab6c6bdd383/providers/Microsoft.Web/locations/brazilsouth/managedApis?api-version=2015-08-01-preview"

            const string template   = "/subscriptions/{subscriptionId}/providers/Microsoft.Web/locations/{location}/managedApis/?api-version={apiVersion}";
            var          parameters = new Dictionary <string, string>();

            parameters["subscriptionId"] = subscriptionId;
            parameters["location"]       = location;
            parameters["apiVersion"]     = ApiVersion;


            var uriTemplate = new UriTemplate(template, true);

            // Add parameters one by one to avoid mismatch parameters count errors.
            foreach (var key in parameters)
            {
                uriTemplate = uriTemplate.AddParameter(key.Key, key.Value);
            }

            var resolvedUri = uriTemplate.Resolve();

            // Build complete URI.
            Uri url = new Uri(_managementEndpointUri, resolvedUri);

            var json = await SendAsync <JObject>(HttpMethod.Get, url);

            var apis = json["value"].ToObject <ArmEnvelope <JToken>[]>();

            return(Array.ConvertAll(apis, x => new ApiId
            {
                Id = x.Id,
                Name = x.Name
            }));
        }
        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()));
        }
예제 #8
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);
        }
        // TODO: Use continuation token.
        public virtual Uri CreateRequestUri(string template, NameValueCollection parameters = null, Query query = null, ContinuationToken continuationToken = null)
        {
            var uriTemplate = new UriTemplate(template, true);

            if (parameters != null)
            {
                // Add parameters one by one to avoid mismatch parameters count errors.
                foreach (var key in parameters.AllKeys)
                {
                    uriTemplate = uriTemplate.AddParameter(key, parameters[key]);
                }
            }

            var resolvedUri = uriTemplate.Resolve();

            // Build complete URI.
            Uri completeUri = new Uri(RuntimeEndpoint, resolvedUri);

            var uriBuilder = new UriBuilder(completeUri.AbsoluteUri)
            {
                Query = query.Coalesce().QueryString
            };

            return(uriBuilder.Uri);
        }
        private static Uri ResolveDocumentationUri(ILinkObject link, string rel)
        {
            var template = new UriTemplate(link.Href.ToString());

            template.SetParameter("rel", rel);

            return(new Uri(template.Resolve()));
        }
예제 #11
0
        public void QueryParamsWithoutValuesTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary <string, object>());

            Assert.AreEqual("http://example.com/foo", actual);
        }
예제 #12
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();
        }
예제 #13
0
        public static void SpecTest(TestCase testCase)
        {
            Assume.That(!testCase.IsInvalid);
            var uriTemplate = new UriTemplate(testCase.Template);
            var uri         = uriTemplate.Resolve(testCase.Suite.Variables);

            Assert.Contains(uri, testCase.Expecteds);
        }
예제 #14
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);
        }
예제 #15
0
        public void ShouldAllowUriTemplateWithQueryParamsButNoValues()
        {
            var template = new UriTemplate("http://example.org/foo{?bar,baz}");
            //template.SetParameter("bar", "yo");
            //template.SetParameter("blar", "yuck");
            var uriString = template.Resolve();

            Assert.Equal("http://example.org/foo", uriString);
        }
예제 #16
0
        public void ShouldAllowUriTemplateWithPathSegmentParameter()
        {
            var template = new UriTemplate("http://example.org/foo/{bar}/baz");

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

            Assert.Equal("http://example.org/foo/yo/baz", uriString);
        }
예제 #17
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);
        }
예제 #18
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);
        }
예제 #19
0
        public void IntValueIsNotSupported_UseStringInstead()
        {
            var template = new UriTemplate("http://example.com/{guid}/{int}");

            var ex = Assert.Throws <UriTemplateException>(() => template.Resolve(new Dictionary <string, object> {
                { "int", 42 }
            }));

            Assert.That(ex.Message, Does.Contain("Invalid value type of variable \"System.Int32\". Expected: string or IEnumerable<string> or IDictionary<string, string>."));
        }
예제 #20
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);
        }
예제 #21
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));
        }
예제 #22
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);
        }
예제 #23
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);
        }
예제 #24
0
        public void QueryParamsWithOneValueTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary <string, object>()
            {
                { "q1", "abc" }
            });

            Assert.AreEqual("http://example.com/foo?q1=abc", actual);
        }
예제 #25
0
        public void PathSegmentTest()
        {
            var template = new UriTemplate("http://example.com/{path}");

            var actual = template.Resolve(new Dictionary <string, object>
            {
                { "path", "foo" }
            });

            Assert.AreEqual("http://example.com/foo", actual);
        }
예제 #26
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);
        }
예제 #27
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);
        }
예제 #28
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);
        }
예제 #29
0
        public void QueryParamsWithMultipleValuesTest()
        {
            var template = new UriTemplate("http://example.com/foo{?q1,q2}");

            var actual = template.Resolve(new Dictionary <string, object>
            {
                { "q1", new string[] { "abc", "def", "ghi" } },
                { "q2", "10" }
            });

            Assert.AreEqual("http://example.com/foo?q1=abc,def,ghi&q2=10", actual);
        }
예제 #30
0
        public void MultiplePathSegmentTest()
        {
            var template = new UriTemplate("http://example.com/{path1}/{path2}");

            var actual = template.Resolve(new Dictionary <string, object>
            {
                { "path1", "foo" },
                { "path2", "bar" }
            });

            Assert.AreEqual("http://example.com/foo/bar", actual);
        }