Resolve() public method

public Resolve ( ) : string
return string
示例#1
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);
 }
        public void ExtendedSamplesTest(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.True(results.Contains(result));
            }

        }
        // Disabled for the moment. [Theory, PropertyData("FailureSamples")]
        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;
            }

            Assert.NotNull(aex);


        }
 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);
 }
示例#5
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();
 }
        private static Uri ResolveDocumentationUri(ILinkObject link, string rel)
        {
            var template = new UriTemplate(link.Href.ToString());

            template.SetParameter("rel", rel);

            return new Uri(template.Resolve());
        }
 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);
 }
示例#8
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);
        }
示例#9
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);
 }
        private static string ResolveTemplateUrl(string href, Dictionary<string, string> values)
        {
            var template = new UriTemplate(href);

            foreach (var templateValue in values)
                template.SetParameter(templateValue.Key, templateValue.Value);

            return template.Resolve();
        }
        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);
        }
示例#12
0
        public void Query_param_with_list_array()
        {
            UriTemplate template = new UriTemplate("/foo/{foo}/baz{?haz}");
            template.SetParameter("foo", "1234");
            template.SetParameter("haz", new string[] { "foo", "bar" });

            string uri = template.Resolve();

            Assert.Equal("/foo/1234/baz?haz=foo,bar", uri);
        }
        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);
        }
示例#14
0
        public void PreserveReservedCharacterExpansion()
        {
            UriTemplate template = new UriTemplate("https://foo.com/?format={+format}");
            template.SetParameter("format", "application/vnd.foo+xml");

            var result = template.Resolve();

            Assert.Equal("https://foo.com/?format=application/vnd.foo+xml", result);

            var httpClient = new HttpClient();

            var response = httpClient.GetAsync("http://yahoo.com/foo%2Fbar").Result;
        }
        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);
        }
示例#16
0
        public void Can_generate_a_fully_qualified_path()
        {
            string expected = _baseUrl + "foo/1";
            const string routeName = "foo.show";
            const string routeTemplate = "foo/{id}";

            string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate)
                .Generate(routeName);
            var uriTemplate = new UriTemplate(template);
            uriTemplate.AddParameter("id", 1);

            string actual = uriTemplate.Resolve();
            Assert.Equal(expected, actual);
        }
示例#17
0
        public static string SubstituteParams(this string uriTemplateString, IDictionary<string, object> parameters)
        {
            var uriTemplate = new UriTemplate(uriTemplateString);

            foreach(var parameter in parameters) {
                var name = parameter.Key;
                var value = parameter.Value;

                var substituionValue = value == null ? null : value.ToString();
                uriTemplate.SetParameter(name, substituionValue);
            }

            return uriTemplate.Resolve();
        }
        public void SpecSamplesTest(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;
            result = uriTemplate.Resolve();

            Assert.True(results.Contains(result));
        }
示例#19
0
        public void Can_generate_two_optional_path_items_template()
        {
            string expected = _baseUrl + "foo/2";
            const string routeName = "foo.one.two";
            const string routeTemplate = "foo/{one}/{two}";

            string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate,
                routeDefaults: new { one = RouteParameter.Optional, two = RouteParameter.Optional })
                .Generate(routeName, new { two = 2 });
            var uriTemplate = new UriTemplate(template);

            uriTemplate.AddParameter("two", "2");

            string actual = uriTemplate.Resolve();
            Assert.Equal(expected, actual);
        }
示例#20
0
        public void ShouldThrowWhenExpressionIsNotClosed()
        {
            var result = string.Empty;
            try
            {
                var template = new UriTemplate("http://example.org/foo/{bar/baz/");
                var uriString = template.Resolve();
            }
            catch (ArgumentException ex)
            {

                result = ex.Message;
            }

            Assert.Equal("Malformed template : http://example.org/foo/{bar/baz/", result);
        }
示例#21
0
        public void Can_generate_a_path_with_anonymous_complex_route_properties()
        {
            string expected = _baseUrl + "foo/1?bar.abc=abc&bar.def=def";
            const string routeName = "foo.show";
            const string routeTemplate = "foo/{id}";

            string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate)
                .Generate(routeName, new { Id = 1, Bar = new { Abc = "abc", Def = "def" } });
            var uriTemplate = new UriTemplate(template);

            uriTemplate.AddParameters(new { id = 1 });
            uriTemplate.AddParameter("bar.abc", "abc");
            uriTemplate.AddParameter("bar.def", "def");

            string actual = uriTemplate.Resolve();
            Assert.Equal(expected, actual);
        }
        public string AsUriStr()
        {
            if (_path != null)
            {
                return _path;
            }

            if (_resource._uriTemplateStr != null)
            {
                var template = new UriTemplate(_resource._uriTemplateStr);
                var parameterNames = template.GetParameterNames();
                var parameterNameList = parameterNames as IList<string> ?? parameterNames.ToList();
                if (_pathElements != null)
                {
                    if (parameterNameList.Count() != _pathElements.Count())
                    {
                        throw new ArgumentException(String.Format("Mismatch between parameters in uriTemplate and supplied elements; uriTemplate={0}, elements={1}", template.Template, _pathElements));
                    }
                    int i = 0;
                    foreach (var parameterName in parameterNameList)
                    {
                        template.SetParameter(parameterName, _pathElements[i++]);
                    }
                }
                else
                {
                    var pathElementMapKeys = _pathElementMap.Keys;
                    var argsWithNoParams = pathElementMapKeys.Except(parameterNameList);
                    var paramsWithNoArgs = parameterNameList.Except(pathElementMapKeys);
                    if (argsWithNoParams.Any() || paramsWithNoArgs.Any())
                    {
                        throw new ArgumentException(String.Format("Mismatch between parameters in uriTemplate and supplied map; uriTemlpate={0}, map={1}", template.Template, _pathElementMap));
                    }
                    foreach (var parameterName in parameterNameList)
                    {
                        template.SetParameter(parameterName, _pathElementMap[parameterName]);
                    }
                }
                return PrefixBaseIfRequired(template.Resolve());
            }
            // else
            return PrefixBaseIfRequired(_resource._uriStr);
        }
        private OperationPath 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 OperationPath(path);
        }
        public static void Main(string[] args)
        {
            if (3 != args.Length)
            {
                Console.WriteLine($"Usage: {System.Reflection.Assembly.GetEntryAssembly().ManifestModule.Name} <apidomain> <httpbasicauthstring> <realm>");
            }
            else
            {
                string apiDomain           = args[0];
                string httpBasicAuthString = args[1];
                string realm = args[2];

                Uri upstreamServerUrl = new Uri($"https://{apiDomain}");
                using (CtmsRegistryClient registryClient = new CtmsRegistryClient(new OAuth2AuthorizationConnection(upstreamServerUrl, httpBasicAuthString)))
                {
                    const string      registeredLinkRelOrchestrationRoot = "orchestration:orchestration";
                    const string      orchestrationServiceType           = "avid.orchestration.ctc";
                    OrchestrationRoot orchestrationRootResource          = PlatformTools.PlatformToolsSDK.FindInRegistry <OrchestrationRoot>(registryClient, orchestrationServiceType, realm, registeredLinkRelOrchestrationRoot);

                    if (null != orchestrationRootResource)
                    {
                        const string registeredLinkRelOrchestrationProcessQuery = "orchestration:start-process";
                        Link         orchestrationProcessQueryLink = orchestrationRootResource.DiscoverLink(registeredLinkRelOrchestrationProcessQuery);
                        if (null != orchestrationProcessQueryLink)
                        {
                            Tavis.UriTemplates.UriTemplate orchestrationProcessQueryUriTemplate = new Tavis.UriTemplates.UriTemplate(orchestrationProcessQueryLink.Href);
                            orchestrationProcessQueryUriTemplate.SetParameter("offset", 0);
                            orchestrationProcessQueryUriTemplate.SetParameter("limit", 50);

                            string orchestrationProcessQueryUri = orchestrationProcessQueryUriTemplate.Resolve();

                            /// Create and start an export process with attachments:
                            string       now            = DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");
                            const string itemToExport   = "2016050410152760101291561460050569B02260000003692B00000D0D000005";
                            string       newProcessName = $"New process as to {DateTime.Now}".Replace(" ", "_").Replace(":", "_").Replace("-", "_");
                            string       newProcessId   = Guid.NewGuid().ToString();
                            JObject      processDescription
                                = new JObject(
                                      new JProperty("base",
                                                    new JObject(
                                                        new JProperty("id", newProcessId)
                                                        , new JProperty("type", "MAM_EXPORT_FILE")
                                                        , new JProperty("systemType", "interplay-mam")
                                                        , new JProperty("systemID", realm)
                                                        )
                                                    )
                                      , new JProperty("common",
                                                      new JObject(
                                                          new JProperty("name", newProcessName)
                                                          , new JProperty("creator", ".NET_Example")
                                                          , new JProperty("created", now)
                                                          , new JProperty("modifier", "Service-WorkflowEngine")
                                                          , new JProperty("modified", now)
                                                          )
                                                      )
                                      , new JProperty("attachments",
                                                      new JArray(
                                                          new JObject(
                                                              new JProperty("base",
                                                                            new JObject(
                                                                                new JProperty("id", itemToExport)
                                                                                , new JProperty("type", "Asset")
                                                                                , new JProperty("systemType", "interplay-mam")
                                                                                , new JProperty("systemID", realm)
                                                                                )
                                                                            )
                                                              )
                                                          )
                                                      )
                                      );

                            Process process = registryClient.SendHal <Process>(HttpMethod.Post, new Uri(orchestrationProcessQueryUri), processDescription);
                            Console.WriteLine($"Process: '{newProcessName}' - start initiated");
                            Console.WriteLine($"Lifecycle: {process.LifeCycle}");
                            /// Monitor the running process:
                            while ("running".Equals(process.LifeCycle) || "pending".Equals(process.LifeCycle))
                            {
                                Thread.Sleep(500);
                                // Directly get the process instance via its id:
                                const string registeredLinkRelOrchestrationGetProcess = "orchestration:process-by-id";
                                Link         orchestrationGetProcessLink = orchestrationRootResource.DiscoverLink(registeredLinkRelOrchestrationGetProcess);
                                Tavis.UriTemplates.UriTemplate orchestrationGetProcessUriTemplate = new Tavis.UriTemplates.UriTemplate(orchestrationGetProcessLink.Href);
                                orchestrationGetProcessUriTemplate.SetParameter("id", newProcessId);
                                process = registryClient.GetHalResource <Process>(new Uri(orchestrationGetProcessUriTemplate.Resolve()));
                                Console.WriteLine($"Lifecycle: {process.LifeCycle}");
                            }
                        }
                    }
                }
                Console.WriteLine("End");
            }
        }
        public void AddMultipleParametersToLink()
        {
            var template = new UriTemplate("http://localhost/api/{dataset}/customer{?foo,bar,baz}");

            template.AddParameters(new Dictionary<string, object>
            {
                {"foo", "bar"},
                {"baz", "99"},
                {"dataset", "bob"}
            });

            var uri = template.Resolve();

            Assert.Equal("http://localhost/api/bob/customer?foo=bar&baz=99", uri);
        }
        public void ShouldSupportUnicodeCharacters2()
        {
            UriTemplate template = new UriTemplate("{?assoc_special_chars*}");
            var dict = new Dictionary<string, string>
            {
                {"šö䟜ñꀣ¥‡ÑÒÓÔÕ", "Ö×ØÙÚàáâãäåæçÿ"}
            };
            template.SetParameter("assoc_special_chars", dict);

            var result = template.Resolve();


            Assert.Equal("?%C5%A1%C3%B6%C3%A4%C5%B8%C5%93%C3%B1%C3%AA%E2%82%AC%C2%A3%C2%A5%E2%80%A1%C3%91%C3%92%C3%93%C3%94%C3%95=%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%BF", result);

        }
        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 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);
 }
        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);
            
        }
 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);
 }
 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);
 }